Skip to content
Verified contractExactMIT

PBS1WrapperV2

Address0x7a481f00b0eeea0bfe90bd15057786fab7b24a08
Balance

0 ETH

 

Transactions

5

 

Compiler

solc 0.8.25

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.25+commit.b61c2a91
Language
solidity
Optimization
Yes, 10 runs
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,389,573
Creation transaction
0xe985be087f…0b467985ce

contracts/PBS1WrapperV2.sol

// SPDX-License-Identifier: MIT
pragma solidity =0.8.25;

/* ============================================================================
   PBS1WrapperV2 - Patronage Bundle Standard, receipt + custody wrapper
   STATUS: DRAFT, written to MARKETPLACE.md (design spec, DRAFT).
   COMPILES: verified with solc 0.8.25 - legacy pipeline (with or without
   optimizer) AND via IR, Nov 10 2026.
   DEPLOY (Remix, Nov 10 2026): legacy pipeline + optimizer 100 runs stays
   under the EIP-170 limit ONLY with short revert codes (P01..P37).
   Long strings push it to ~25.3KB, over the 24.576KB ceiling. via IR
   also fits but Remix 2.6.13 hides the toggle - keep it simple.
   REHEARSED: Foundry mainnet-fork rehearsal Nov 10 2026 - wrap, scrape
   split, receipt-transfer auth, and permissionless renew all verified.
   Vault engine fork-tested 9/9 same day (both wtnUSDC and wsnUSDC:
   deposit/claim/compound mechanics + wrapper end-to-end).
   NOT DEPLOYED. NOT AUDITED. Rehearse on a mainnet FORK before any
   live use. Do not point this at valuable stakes until reviewed.

   REVERT CODE MAP (full names, for Etherscan debugging):
   P01 NOT_OWNER, P02 ZERO_ADDR, P03 NO_RECEIPT, P04 NOT_AUTH,
   P05 TRANSFER_FAIL, P06 REENTRANCY, P07 NOT_ACTIVE, P08 LOCK_TOO_SHORT,
   P09 PATRON_TOO_BIG, P10 TOPUP_TOO_BIG, P11 BAD_CATEGORY,
   P12 CATEGORY_EXISTS, P13 EMPTY_LABEL, P14 LABEL_TOO_LONG,
   P15 MINT_SCAN, P16 NOTHING_TO_SCRAPE, P17 RENEWAL_OFF,
   P18 SET_MODE_OFF, P19 NOT_MATURE, P20 BAL_MATH, P21 PRINCIPAL_SHORT,
   P22 RELEASE_PENDING, P23 NO_PENDING_RELEASE, P24 RELEASE_LOCKED,
   P25 ZERO_TREASURY, P26 ZERO_PRICE, P27 DIVERT_CAP, P28 FEE_CAP,
   P29 BAD_VAULT, P30 VAULT_SET, P31 NO_VAULT, P32 SCRAPE_NOT_AUTH,
   P33 ZERO, P34 ALREADY

   Architecture (verified against WISE core StakingToken 0.7.6 and
   WiseStakingNFT 0.8.25 source, Nov 10 2026):
   - Core WISE stakes are NOT transferable; transferability lives only in
     WiseStakingNFT Signature cards. Every bundle wraps a Signature card.
   - Scrape and burn on the card are card-owner-only, so this wrapper, as
     the card owner, is the only executor. The renewal caller needs no key
     to anything: renew() is permissionless and executes from wrapper funds.
   - Renewal is BURN + REMINT (no native re-stake exists). Renewal mints a
     NEW card tokenId; the bundle's cardId is updated to the live one.
   - INVARIANT: pot funds are held HERE, never in WiseStakingNFT - its
     burn() sweeps that contract's ENTIRE WISE balance to the caller.

   SCRAPE AUTHORIZATION: pre-maturity, only the receipt owner or an approved
   operator may scrape - mid-term scraping incurs a share penalty in the
   core contract, so open triggering would be a griefing vector. Post-
   maturity anyone may scrape (penalty-free; keeper/cleanup friendly).

   SCRAPE-DAY CAP (fixed Nov 10, 2026): the core's scrapeInterest divides
   by each day's inflationAmount. Requesting days beyond the last WRITTEN
   daily snapshot divides by zero and the core ASSERTS (InvalidFEOpcode,
   no revert message) - it cannot be caught, only prevented. scrape()
   caps scrapeDays at currentWiseDay - accrualPointer, where the pointer
   is the stake's stored scrapeDay once one exists, otherwise its
   startDay. Fork-verified: a fresh stake stores scrapeDay = 0 AND starts
   at currentWiseDay + 1, so the stored zero must NOT be read as the
   pointer. Oversized requests clamp silently and pay what exists;
   a zero cap reverts P16 before touching the core.

   EMERGENCY RELEASE (added Nov 10, 2026): custody is never a one-way
   door. requestRelease + releaseCard unwrap the card back to the
   receipt owner after a fixed 7-day delay (constant, not owner-
   configurable); the pot returns with it and the receipt is burned.
   A pending release blocks renew() and close() so the card cannot
   change identity mid-escape. Fork-verified Nov 10 2026.

   CATEGORIES + PBS-ART (added Nov 10, 2026): every bundle carries a
   category (Security, Music, Donor, Loyalty, Tithe, Art, Merchant,
   Business, ENS at launch) from an owner-curated registry -
   addCategory() extends it on-chain, no redeploy. Category is set at
   creation, permanent, and keys the receipt's art: tokenURI =
   baseURI + CATEGORY + / + bundleId + ".json". The art set per
   category lives OFF-CHAIN (EIP-170 size ceiling rules out on-chain
   SVG); the Wise Stake Consulting owl is the identity mark (PBS-ART
   naming rule, Nov 10 2026). Each bundle also stores a short LABEL
   chosen at creation (e.g. the ENS name an ENS bundle pays for),
   permanent, readable on-chain for metadata renderers.

   VAULT ENGINE (added Nov 10, 2026): bundles may be backed by a Wise RWA
   vault position (ERC-20 receipt token, e.g. wtnUSDC), a Signature card,
   or both. See the VAULT ENGINE section near the end. Vault-backed
   bundles resolve tokenURI to baseURI + VAULT/ + id + .json and share
   ONE vault emblem image (Ramon decision, Nov 10 2026); category stays
   on-chain as a trait.

   CARD ID RESOLUTION (fixed Nov 10, 2026): Signature Stakes token IDs are
   NOT sequential (confirmed live Nov 5, 2026: card #59 minted on mainnet).
   The new card ID after a mint is resolved by diffing walletOfOwner() of
   the wrapper before and after the mint - NEVER by guessing totalSupply().

   Receipt deviations from full ERC-721: no onERC721Received hook (cards are
   pulled via transferFrom, receipts are minted only to EOAs/verified
   callers). Deliberate, to keep this single-file Etherscan-verifiable.
   ============================================================================ */

interface IWiseToken {
    function balanceOf(address) external view returns (uint256);
    function transfer(address to, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
    function approve(address spender, uint256 amount) external returns (bool);
}

interface IWiseCore {
    /// Staker in the core ledger is the WiseStakingNFT contract address.
    function currentWiseDay() external view returns (uint64);
    function checkStakeByID(address staker, bytes16 stakeID)
        external
        view
        returns (
            uint256 startDay,
            uint256 lockDays,
            uint256 finalDay,
            uint256 closeDay,
            uint256 scrapeDay,
            uint256 stakedAmount,
            uint256 stakesShares,
            uint256 rewardAmount,
            uint256 penaltyAmount,
            bool isActive,
            bool isMature
        );
}

interface IWiseStakingNFT {
    function mint(uint256 _amount, uint64 _lockDays, address _referrer) external;
    function burn(uint256 _tokenId) external;
    function scrapeInterest(uint256 _tokenId, uint64 _scrapeDays) external returns (uint256);
    function NFTStake(uint256 _tokenId) external view returns (bytes16);
    function ownerOf(uint256 _tokenId) external view returns (address);
    function transferFrom(address _from, address _to, uint256 _tokenId) external;
    function totalSupply() external view returns (uint256);
    function walletOfOwner(address _owner) external view returns (uint256[] memory);
}

contract PBS1WrapperV2 {
    // ------------------------------------------------------------------
    // Roles / constants
    // ------------------------------------------------------------------

    address public owner;

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

    modifier onlyOwner() {
        require(msg.sender == owner, "P01");
        _;
    }

    // ------------------------------------------------------------------
    // Receipt NFT (minimal ERC-721). tokenId == bundleId.
    // ------------------------------------------------------------------

    string public constant name = "Patronage Bundle Standard - Receipt";
    string public constant symbol = "PBS-RCPT";

    uint256 private nextId = 1;
    mapping(uint256 => address) private tokenOwner;
    mapping(address => uint256) private balances;
    mapping(uint256 => address) private tokenApprovals;
    mapping(address => mapping(address => bool)) private operators;

    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
    event Approval(address indexed holder, address indexed spender, uint256 indexed tokenId);
    event ApprovalForAll(address indexed holder, address indexed operator, bool approved);

    function balanceOf(address a) external view returns (uint256) {
        require(a != address(0), "P02");
        return balances[a];
    }

    function ownerOf(uint256 id) public view returns (address) {
        require(tokenOwner[id] != address(0), "P03");
        return tokenOwner[id];
    }

    function totalSupply() external view returns (uint256) {
        return nextId - 1;
    }

    function getApproved(uint256 id) external view returns (address) {
        return tokenApprovals[id];
    }

    function isApprovedForAll(address holder, address op) external view returns (bool) {
        return operators[holder][op];
    }

    function approve(address spender, uint256 id) external {
        address holder = ownerOf(id);
        require(msg.sender == holder || operators[holder][msg.sender], "P04");
        tokenApprovals[id] = spender;
        emit Approval(holder, spender, id);
    }

    function setApprovalForAll(address op, bool ok) external {
        operators[msg.sender][op] = ok;
        emit ApprovalForAll(msg.sender, op, ok);
    }

    function transferFrom(address from, address to, uint256 id) public {
        address holder = ownerOf(id);
        bool authorized =
            msg.sender == holder ||
            tokenApprovals[id] == msg.sender ||
            operators[holder][msg.sender];
        require(authorized, "P04");
        require(to != address(0), "P02");

        delete tokenApprovals[id];
        balances[from] -= 1;
        balances[to] += 1;
        tokenOwner[id] = to;
        emit Transfer(from, to, id);
    }

    function _mintReceipt(address to) internal returns (uint256 id) {
        id = nextId;
        nextId = nextId + 1;
        tokenOwner[id] = to;
        balances[to] += 1;
        emit Transfer(address(0), to, id);
    }

    function _burnReceipt(uint256 id) internal {
        address holder = ownerOf(id);
        balances[holder] -= 1;
        delete tokenOwner[id];
        delete tokenApprovals[id];
        emit Transfer(holder, address(0), id);
    }

    /// ERC-721 receiver hook. REQUIRED: WiseStakingNFT uses _safeMint, so
    /// createBundle()/renew() revert on mint-to-contract without this
    /// (found in Foundry mainnet-fork rehearsal, Nov 10 2026).
    function onERC721Received(address, address, uint256, bytes calldata)
        external
        pure
        returns (bytes4)
    {
        return this.onERC721Received.selector;
    }

    // ------------------------------------------------------------------
    // Bundle state
    // ------------------------------------------------------------------

    enum Mode { Off, Restake, RestakeTopUp }

    struct Bundle {
        uint256 cardId;      // CURRENT WiseStakingNFT tokenId (changes on renewal); 0 = vault-only bundle
        address patron;      // permanent patronage beneficiary (address(0) = none)
        uint16 patronBps;    // patron share of scraped yield, of post-fee remainder
        Mode mode;           // maturity behavior
        uint16 topUpBps;     // RestakeTopUp: pct of pot added to the re-stake
        uint256 potBalance;  // renewal pot, WISE-wei, bound to this bundle
        bool active;
    }

    mapping(uint256 => Bundle) public bundles;

    IWiseToken public immutable wise;
    IWiseCore public immutable wiseCore;
    IWiseStakingNFT public immutable card;

    // Fee / splits
    address public treasury;            // receives WSC fee
    uint16 public feeBps = 100;         // 1% of scraped yield, cap 500 (5%)
    uint16 public constant FEE_CAP_BPS = 500;
    uint16 public constant PATRON_CAP_BPS = 5000;

    // Renewal pot (lean pot: gas coverage only; the service fee is the
    // standard feeBps taken on the matured interest at renewal time)
    uint256 public gasTargetWei;        // ETH gas coverage target
    uint256 public wisePricePerEth;     // WISE-wei per ETH-wei, owner-updated
    uint16 public potDivertBps = 2000;  // pct of owner share diverted while pot below target
    uint16 public constant POT_DIVERT_CAP_BPS = 5000;

    // Renewal referral attribution: renew() accepts any valid EOA referrer;
    // address(0) resolves to this default (WSC rail for now).
    address public defaultReferrer;

    // Bundle categories (PBS-ART art families). Owner-curated registry:
    // seeded with the launch nine, extensible on-chain as new bundle
    // kinds are invented - a closed enum would force a redeploy per new
    // category. A bundle's category is set at creation and permanent;
    // it keys the receipt's art in the off-chain metadata set.
    bytes32[] public categoryList;
    mapping(bytes32 => bool) public isCategory;
    mapping(uint256 => bytes32) public bundleCategory;
    string public baseURI; // off-chain metadata root, owner-updated

    // Bundle label: a short human name chosen at creation (e.g. the ENS
    // name an ENS-category bundle is set up to pay for, "denise.eth").
    // Set at creation, permanent, immutable like the category. Surfaces
    // in off-chain metadata attributes; kept on-chain so any metadata
    // renderer can read it trustlessly.
    mapping(uint256 => string) public bundleLabel;

    function addCategory(bytes32 label) external onlyOwner {
        require(label[0] != 0, "P13");
        require(!isCategory[label], "P12");
        isCategory[label] = true;
        categoryList.push(label);
    }

    function categoryCount() external view returns (uint256) {
        return categoryList.length;
    }

    function setBaseURI(string calldata uri) external onlyOwner {
        baseURI = uri;
    }

    /// Right-padded bytes32 label -> its string up to the first zero.
    function _label(bytes32 b) internal pure returns (string memory) {
        uint256 n = 0;
        while (n < 32 && b[n] != 0) n++;
        bytes memory s = new bytes(n);
        for (uint256 j = 0; j < n; j++) s[j] = b[j];
        return string(s);
    }

    function _uint2str(uint256 v) internal pure returns (string memory) {
        if (v == 0) return "0";
        uint256 len;
        for (uint256 t = v; t > 0; t /= 10) len++;
        bytes memory s = new bytes(len);
        while (v > 0) {
            s[--len] = bytes1(uint8(48 + (v % 10)));
            v /= 10;
        }
        return string(s);
    }

    /// Receipt metadata: baseURI + CATEGORY + / + bundleId + ".json"
    /// (e.g. https://wisestake.consulting/pbs-art/MUSIC/12.json). The
    /// .json suffix keeps GitHub Pages serving content-type application/
    /// json (extensionless files serve as octet-stream, which some
    /// marketplaces reject). Art set per category lives off-chain.
    /// VAULT BUNDLES (Nov 10 2026): a bundle holding a vault position
    /// resolves instead to baseURI + VAULT/ + id + .json and shows the
    /// single vault emblem image; the category stays on-chain
    /// (bundleCategory) and surfaces as a marketplace trait. attachVault
    /// can flip a bundle's URI from its category folder to VAULT/.
    function tokenURI(uint256 id) external view returns (string memory) {
        require(tokenOwner[id] != address(0), "P03");
        if (bundleVault[id] != address(0)) {
            return string(abi.encodePacked(baseURI, "VAULT/", _uint2str(id), ".json"));
        }
        return string(abi.encodePacked(baseURI, _label(bundleCategory[id]), "/", _uint2str(id), ".json"));
    }

    uint64 public constant MIN_RENEWAL_LOCK_DAYS = 366;

    event BundleCreated(uint256 indexed bundleId, address indexed creator, uint256 cardId, address patron, uint16 patronBps, Mode mode, uint16 topUpBps, bytes32 category, string label);
    event Scraped(uint256 indexed bundleId, uint256 amount, uint256 fee, uint256 patronAmt, uint256 toPot, uint256 toOwner, address caller);
    event ModeChanged(uint256 indexed bundleId, Mode mode, uint16 topUpBps);
    event Renewed(uint256 indexed bundleId, uint256 newCardId, uint256 restakedAmount, uint256 topUpUsed, address referrer, address caller);
    event Closed(uint256 indexed bundleId, uint256 principalToOwner, uint256 potToOwner, address caller);
    event PotFunded(uint256 indexed bundleId, uint256 amount, uint256 potBalance);

    modifier active(uint256 id) {
        require(bundles[id].active, "P07");
        _;
    }

    modifier guard() {
        require(!locked, "P06");
        locked = true;
        _;
        locked = false;
    }

    bool private locked;

    // Constructor params carry a trailing underscore so they can NEVER
    // shadow the immutable state variables they initialize (compile error
    // caught in first Remix compile, Nov 10 2026).
    constructor(
        address wiseToken_,
        address wiseCore_,
        address wiseStakingNFT_,
        address treasury_,
        address defaultReferrer_,
        uint256 gasTargetWei_,
        uint256 wisePricePerEth_
    ) {
        require(treasury_ != address(0), "P25");
        owner = msg.sender;
        emit OwnershipTransferred(address(0), msg.sender);
        wise = IWiseToken(wiseToken_);
        wiseCore = IWiseCore(wiseCore_);
        card = IWiseStakingNFT(wiseStakingNFT_);
        treasury = treasury_;
        defaultReferrer = defaultReferrer_;
        gasTargetWei = gasTargetWei_;
        wisePricePerEth = wisePricePerEth_;

        // Launch categories (PBS-ART): Security, Music, Donor, Loyalty,
        // Tithe, Art, Merchant, Business, ENS. addCategory() extends the
        // registry. BUSINESS = the processing-fees/loyalty business-owner
        // bundle (Ramon, Nov 10 2026); MERCHANT and LOYALTY can share art.
        bytes32[9] memory seeds = [
            bytes32("SECURITY"), bytes32("MUSIC"), bytes32("DONOR"),
            bytes32("LOYALTY"), bytes32("TITHE"), bytes32("ART"),
            bytes32("MERCHANT"), bytes32("BUSINESS"), bytes32("ENS")
        ];
        for (uint256 j = 0; j < 9; j++) {
            isCategory[seeds[j]] = true;
            categoryList.push(seeds[j]);
        }
    }

    // ------------------------------------------------------------------
    // Card mint helper: resolve the NEW card ID by wallet diff
    // ------------------------------------------------------------------

    /// Signature Stakes IDs are NOT sequential. Snapshot the wrapper's
    /// walletOfOwner before and after the mint; the new ID is the single
    /// entry that appears only afterward. NEVER guess from totalSupply().
    function _mintCard(uint256 amount, uint64 lockDays, address ref)
        internal
        returns (uint256 newCardId)
    {
        uint256[] memory before = card.walletOfOwner(address(this));
        card.mint(amount, lockDays, ref);
        uint256[] memory afterList = card.walletOfOwner(address(this));

        require(afterList.length == before.length + 1, "P15");
        uint256 found;
        for (uint256 j = 0; j < afterList.length; j++) {
            bool seen;
            for (uint256 k = 0; k < before.length; k++) {
                if (afterList[j] == before[k]) {
                    seen = true;
                    break;
                }
            }
            if (!seen) {
                newCardId = afterList[j];
                found++;
            }
        }
        require(found == 1, "P15");
    }

    // ------------------------------------------------------------------
    // Stake state helper: collapses the 11-field core read into 4 slots.
    // Keeps the main functions under the EVM stack limit.
    // ------------------------------------------------------------------

    function _stakeState(uint256 cardId)
        internal
        view
        returns (uint256 stakedAmount, uint256 rewardAmount, bool isActive, bool isMature)
    {
        bytes16 stakeId = card.NFTStake(cardId);
        (, , , , , stakedAmount, , rewardAmount, , isActive, isMature) =
            wiseCore.checkStakeByID(address(card), stakeId);
    }

    // ------------------------------------------------------------------
    // Scrape-day cap
    // ------------------------------------------------------------------

    /// Safe maximum for scrapeDays on this card. The core processes days
    /// [pointer, pointer + k) and divides by each day's inflationAmount;
    /// snapshots exist through currentWiseDay - 1, so k <= currentWiseDay
    /// - pointer. The pointer is the stake's stored scrapeDay once one
    /// exists, otherwise its startDay. A fresh stake stores scrapeDay = 0
    /// AND starts at currentWiseDay + 1 - its stored zero is NOT its
    /// pointer (fork-verified Nov 10 2026: reading the zero as the
    /// pointer let an oversized request through to the core's assert).
    /// Over-conservative only when the protocol clock lags the timestamp
    /// (a same-tx clock advance adds usable days this view read cannot
    /// see); never unsafe.
    function _capScrapeDays(uint256 cardId, uint64 scrapeDays)
        internal
        view
        returns (uint64)
    {
        bytes16 sid = card.NFTStake(cardId);
        (uint256 startDay, , , , uint256 sDay, , , , , , ) =
            wiseCore.checkStakeByID(address(card), sid);
        uint256 pointer = sDay > 0 ? sDay : startDay;
        uint256 c = wiseCore.currentWiseDay();
        if (c <= pointer) return 0;
        uint256 maxDays = c - pointer;
        if (scrapeDays <= maxDays) return scrapeDays;
        return uint64(maxDays);
    }

    // ------------------------------------------------------------------
    // Matured harvest: burn the card, split the interest, return principal.
    // Shared by renew() and close(); keeps both under the stack limit.
    // ------------------------------------------------------------------

    function _harvestMatured(uint256 id, uint256 cardId)
        internal
        returns (uint256 principal)
    {
        (uint256 stakedAmount, uint256 rewardAmount, bool isActive, bool isMature) =
            _stakeState(cardId);
        require(isActive && isMature, "P19");

        uint256 received = wise.balanceOf(address(this));
        card.burn(cardId); // principal + matured interest come to wrapper
        received = wise.balanceOf(address(this)) - received;

        // Matured interest flows through the normal split; principal is the
        // renewal capital and is never priced or converted.
        require(received >= rewardAmount, "P20");
        _distribute(id, rewardAmount);

        principal = received - rewardAmount;
        require(principal + 1000 >= stakedAmount, "P21");
    }

    // ------------------------------------------------------------------
    // Creation
    // ------------------------------------------------------------------

    /// Create a bundle by staking WISE into a fresh Signature card.
    /// Caller must have approved this wrapper for WISE.
    function createBundle(
        uint256 amount,
        uint64 lockDays,
        address patron,
        uint16 patronBps,
        Mode mode,
        uint16 topUpBps,
        address referrer,
        bytes32 category,
        string calldata label
    )
        external
        guard
        returns (uint256 id)
    {
        require(lockDays >= MIN_RENEWAL_LOCK_DAYS, "P08");
        require(patronBps <= PATRON_CAP_BPS, "P09");
        require(topUpBps <= 10000, "P10");
        require(isCategory[category], "P11");
        require(bytes(label).length <= 64, "P14");

        wise.transferFrom(msg.sender, address(this), amount);
        wise.approve(address(card), type(uint256).max);

        address ref = referrer == address(0) ? defaultReferrer : referrer;
        uint256 newCardId = _mintCard(amount, lockDays, ref);

        id = _mintReceipt(msg.sender);
        Bundle storage b = bundles[id];
        b.cardId = newCardId;
        b.patron = patron;
        b.patronBps = patronBps;
        b.mode = mode;
        b.topUpBps = topUpBps;
        b.active = true;
        bundleCategory[id] = category;
        bundleLabel[id] = label;

        emit BundleCreated(id, msg.sender, newCardId, patron, patronBps, mode, topUpBps, category, label);
    }

    /// Wrap an existing Signature card the caller already owns. The card is
    /// pulled into wrapper custody; the receipt holder controls it from then
    /// on. Plain transferFrom is used (no receiver hook by design).
    function wrapCard(
        uint256 cardId,
        address patron,
        uint16 patronBps,
        Mode mode,
        uint16 topUpBps,
        bytes32 category,
        string calldata label
    )
        external
        guard
        returns (uint256 id)
    {
        require(patronBps <= PATRON_CAP_BPS, "P09");
        require(topUpBps <= 10000, "P10");
        require(isCategory[category], "P11");
        require(bytes(label).length <= 64, "P14");
        require(card.ownerOf(cardId) == msg.sender, "P04");

        (, , bool isActiveW, ) = _stakeState(cardId);
        require(isActiveW, "P19");

        card.transferFrom(msg.sender, address(this), cardId);

        id = _mintReceipt(msg.sender);
        Bundle storage b = bundles[id];
        b.cardId = cardId;
        b.patron = patron;
        b.patronBps = patronBps;
        b.mode = mode;
        b.topUpBps = topUpBps;
        b.active = true;
        bundleCategory[id] = category;
        bundleLabel[id] = label;

        emit BundleCreated(id, msg.sender, cardId, patron, patronBps, mode, topUpBps, category, label);
    }

    // ------------------------------------------------------------------
    // Owner controls
    // ------------------------------------------------------------------

    function changeMode(uint256 id, Mode mode, uint16 topUpBps)
        external
        active(id)
    {
        require(ownerOf(id) == msg.sender, "P04");
        require(topUpBps <= 10000, "P10");
        bundles[id].mode = mode;
        bundles[id].topUpBps = topUpBps;
        emit ModeChanged(id, mode, topUpBps);
    }

    // ------------------------------------------------------------------
    // Scraping - owner/operator pre-maturity, anyone post-maturity
    // ------------------------------------------------------------------

    /// Pre-maturity: receipt owner or approved operator only (mid-term
    /// scraping carries a core-contract share penalty; open triggering would
    /// let a griefer burn gas to shrink the bundle's future yield).
    /// Post-maturity: anyone (penalty-free harvest; keeper-friendly).
    /// In all cases the caller receives nothing - the split pays every party
    /// inside the call.
    /// scrapeDays is capped at the written-snapshot range (see
    /// _capScrapeDays); oversized requests clamp silently and pay what
    /// exists, keeping keepers and UIs safe from the core's assert.
    function scrape(uint256 id, uint64 scrapeDays) external active(id) guard {
        Bundle storage b = bundles[id];

        (, , bool isActiveS, bool isMatureS) = _stakeState(b.cardId);
        require(isActiveS, "P19");

        if (!isMatureS) {
            address holder = ownerOf(id);
            bool authorized =
                msg.sender == holder ||
                tokenApprovals[id] == msg.sender ||
                operators[holder][msg.sender];
            require(authorized, "P32");
        }

        scrapeDays = _capScrapeDays(b.cardId, scrapeDays);
        require(scrapeDays > 0, "P16");

        uint256 amount = card.scrapeInterest(b.cardId, scrapeDays);
        require(amount > 0, "P16");

        (uint256 fee, uint256 patronAmt, uint256 toPot, uint256 toOwner) = _distribute(id, amount);
        emit Scraped(id, amount, fee, patronAmt, toPot, toOwner, msg.sender);
    }

    // ------------------------------------------------------------------
    // Renewal - permissionless burn + remint
    // ------------------------------------------------------------------

    function renew(uint256 id, uint64 lockDays, address referrer)
        external
        active(id)
        guard
    {
        Bundle storage b = bundles[id];
        require(b.mode != Mode.Off, "P17");
        require(lockDays >= MIN_RENEWAL_LOCK_DAYS, "P08");
        require(releaseAt[id] == 0, "P22");

        uint256 principal = _harvestMatured(id, b.cardId);

        // Optional top-up from the pot grows the next card.
        uint256 topUp = 0;
        if (b.mode == Mode.RestakeTopUp && b.topUpBps > 0) {
            topUp = (b.potBalance * b.topUpBps) / 10000;
            b.potBalance -= topUp;
        }

        wise.approve(address(card), type(uint256).max);
        address ref = referrer == address(0) ? defaultReferrer : referrer;
        uint256 newCardId = _mintCard(principal + topUp, lockDays, ref);

        b.cardId = newCardId;
        emit Renewed(id, newCardId, principal + topUp, topUp, ref, msg.sender);
    }

    /// Close a matured OFF-mode bundle: interest via the split, principal and
    /// pot to the receipt owner. Owner flips mode to Off first if needed.
    function close(uint256 id) external active(id) guard {
        Bundle storage b = bundles[id];
        require(ownerOf(id) == msg.sender, "P04");
        require(b.mode == Mode.Off, "P18");
        require(releaseAt[id] == 0, "P22");

        uint256 principal = _harvestMatured(id, b.cardId);

        uint256 pot = b.potBalance;
        b.potBalance = 0;
        b.active = false;

        address recipient = ownerOf(id);
        require(wise.transfer(recipient, principal), "P05");
        if (pot > 0) {
            require(wise.transfer(recipient, pot), "P05");
        }
        emit Closed(id, principal, pot, msg.sender);
    }

    // ------------------------------------------------------------------
    // Emergency release: unwrap the card back to the receipt owner
    // ------------------------------------------------------------------

    // Escape hatch so custody is never a one-way door. Two steps, patron
    // only: requestRelease starts a fixed 7-day delay, releaseCard (after
    // the delay) hands the card NFT and the pot back and retires the
    // bundle. The stake itself is untouched - the card IS the core stake;
    // transferring it changes custody only. The delay is a fixed constant,
    // deliberately NOT owner-configurable: the point is that no one,
    // including this contract's owner, can rush a bundle out of custody.
    uint64 public constant RELEASE_DELAY = 7 days;
    mapping(uint256 => uint256) public releaseAt;

    event ReleaseRequested(uint256 indexed bundleId, uint256 cardId, uint256 releaseAt);
    event ReleaseCancelled(uint256 indexed bundleId);
    event Released(uint256 indexed bundleId, uint256 cardId, address to, uint256 potReturned);

    function requestRelease(uint256 id) external active(id) {
        require(ownerOf(id) == msg.sender, "P04");
        uint256 at = block.timestamp + RELEASE_DELAY;
        releaseAt[id] = at;
        emit ReleaseRequested(id, bundles[id].cardId, at);
    }

    function cancelRelease(uint256 id) external {
        require(ownerOf(id) == msg.sender, "P04");
        require(releaseAt[id] != 0, "P23");
        delete releaseAt[id];
        emit ReleaseCancelled(id);
    }

    function releaseCard(uint256 id) external active(id) guard {
        require(ownerOf(id) == msg.sender, "P04");
        uint256 at = releaseAt[id];
        require(at != 0, "P23");
        require(block.timestamp >= at, "P24");

        Bundle storage b = bundles[id];
        uint256 cardId = b.cardId;
        uint256 pot = b.potBalance;
        address recipient = ownerOf(id);

        delete releaseAt[id];
        b.potBalance = 0;
        b.active = false;
        _burnReceipt(id);

        if (cardId != 0) {
            card.transferFrom(address(this), recipient, cardId);
        }
        address vaultToken_ = bundleVault[id];
        if (vaultToken_ != address(0) && vaultPrincipal[id] > 0) {
            require(IERC20Vault(vaultToken_).transfer(recipient, vaultPrincipal[id]), "P05");
        }
        if (pot > 0) {
            require(wise.transfer(recipient, pot), "P05");
        }
        emit Released(id, cardId, recipient, pot);
    }

    // ------------------------------------------------------------------
    // Views for marketplace display (public numbers)
    // ------------------------------------------------------------------

    function bundleInfo(uint256 id)
        external
        view
        returns (
            uint256 cardId,
            address patron,
            uint16 patronBps,
            Mode mode,
            uint16 topUpBps,
            uint256 potBalance,
            uint256 potTarget,
            bool activeNow
        )
    {
        Bundle storage b = bundles[id];
        return (b.cardId, b.patron, b.patronBps, b.mode, b.topUpBps, b.potBalance, potTargetWise(), b.active);
    }

    // Split into two views: an 11-field single return overflows the EVM
    // stack on the legacy pipeline (no via IR needed in the Remix UI).
    function stakeTiming(uint256 id)
        external
        view
        returns (uint256 startDay, uint256 lockDays, uint256 finalDay, uint256 closeDay, uint256 scrapeDay)
    {
        bytes16 stakeId = card.NFTStake(bundles[id].cardId);
        (startDay, lockDays, finalDay, closeDay, scrapeDay, , , , , , ) =
            wiseCore.checkStakeByID(address(card), stakeId);
    }

    function stakeMoney(uint256 id)
        external
        view
        returns (uint256 stakedAmount, uint256 stakesShares, uint256 rewardAmount, uint256 penaltyAmount, bool isActive, bool isMature)
    {
        bytes16 stakeId = card.NFTStake(bundles[id].cardId);
        (, , , , , stakedAmount, stakesShares, rewardAmount, penaltyAmount, isActive, isMature) =
            wiseCore.checkStakeByID(address(card), stakeId);
    }

    function potTargetWise() public view returns (uint256) {
        // VOLATILITY RULE: gas coverage is targeted in VALUE, not tokens.
        return (gasTargetWei * wisePricePerEth) / 1e18;
    }

    function potFundingOpen(uint256 id) external view returns (bool) {
        return bundles[id].potBalance < potTargetWise();
    }

    // ------------------------------------------------------------------
    // Internal split: fee -> patron -> pot -> owner
    // ------------------------------------------------------------------

    function _distribute(uint256 id, uint256 amount)
        internal
        returns (uint256 fee, uint256 patronAmt, uint256 toPot, uint256 ownerPart)
    {
        Bundle storage b = bundles[id];

        fee = (amount * feeBps) / 10000;
        if (fee > 0) {
            require(wise.transfer(treasury, fee), "P05");
        }

        uint256 afterFee = amount - fee;
        patronAmt = (afterFee * b.patronBps) / 10000;
        if (patronAmt > 0 && b.patron != address(0)) {
            require(wise.transfer(b.patron, patronAmt), "P05");
        }

        ownerPart = afterFee - patronAmt;

        // Lean pot: divert a capped slice of the owner share until the pot
        // covers its gas target. Diversion redirects scrapes that are already
        // happening; it induces NO additional scraping and therefore no
        // additional core-contract share penalty. Surplus above target is
        // never collected.
        uint256 target = potTargetWise();
        if (b.potBalance < target && ownerPart > 0) {
            toPot = (ownerPart * potDivertBps) / 10000;
            if (toPot > target - b.potBalance) toPot = target - b.potBalance;
            if (toPot > ownerPart) toPot = ownerPart;
            if (toPot > 0) {
                b.potBalance += toPot;
                emit PotFunded(id, toPot, b.potBalance);
                ownerPart -= toPot;
            }
        }

        if (ownerPart > 0) {
            require(wise.transfer(ownerOf(id), ownerPart), "P05");
        }
    }

    // ------------------------------------------------------------------
    // Admin (owner only, no pot access - pot is never owner-sweepable)
    // ------------------------------------------------------------------

    function setFeeBps(uint16 bps) external onlyOwner {
        require(bps <= FEE_CAP_BPS, "P28");
        feeBps = bps;
    }

    function setTreasury(address t) external onlyOwner {
        require(t != address(0), "P02");
        treasury = t;
    }

    function setDefaultReferrer(address r) external onlyOwner {
        defaultReferrer = r;
    }

    function setGasTargetWei(uint256 v) external onlyOwner {
        gasTargetWei = v;
    }

    function setWisePricePerEth(uint256 p) external onlyOwner {
        require(p > 0, "P26");
        wisePricePerEth = p;
    }

    function setPotDivertBps(uint16 bps) external onlyOwner {
        require(bps <= POT_DIVERT_CAP_BPS, "P27");
        potDivertBps = bps;
    }

    function transferOwnership(address newOwner) external onlyOwner {
        require(newOwner != address(0), "P02");
        emit OwnershipTransferred(owner, newOwner);
        owner = newOwner;
    }

    // ------------------------------------------------------------------
    // VAULT ENGINE - Wise RWA vault receipts (ERC-20) as bundle assets.
    // A Wise vault receipt token (e.g. wtnUSDC) IS an ERC-20. The wrapper
    // custodies receipts, can create fresh deposits, scrape the vault's
    // penalty-free interest, compound it, and return the position through
    // the same delayed-release flow. A bundle may carry a Signature card,
    // a vault position, or both (wrapCard then attachVault).
    // NOTE: the vault contract's deposit() has NO referrer parameter, so
    // deposits created here do NOT earn Wise Soft referral credit.
    // Bundlers who want referral credit deposit through the Wise Soft app
    // and use wrapVault on the receipt they receive.
    // ------------------------------------------------------------------

    address[] public vaultList;
    mapping(address => bool) public isVaultToken;
    mapping(address => address) public vaultUnderlying; // vault receipt => deposit asset (e.g. USDC)
    mapping(uint256 => address) public bundleVault;     // bundleId => vault receipt token
    mapping(uint256 => uint256) public vaultPrincipal;  // bundleId => receipt balance recorded for it

    event VaultTokenAdded(address indexed vaultToken, address indexed underlying);
    event VaultWrapped(uint256 indexed id, address indexed vaultToken, uint256 amount, bytes32 category, string label);
    event VaultDeposited(uint256 indexed id, address indexed vaultToken, uint256 usdcIn, uint256 receipts);
    event VaultAttached(uint256 indexed id, address indexed vaultToken, uint256 amount);
    event VaultScraped(uint256 indexed id, uint256 interest, uint256 fee, uint256 patronAmt, uint256 ownerPart);
    event VaultCompounded(uint256 indexed id, uint256 addedPrincipal);

    function addVaultToken(address vaultToken, address underlying) external onlyOwner {
        require(vaultToken != address(0) && underlying != address(0), "P33");
        require(!isVaultToken[vaultToken], "P34");
        isVaultToken[vaultToken] = true;
        vaultUnderlying[vaultToken] = underlying;
        vaultList.push(vaultToken);
        emit VaultTokenAdded(vaultToken, underlying);
    }

    function vaultCount() external view returns (uint256) {
        return vaultList.length;
    }

    function vaultAt(uint256 i) external view returns (address) {
        return vaultList[i];
    }

    /// Vault bundle facts: receipt token, recorded principal, deposit asset, active flag.
    function vaultInfo(uint256 id)
        external view
        returns (address vaultToken, uint256 principal, address underlying, bool activeNow)
    {
        return (bundleVault[id], vaultPrincipal[id], vaultUnderlying[bundleVault[id]], bundles[id].active);
    }

    /// Wrap an EXISTING vault receipt position (e.g. one created through the
    /// Wise Soft app, which is also how referral attribution is earned).
    function wrapVault(
        address vaultToken,
        uint256 receiptAmount,
        address patron,
        uint16 patronBps,
        bytes32 category,
        string calldata label
    ) external guard returns (uint256 id) {
        require(isVaultToken[vaultToken], "P29");
        require(receiptAmount > 0, "P33");
        require(isCategory[category], "P11");
        require(patronBps <= PATRON_CAP_BPS, "P09");
        require(bytes(label).length <= 64, "P14");

        require(IERC20Vault(vaultToken).transferFrom(msg.sender, address(this), receiptAmount), "P05");

        id = _mintReceipt(msg.sender);
        Bundle storage b = bundles[id];
        b.cardId = 0;
        b.patron = patron;
        b.patronBps = patronBps;
        b.active = true;
        bundleCategory[id] = category;
        bundleLabel[id] = label;
        bundleVault[id] = vaultToken;
        vaultPrincipal[id] = receiptAmount;
        emit VaultWrapped(id, vaultToken, receiptAmount, category, label);
    }

    /// Create a FRESH vault deposit: pulls the underlying asset (USDC) from
    /// the caller, deposits into the whitelisted vault, custodies the receipt.
    function createVaultBundle(
        address vaultToken,
        uint256 usdcAmount,
        address patron,
        uint16 patronBps,
        bytes32 category,
        string calldata label
    ) external guard returns (uint256 id) {
        require(isVaultToken[vaultToken], "P29");
        require(usdcAmount > 0, "P33");
        require(isCategory[category], "P11");
        require(patronBps <= PATRON_CAP_BPS, "P09");
        require(bytes(label).length <= 64, "P14");

        IERC20Vault asset = IERC20Vault(vaultUnderlying[vaultToken]);
        require(asset.transferFrom(msg.sender, address(this), usdcAmount), "P05");
        require(asset.approve(vaultToken, usdcAmount), "P05");
        uint256 beforeReceipts = IERC20Vault(vaultToken).balanceOf(address(this));
        IERC20Vault(vaultToken).deposit(usdcAmount);
        uint256 receipts = IERC20Vault(vaultToken).balanceOf(address(this)) - beforeReceipts;
        require(receipts > 0, "P33");

        id = _mintReceipt(msg.sender);
        Bundle storage b = bundles[id];
        b.cardId = 0;
        b.patron = patron;
        b.patronBps = patronBps;
        b.active = true;
        bundleCategory[id] = category;
        bundleLabel[id] = label;
        bundleVault[id] = vaultToken;
        vaultPrincipal[id] = receipts;
        emit VaultDeposited(id, vaultToken, usdcAmount, receipts);
    }

    /// Attach a vault position to an existing bundle (card, vault, or both).
    function attachVault(uint256 id, address vaultToken, uint256 receiptAmount) external active(id) guard {
        require(ownerOf(id) == msg.sender, "P04");
        require(isVaultToken[vaultToken], "P29");
        require(receiptAmount > 0, "P33");
        require(bundleVault[id] == address(0), "P30");

        require(IERC20Vault(vaultToken).transferFrom(msg.sender, address(this), receiptAmount), "P05");
        bundleVault[id] = vaultToken;
        vaultPrincipal[id] = receiptAmount;
        emit VaultAttached(id, vaultToken, receiptAmount);
    }

    /// Scrape: claim the vault's penalty-free interest and split it in the
    /// deposit asset, same shape as a stake scrape. No pot: vault positions
    /// have no renewal, so there is nothing to pre-fund. Callable by the
    /// receipt owner or the patron of record.
    function scrapeVault(uint256 id) external active(id) guard {
        address v = bundleVault[id];
        require(v != address(0), "P31");
        Bundle storage b = bundles[id];
        require(b.patron == msg.sender || ownerOf(id) == msg.sender, "P32");

        IERC20Vault asset = IERC20Vault(vaultUnderlying[v]);
        uint256 beforeAsset = asset.balanceOf(address(this));
        IERC20Vault(v).claimInterest(); // vault pays the holder (this wrapper) in the deposit asset
        uint256 interest = asset.balanceOf(address(this)) - beforeAsset;
        require(interest > 0, "P16");

        uint256 fee = (interest * feeBps) / 10000;
        if (fee > 0) {
            require(asset.transfer(treasury, fee), "P05");
        }
        uint256 afterFee = interest - fee;
        uint256 patronAmt = (afterFee * b.patronBps) / 10000;
        if (patronAmt > 0 && b.patron != address(0)) {
            require(asset.transfer(b.patron, patronAmt), "P05");
        }
        uint256 ownerPart = afterFee - patronAmt;
        if (ownerPart > 0) {
            require(asset.transfer(ownerOf(id), ownerPart), "P05");
        }
        emit VaultScraped(id, interest, fee, patronAmt, ownerPart);
    }

    /// Compound: convert accrued interest into more receipt principal.
    /// The wrapper holds receipts for ALL its vault bundles of a given
    /// vault, so principal records are informational; custody is the
    /// wrapper's actual balance.
    function compoundVault(uint256 id) external active(id) guard {
        address v = bundleVault[id];
        require(v != address(0), "P31");
        IERC20Vault(v).compoundInterest();
        uint256 nowBal = IERC20Vault(v).balanceOf(address(this));
        if (nowBal > vaultPrincipal[id]) {
            uint256 added = nowBal - vaultPrincipal[id];
            vaultPrincipal[id] = nowBal;
            emit VaultCompounded(id, added);
        }
    }
}

/// Minimal interface for Wise RWA vault receipt tokens (e.g. wtnUSDC):
/// standard ERC-20 plus the vault's deposit/claim/compound surface.
interface IERC20Vault {
    function deposit(uint256 amount) external;
    function claimInterest() external;
    function compoundInterest() external;
    function balanceOf(address account) external view returns (uint256);
    function transfer(address to, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
    function approve(address spender, uint256 amount) external returns (bool);
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 10,
    "enabled": true
  },
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.