{
 "item": "token-authorizations",
 "commit": "ff1c192b3798542997f600091f2dc73ff05e4c40",
 "forge": "forge 1.9.0 (6056c58); `--use solar` unsupported by this build; tests compiled with solc 0.8.28 on a pragma-relaxed copy (0.8.38 not installed)",
 "verdict": "findings",
 "findings": [
  {
   "id": "TA-1",
   "severity": "info",
   "title": "A per-id PermitOperator signature is not bound to the transfer epoch: a pre-sale signature revives when the position comes back, unlike an approveOperator grant",
   "property": "P3 / C6",
   "claim": "C6: 'A transfer of the NFT ends every per-id grant (epochOf): show a grant or a signature from an earlier owner that still acts after a transfer'. NatSpec src/PositionNFT.sol:27: 'a grant never comes back when a position returns to an earlier owner'.",
   "files": [
    "src/PositionNFT.sol:52",
    "src/PositionNFT.sol:168-174",
    "src/PositionNFT.sol:213-221",
    "src/PositionNFT.sol:236-243",
    "src/PositionNFT.sol:145-158",
    "src/house/PositionNFT.sol:52 (byte-identical file)"
   ],
   "sequence": "1) alice owns id X and signs PermitOperator(X, op, WITHDRAW_ANY, nonce n, long deadline), not yet submitted; she also grants it with approveOperator. 2) alice sells X to bob (epochOf[X]++). Both are dead while bob owns X (_setRights reverts Unauthorized). 3) bob transfers X back to alice; ERC-721 needs no consent from the receiver. 4) anyone submits the old signature: _setRights writes the grant into the NEW epoch; op withdraws X's collateral to any address. The approveOperator grant stays lapsed. BorrowFor (struct has id but no epoch) revives the same way.",
   "expected": "Per-id grants, given directly or by signature, end at a transfer and do not come back when the position returns (src/PositionNFT.sol:27).",
   "actual": "The direct grant lapses, but the signed grant and BorrowFor do not: they bind (owner, id, nonce, deadline) only, so they work again whenever the signer owns the id again and nonces[owner] is still n. The signature is still the current owner's own, unexpired and single-use, and bumpNonce cancels it, so the literal rule of P3 holds. No loss beyond what the owner once signed, so this is info.",
   "reachableAtDeploy": true,
   "fix": "For id != 0, add epochOf[id] to the PermitOperator and BorrowFor structs (e.g. 'uint256 epoch' read at verify time), or document that signatures outlive a sale and must be cancelled with bumpNonce before selling.",
   "test": {
    "source": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {Test} from \"forge-std/Test.sol\";\nimport {MessageHashUtils} from \"@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol\";\nimport {PositionNFT} from \"../../src/PositionNFT.sol\";\nimport {PositionNFT as HouseNFT} from \"../../src/house/PositionNFT.sol\";\n\ncontract L { address public nft; function setNft(address n) external { nft = n; } function onTransfer(uint256, address, address) external {} }\n\ncontract ReviveTest is Test {\n    uint256 k = 0xA11CE; address alice = vm.addr(0xA11CE); address bob = address(0xB0B); address op = address(0x0B);\n\n    function _run(PositionNFT nft, L led) internal {\n        uint256 id = 42;\n        vm.prank(address(led)); nft.mint(alice, id);\n        uint256 dl = block.timestamp + 30 days;\n        bytes memory sig;\n        {\n            (uint8 v, bytes32 r, bytes32 s) = vm.sign(k, MessageHashUtils.toTypedDataHash(nft.DOMAIN_SEPARATOR(),\n                keccak256(abi.encode(nft.PERMIT_TYPEHASH(), alice, id, op, uint8(32), nft.nonces(alice), dl))));\n            sig = abi.encodePacked(r, s, v);\n        }\n        vm.prank(alice); nft.approveOperator(id, op, 32);  // direct grant of the same right\n        vm.prank(alice); nft.transferFrom(alice, bob, id);  // sold: both should be gone\n        vm.prank(bob); nft.transferFrom(bob, alice, id);    // sent back by the buyer, no consent needed\n        assertEq(nft.rightsOf(id, op), 0);                  // the direct grant lapsed (epochOf)\n        nft.permitOperator(alice, id, op, 32, dl, sig);      // anyone submits the pre-sale signature\n        assertEq(nft.rightsOf(id, op) & 32, 0, \"pre-sale per-id PermitOperator revived after a transfer\");\n    }\n    function test_core() public { L l = new L(); PositionNFT n = new PositionNFT(address(this)); l.setNft(address(n)); n.bind(address(l)); _run(n, l); }\n    function test_house() public { L l = new L(); HouseNFT n = new HouseNFT(address(this)); l.setNft(address(n)); n.bind(address(l)); _run(PositionNFT(address(n)), l); }\n}\n",
    "ran": "forge 1.9.0 has no `--use solar` (answers: `solc` \"solar\" does not exist) and solc 0.8.38 is not installed; ran with the installed solc 0.8.28 (via_ir, cancun) on a local copy where only `pragma solidity 0.8.38` was relaxed to ^0.8.24. No source line changed.",
    "result": "[FAIL: pre-sale per-id PermitOperator revived after a transfer: 32 != 0] test_core() (gas: 2657841)\n[FAIL: pre-sale per-id PermitOperator revived after a transfer: 32 != 0] test_house() (gas: 2657914)\nSuite result: FAILED. 0 passed; 2 failed. The full-system version (TokenAuth.t.sol test_C6_permitOperatorRevivesAfterRoundTrip, core Ledger) PASSES its assertion that op withdraws 1e18 WETH to itself after the round trip."
   }
  }
 ],
 "claims": [
  {
   "id": "C1",
   "result": "holds",
   "evidence": "testFuzz_C1_receiveOnlyPayee_timeBounds_chain (256 runs) PASS: an ERC-1271 wallet's ReceiveWithAuthorization reverts Unauthorized for every caller except the payee (src/ImdUSD.sol:357). It reverts InvalidSignature when submitted as a transfer (separate typehash), and again after vm.chainId set to 1/8453/4663 (OZ EIP712 rebuilds the domain from block.chainid; verifyingContract = token). testFuzz_C2 PASS: after a cancel, every use reverts AuthorizationAlreadyUsed."
  },
  {
   "id": "C2",
   "result": "holds",
   "evidence": "testFuzz_C2_oneNonceSpace (256 runs, EOA and ERC-1271 from) PASS. Whichever of transfer / receive / cancel runs first, every other route with the same nonce reverts AuthorizationAlreadyUsed, through the bytes and the v,r,s overloads, and the balance does not move. One mapping authorizationState[authorizer][nonce] is read at :378-379 and :369, and written at :392 and :372."
  },
  {
   "id": "C3",
   "result": "holds",
   "evidence": "Permit.t.sol testFuzz_C3_permit (256 chain ids) and test_C3_permitRefusesErc1271 PASS. Replaying a used nonce reverts, and a signature valid here reverts on any other chainid. A contract that returns the 1271 magic for anything still cannot permit: OZ ERC20Permit.permit uses ECDSA.recover only. The permit nonces (OZ Nonces) are separate from authorizationState and from PositionNFT.nonces."
  },
  {
   "id": "C4",
   "result": "holds",
   "evidence": "Only three minters can call ImdUSD.burn(from) (test_C4_nonMinterCannotBurn, fuzzed caller, PASS). Every call site in src/: Ledger.sol:278 burn(actor) on repay, where actor = msg.sender or the openFor/borrowFor submitter. Ledger.sol:359 cover and :367 retire burn msg.sender. Ledger.sol:412 burnFrom is redeemer-only, with Redeemer.sol:133 passing msg.sender. LedgerSettlement.sol:176 burn(payer) is liquidator-only (:111): Liquidator.sol:149 passes msg.sender, and :165 passes the Backstop sleeve inside the bid room it opened (the stated exception). MinterHub.sol:191 burn and :251 cover burn msg.sender; :644 burns address(this). ImdBridge.sol:520 send burns msg.sender. Spokes (StableModule, FixedLoans, MorphoLender, Migrator, house Ledger/LedgerBase) burn only through hub.burn, which burns their own balance; house repayments pull by allowance from actor/payer/msg.sender (house/LedgerBase.sol:340, house/Ledger.sol:300/386/394). Every transferFrom in src/ whose from is not msg.sender was grepped: all take actor/payer, except CompoundHook.sol:583, which moves vault shares, not imdUSD. No burn of an account that did not start the action."
  },
  {
   "id": "C5",
   "result": "holds",
   "evidence": "test_C5_frontrunOnlyChangesGasPayer PASS: a relayer submitting with another to or value gets InvalidSignature, and only the signed transfer executes. testFuzz_C2 submits from a third party and moves exactly v."
  },
  {
   "id": "C6",
   "result": "refuted",
   "evidence": "Mostly holds. testFuzz_P3_rightsExact (256 runs, random mask, action, to and scope) PASS: per-id grants read 0 after transfer and transfer-back, and all-ids grants follow the owner. test_C6_signaturesBoundToChainAndContract_bump PASS: chainid 8453/4663 reverts BadSignature, the house PositionNFT (same name and version, other verifyingContract) reverts BadSignature, and a bumped nonce kills the signature. testFuzz_C7_openForExact PASS: a changed to or rate reverts, hints do not matter. Refuted on one point, finding TA-1 (info): an unsubmitted per-id PermitOperator or BorrowFor of an earlier owner acts again after the position returns to that owner. No loss from an all-ids grant beyond what the owner granted (it covers positions sent to her, by design, PositionNFT.sol:28-29)."
  },
  {
   "id": "C7",
   "result": "holds",
   "evidence": "testFuzz_C7_openForExact (256 runs, random collateral, debt and submitter) PASS: the submitter pays exactly dCollateral, the signed to receives exactly dDebt, the submitter receives no imdUSD, and owner and rate are as signed. In Ledger._adjust (core :185, house :202), authorized=true only for execute (NFT-only, :125, after ownerOf==owner :127), addFor (dCollateral>0 only, from actor) and repayFor (dDebt<0 only, burn/pull from actor). The non-owner doors found: liquidation, redemption, harvest, addFor, repayFor, operators and signatures, plus the house auction cancel triggered by addFor/repayFor (house/Ledger.sol:328), which only cancels a sale of a healthy position. addFor's _blendMark runs after the harvest, so it does not move yield."
  }
 ],
 "holds": [
  {
   "property": "P1",
   "tried": "C1-C5 tests above (fuzzed nonces, values, payers, orderings of transfer/receive/cancel, both overloads, EOA and ERC-1271, chainids 1/8453/4663, strict time bounds validAfter < now < validBefore over fuzzed timestamps). All burn(from) and transferFrom(from) call sites in src/ were grepped and read up to where money moves (C4). No route takes imdUSD from a holder outside the listed doors."
  },
  {
   "property": "P2",
   "tried": "testFuzz_P2_flash (256 runs) with a borrower that nests a second loan: a + b > flashCap reverts. After the loan, totalSupply, the receiver's balance and allowance, feeBase(), circulating() and flashOutstanding() are unchanged (the first mint records only the tx-start supply in _lows, the same as any mint). Burn from the receiver at :285-286 before return. Both in-repo receivers (PegPositionZap:139, LoopVault:519) check initiator == this, so no third party can drive them. Sequential full-cap loans are the README:1277 known issue."
  },
  {
   "property": "P3",
   "tried": "testFuzz_P3_rightsExact: an operator's adjust succeeds iff the expanded mask covers _rightsFor; a refusal changes no state. Transfer then transfer-back clears per-id rights. Signature tests C6/C7; finding TA-1 (info) is the only gap. setRate checks SET_RATE (LedgerSettlement.sol:219, house :238) and refuses an operator's in-cooldown premium (:235). A reopen at another rate needs SET_RATE (Ledger.sol:245, house :266). House PositionNFT is byte-identical to the core one (diff empty), and house _adjust repeats the core rights logic plus the holder-bound rule (house/Ledger.sol:209-211). House was checked by reading plus Revive.t.sol test_house; the house Ledger was not run end to end. The deployer's one-shot PositionNFT.bind requires ledger.nft()==this, and the real Ledger refuses to wire otherwise, so a hostile bind blocks the deploy rather than taking funds (read, not run)."
  }
 ],
 "notRun": [
  "No [fork]/[data] claims in this sheet; no fork run (NOT RUN).",
  "solc 0.8.38 / solar: NOT RUN (unavailable); results come from solc 0.8.28 on the same sources.",
  "House Ledger end-to-end operator/openFor fuzz: NOT RUN (code read; NFT-level test_house ran).",
  "Full-system scratch suite TokenAuth.t.sol (10 tests: 9 PASS, plus an earlier draft of the permit test that failed on a harness chainid restore and was replaced by Permit.t.sol, 2 PASS). Source below."
 ],
 "supportingTests": {
  "TokenAuth.t.sol": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {MessageHashUtils} from \"@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol\";\nimport {IERC3156FlashBorrower} from \"@openzeppelin/contracts/interfaces/IERC3156FlashBorrower.sol\";\nimport {System} from \"../utils/System.sol\";\nimport {MockERC20, MockFeed} from \"../utils/Mocks.sol\";\nimport {ParametersBase} from \"../../src/ParametersBase.sol\";\nimport {LedgerBase} from \"../../src/LedgerBase.sol\";\nimport {PositionNFT} from \"../../src/PositionNFT.sol\";\nimport {PositionNFT as HouseNFT} from \"../../src/house/PositionNFT.sol\";\nimport {ImdUSD} from \"../../src/ImdUSD.sol\";\nimport {Adjust} from \"../../src/interfaces/IPositions.sol\";\n\ncontract W1271 {\n    address public immutable signer;\n    constructor(address s) { signer = s; }\n    function isValidSignature(bytes32 h, bytes calldata sig) external view returns (bytes4) {\n        (bytes32 r, bytes32 s) = abi.decode(sig[:64], (bytes32, bytes32));\n        return ecrecover(h, uint8(sig[64]), r, s) == signer ? bytes4(0x1626ba7e) : bytes4(0xffffffff);\n    }\n}\n\ncontract Borrower is IERC3156FlashBorrower {\n    ImdUSD t; uint256 public nest; uint256 public seenMax; uint256 public seenOut;\n    constructor(ImdUSD t_) { t = t_; }\n    function setNest(uint256 n) external { nest = n; }\n    function onFlashLoan(address, address, uint256 v, uint256, bytes calldata) external returns (bytes32) {\n        seenOut = t.flashOutstanding(); seenMax = t.maxFlashLoan(address(t));\n        if (nest != 0) { uint256 n = nest; nest = 0; t.flashLoan(this, address(t), n, \"\"); }\n        t.approve(address(t), t.allowance(address(this), address(t)) + v);\n        return keccak256(\"ERC3156FlashBorrower.onFlashLoan\");\n    }\n}\n\ncontract TokenAuthTest is System {\n    bytes32 constant ETH = \"ETH\";\n    MockERC20 weth; MockFeed ethFeed; PositionNFT nft;\n    uint256 aliceKey = 0xA11CE; address alice = vm.addr(0xA11CE);\n    address bob = makeAddr(\"bob\"); address op = makeAddr(\"op\"); address relayer = makeAddr(\"relayer\");\n    W1271 wallet;\n\n    function setUp() public {\n        vm.warp(1_800_000_000);\n        weth = new MockERC20(\"WETH\", 18); ethFeed = new MockFeed(2000e18);\n        _deploySystem(IERC20(address(new MockERC20(\"v1\", 18))));\n        _addIlk(ETH, address(weth), ethFeed, ethFeed, address(0), address(0), true, _risk(1.4e18, 10_000_000e18));\n        params.seal();\n        nft = ledger.nft();\n        wallet = new W1271(alice);\n        address[5] memory us = [alice, bob, op, relayer, address(wallet)];\n        for (uint256 i; i < us.length; ++i) {\n            weth.mint(us[i], 1_000e18);\n            vm.startPrank(us[i]);\n            weth.approve(address(ledger), type(uint256).max);\n            vm.stopPrank();\n        }\n        vm.startPrank(address(ledger));\n        usd.mint(alice, 10_000e18); usd.mint(address(wallet), 10_000e18);\n        vm.stopPrank();\n    }\n\n    // ------------------------------------------------ helpers\n    function _a(int256 c, int256 d, uint64 rate, address to) internal pure returns (Adjust memory) {\n        return Adjust(c, d, rate, 0, 0, false, type(uint256).max, to);\n    }\n    function _open(address u, uint256 salt) internal returns (uint256 id) {\n        vm.prank(u); id = ledger.open(ETH, salt, _a(10e18, 5_000e18, 0.05e18, address(0)));\n    }\n    function _signN(uint256 key, bytes32 dom, bytes32 sh) internal pure returns (bytes memory) {\n        (uint8 v, bytes32 r, bytes32 s) = vm.sign(key, MessageHashUtils.toTypedDataHash(dom, sh));\n        return abi.encodePacked(r, s, v);\n    }\n    function _permitOp(address owner, uint256 id, address o, uint8 m, uint256 dl) internal view returns (bytes memory) {\n        return _signN(aliceKey, nft.DOMAIN_SEPARATOR(),\n            keccak256(abi.encode(nft.PERMIT_TYPEHASH(), owner, id, o, m, nft.nonces(owner), dl)));\n    }\n    function _auth(bytes32 th, address from, address to, uint256 v, uint256 va, uint256 vb, bytes32 n)\n        internal view returns (bytes memory) {\n        return _signN(aliceKey, usd.DOMAIN_SEPARATOR(), keccak256(abi.encode(th, from, to, v, va, vb, n)));\n    }\n\n    // ------------------------------------------------ C1/C2/C5: EIP-3009\n    function testFuzz_C2_oneNonceSpace(bytes32 n, uint96 v, uint8 order) public {\n        v = uint96(bound(v, 1, 1_000e18));\n        address from = order % 2 == 0 ? alice : address(wallet);\n        bytes32 TW = usd.TRANSFER_WITH_AUTHORIZATION_TYPEHASH(); bytes32 RW = usd.RECEIVE_WITH_AUTHORIZATION_TYPEHASH();\n        uint256 vb = block.timestamp + 1 hours;\n        bytes memory st = _auth(TW, from, bob, v, 0, vb, n);\n        bytes memory sr = _auth(RW, from, bob, v, 0, vb, n);\n        bytes memory sc = _signN(aliceKey, usd.DOMAIN_SEPARATOR(), keccak256(abi.encode(usd.CANCEL_AUTHORIZATION_TYPEHASH(), from, n)));\n        uint256 b0 = usd.balanceOf(from);\n        uint8 first = order % 3;\n        vm.prank(relayer); // front-runner / facilitator\n        if (first == 0) usd.transferWithAuthorization(from, bob, v, 0, vb, n, st);\n        else if (first == 1) { vm.stopPrank(); vm.prank(bob); usd.receiveWithAuthorization(from, bob, v, 0, vb, n, sr); }\n        else usd.cancelAuthorization(from, n, sc);\n        assertTrue(usd.authorizationState(from, n));\n        uint256 b1 = usd.balanceOf(from);\n        assertEq(b0 - b1, first == 2 ? 0 : v);\n        // every other route with the same nonce now fails, through both overloads\n        (bytes32 r, bytes32 s) = abi.decode(st, (bytes32, bytes32)); uint8 vv = uint8(st[64]);\n        vm.expectRevert(ImdUSD.AuthorizationAlreadyUsed.selector);\n        usd.transferWithAuthorization(from, bob, v, 0, vb, n, st);\n        if (from == alice) { vm.expectRevert(ImdUSD.AuthorizationAlreadyUsed.selector); usd.transferWithAuthorization(from, bob, v, 0, vb, n, vv, r, s); }\n        vm.prank(bob); vm.expectRevert(ImdUSD.AuthorizationAlreadyUsed.selector);\n        usd.receiveWithAuthorization(from, bob, v, 0, vb, n, sr);\n        vm.expectRevert(ImdUSD.AuthorizationAlreadyUsed.selector);\n        usd.cancelAuthorization(from, n, sc);\n        assertEq(usd.balanceOf(from), b1);\n    }\n\n    function testFuzz_C1_receiveOnlyPayee_timeBounds_chain(address caller, uint64 va, uint64 vb, uint64 now_) public {\n        vm.assume(caller != bob);\n        bytes32 RW = usd.RECEIVE_WITH_AUTHORIZATION_TYPEHASH(); bytes32 TW = usd.TRANSFER_WITH_AUTHORIZATION_TYPEHASH();\n        bytes memory sr = _auth(RW, address(wallet), bob, 1e18, 0, type(uint256).max, \"n\");\n        vm.prank(caller); vm.expectRevert(ImdUSD.Unauthorized.selector);\n        usd.receiveWithAuthorization(address(wallet), bob, 1e18, 0, type(uint256).max, \"n\", sr);\n        // a receive signature is not a transfer signature\n        vm.expectRevert(ImdUSD.InvalidSignature.selector);\n        usd.transferWithAuthorization(address(wallet), bob, 1e18, 0, type(uint256).max, \"n\", sr);\n        // another chain: same token address, other chainid\n        uint256 cid = block.chainid; vm.chainId(cid == 1 ? 8453 : 1);\n        vm.prank(bob); vm.expectRevert(ImdUSD.InvalidSignature.selector);\n        usd.receiveWithAuthorization(address(wallet), bob, 1e18, 0, type(uint256).max, \"n\", sr);\n        vm.chainId(4663);\n        vm.prank(bob); vm.expectRevert(ImdUSD.InvalidSignature.selector);\n        usd.receiveWithAuthorization(address(wallet), bob, 1e18, 0, type(uint256).max, \"n\", sr);\n        vm.chainId(cid);\n        // time bounds (strict: validAfter < now < validBefore)\n        vm.warp(now_);\n        bytes memory st = _auth(TW, alice, bob, 1e18, va, vb, \"t\");\n        bool ok = now_ > va && now_ < vb;\n        if (!ok) vm.expectRevert();\n        usd.transferWithAuthorization(alice, bob, 1e18, va, vb, \"t\", st);\n        assertEq(usd.authorizationState(alice, \"t\"), ok);\n    }\n\n    function test_C5_frontrunOnlyChangesGasPayer() public {\n        bytes32 TW = usd.TRANSFER_WITH_AUTHORIZATION_TYPEHASH();\n        bytes memory st = _auth(TW, alice, bob, 7e18, 0, type(uint256).max, \"x\");\n        // any other to / value / bounds fails; only the signed transfer executes, whoever submits\n        vm.prank(relayer); vm.expectRevert(ImdUSD.InvalidSignature.selector);\n        usd.transferWithAuthorization(alice, relayer, 7e18, 0, type(uint256).max, \"x\", st);\n        vm.prank(relayer); vm.expectRevert(ImdUSD.InvalidSignature.selector);\n        usd.transferWithAuthorization(alice, bob, 8e18, 0, type(uint256).max, \"x\", st);\n        vm.prank(relayer); usd.transferWithAuthorization(alice, bob, 7e18, 0, type(uint256).max, \"x\", st);\n        assertEq(usd.balanceOf(bob), 7e18); assertEq(usd.balanceOf(relayer), 0);\n    }\n\n    // ------------------------------------------------ C3: permit\n    function test_C3_permitEoaOnly_noReplay() public {\n        uint256 dl = block.timestamp + 1 hours;\n        bytes32 PT = keccak256(\"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\");\n        (uint8 v, bytes32 r, bytes32 s) = vm.sign(aliceKey, MessageHashUtils.toTypedDataHash(usd.DOMAIN_SEPARATOR(),\n            keccak256(abi.encode(PT, alice, bob, 5e18, 0, dl))));\n        uint256 cid = block.chainid; vm.chainId(8453);\n        vm.expectRevert(); usd.permit(alice, bob, 5e18, dl, v, r, s);\n        vm.chainId(cid);\n        usd.permit(alice, bob, 5e18, dl, v, r, s);\n        assertEq(usd.allowance(alice, bob), 5e18);\n        vm.expectRevert(); usd.permit(alice, bob, 5e18, dl, v, r, s); // nonce used\n        // ERC-1271 wallet's key signing for the wallet: refused (ECDSA only)\n        (v, r, s) = vm.sign(aliceKey, MessageHashUtils.toTypedDataHash(usd.DOMAIN_SEPARATOR(),\n            keccak256(abi.encode(PT, address(wallet), bob, 5e18, 0, dl))));\n        vm.expectRevert(); usd.permit(address(wallet), bob, 5e18, dl, v, r, s);\n    }\n\n    // ------------------------------------------------ P2: flash mint\n    function testFuzz_P2_flash(uint256 a, uint256 b) public {\n        Borrower br = new Borrower(usd);\n        uint256 cap = usd.flashCap();\n        a = bound(a, 0, cap); b = bound(b, 0, cap);\n        br.setNest(b);\n        uint256 sup = usd.totalSupply(); uint256 fb = usd.feeBase(); uint256 circ = usd.circulating();\n        if (a + b > cap && b != 0) vm.expectRevert();\n        usd.flashLoan(br, address(usd), a, \"\");\n        assertEq(usd.totalSupply(), sup); assertEq(usd.balanceOf(address(br)), 0);\n        assertEq(usd.allowance(address(br), address(usd)), 0);\n        assertEq(usd.feeBase(), fb); assertEq(usd.circulating(), circ); assertEq(usd.flashOutstanding(), 0);\n    }\n\n    function test_C4_nonMinterCannotBurn(address x) public {\n        vm.assume(!usd.isMinter(x));\n        vm.prank(x); vm.expectRevert(ImdUSD.Unauthorized.selector); usd.burn(alice, 1);\n    }\n\n    // ------------------------------------------------ P3 / C6: rights\n    function testFuzz_P3_rightsExact(uint8 mask, uint8 kind, bool toOwner, bool allIds) public {\n        uint256 id = _open(alice, 0);\n        vm.prank(alice); nft.approveOperator(allIds ? 0 : id, op, mask);\n        int256 dc; int256 dd; uint8 need;\n        uint8 k = kind % 4;\n        if (k == 0) { dc = 1e18; need = 1; }\n        else if (k == 1) { dc = -1e18; need = toOwner ? 8 : 32; }\n        else if (k == 2) { dd = 100e18; need = toOwner ? 16 : 64; }\n        else { dd = -100e18; need = 2; vm.prank(address(ledger)); usd.mint(op, 100e18); }\n        uint8 have = mask | ((mask & 96) >> 2);\n        uint256 c0 = ledger.position(id).collateral; uint256 d0 = ledger.debtOf(id);\n        vm.prank(op);\n        try ledger.adjust(id, _a(dc, dd, 0, toOwner ? address(0) : op)) {\n            assertEq(need & ~have, 0, \"acted without the right\");\n        } catch {\n            assertTrue(need & ~have != 0, \"refused with the right\");\n            assertEq(ledger.position(id).collateral, c0); assertEq(ledger.debtOf(id), d0);\n        }\n        // after a transfer: per-id grants end; all-ids grant does not follow the position\n        vm.prank(alice); nft.transferFrom(alice, bob, id);\n        assertEq(nft.rightsOf(id, op), 0);\n        vm.prank(bob); nft.transferFrom(bob, alice, id);\n        assertEq(nft.rightsOf(id, op), allIds ? have : 0, \"per-id grant came back\");\n    }\n\n    function test_C6_signaturesBoundToChainAndContract_bump() public {\n        uint256 id = _open(alice, 0);\n        uint256 dl = block.timestamp + 1 hours;\n        bytes memory sig = _permitOp(alice, id, op, 32, dl);\n        HouseNFT house = new HouseNFT(address(this));\n        vm.expectRevert(HouseNFT.BadSignature.selector);\n        house.permitOperator(alice, id, op, 32, dl, sig);\n        uint256 cid = block.chainid; vm.chainId(8453);\n        vm.expectRevert(PositionNFT.BadSignature.selector); nft.permitOperator(alice, id, op, 32, dl, sig);\n        vm.chainId(4663);\n        vm.expectRevert(PositionNFT.BadSignature.selector); nft.permitOperator(alice, id, op, 32, dl, sig);\n        vm.chainId(cid);\n        vm.prank(alice); nft.bumpNonce(1);\n        vm.expectRevert(PositionNFT.BadSignature.selector); nft.permitOperator(alice, id, op, 32, dl, sig);\n        // OpenFor signature for the core NFT is refused by a house NFT as well (same name/version, other verifyingContract)\n        assertTrue(house.DOMAIN_SEPARATOR() != nft.DOMAIN_SEPARATOR());\n    }\n\n    /// C6: an unsubmitted per-id PermitOperator outlives a sale and revives when the position comes back (grants by\n    /// approveOperator do not: epochOf). The previous holder (bob) can send it back unilaterally.\n    function test_C6_permitOperatorRevivesAfterRoundTrip() public {\n        uint256 id = _open(alice, 0);\n        uint256 dl = block.timestamp + 30 days;\n        bytes memory sig = _permitOp(alice, id, op, 32, dl); // WITHDRAW_ANY, nonce 0\n        vm.prank(alice); nft.approveOperator(id, op, 32);    // the same grant, given directly\n        vm.prank(alice); nft.transferFrom(alice, bob, id);   // sold\n        vm.expectRevert(PositionNFT.Unauthorized.selector);\n        nft.permitOperator(alice, id, op, 32, dl, sig);       // dead while bob owns it\n        vm.prank(bob); nft.transferFrom(bob, alice, id);     // returned (no consent needed from alice)\n        assertEq(nft.rightsOf(id, op), 0, \"direct grant lapsed (epoch)\");\n        nft.permitOperator(alice, id, op, 32, dl, sig);       // anyone submits the old signature\n        uint256 before = weth.balanceOf(op);\n        vm.prank(op); ledger.adjust(id, _a(-1e18, 0, 0, op));\n        assertEq(weth.balanceOf(op) - before, 1e18, \"old signature acts after two transfers\");\n    }\n\n    /// C7: openFor executes exactly what was signed; the submitter pays collateral in, proceeds go to the signed `to`.\n    function testFuzz_C7_openForExact(int128 dc, uint128 dd, address sub) public {\n        vm.assume(sub != address(0) && sub != alice && sub.code.length == 0);\n        dc = int128(bound(dc, 1e18, 50e18)); dd = uint128(bound(dd, 2_000e18, 20_000e18));\n        weth.mint(sub, 100e18); vm.prank(sub); weth.approve(address(ledger), type(uint256).max);\n        address sink = makeAddr(\"sink\");\n        Adjust memory a = Adjust(dc, int256(uint256(dd)), 0.05e18, 0, 0, false, type(uint256).max, sink);\n        uint256 dl = block.timestamp + 1;\n        bytes memory sig = _signN(aliceKey, nft.DOMAIN_SEPARATOR(), keccak256(abi.encode(nft.OPEN_TYPEHASH(), alice, ETH,\n            uint256(0), a.dCollateral, a.dDebt, a.rate, a.viaAsset, a.maxUpfrontFee, a.to, nft.nonces(alice), dl)));\n        Adjust memory b = a; b.to = sub;\n        vm.prank(sub); vm.expectRevert(PositionNFT.BadSignature.selector); nft.openFor(alice, ETH, 0, b, dl, sig);\n        b = a; b.rate = 0.051e18;\n        vm.prank(sub); vm.expectRevert(PositionNFT.BadSignature.selector); nft.openFor(alice, ETH, 0, b, dl, sig);\n        b = a; b.prevHint = 7; // unsigned hint: gas only\n        uint256 s0 = weth.balanceOf(sub);\n        vm.prank(sub);\n        try nft.openFor(alice, ETH, 0, b, dl, sig) returns (uint256 id) {\n            assertEq(usd.balanceOf(sink), dd); assertEq(usd.balanceOf(sub), 0);\n            assertEq(s0 - weth.balanceOf(sub), uint256(int256(dc)));\n            assertEq(nft.ownerOf(id), alice); assertEq(ledger.rateOf(id), 0.05e18);\n        } catch {}\n    }\n}\n",
  "Permit.t.sol": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {Test} from \"forge-std/Test.sol\";\nimport {MessageHashUtils} from \"@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol\";\nimport {ImdUSD} from \"../../src/ImdUSD.sol\";\n\ncontract C {}\ncontract W1271 {\n    function isValidSignature(bytes32, bytes calldata) external pure returns (bytes4) { return 0x1626ba7e; } // accepts anything\n}\n\ncontract PermitTest is Test {\n    ImdUSD usd; uint256 k = 0xA11CE; address alice = vm.addr(0xA11CE); address bob = address(0xB0B);\n    bytes32 constant PT = keccak256(\"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\");\n    function setUp() public {\n        usd = new ImdUSD(address(this), 1e24, address(0));\n        usd.wire(address(new C()), address(new C()), address(new C()));\n    }\n    function _sig(address owner, uint256 nonce, uint256 dl) internal view returns (uint8 v, bytes32 r, bytes32 s) {\n        (v, r, s) = vm.sign(k, MessageHashUtils.toTypedDataHash(usd.DOMAIN_SEPARATOR(),\n            keccak256(abi.encode(PT, owner, bob, 5e18, nonce, dl))));\n    }\n    function testFuzz_C3_permit(uint64 chain) public {\n        vm.assume(chain != block.chainid && chain != 0);\n        uint256 dl = block.timestamp + 1 hours;\n        (uint8 v, bytes32 r, bytes32 s) = _sig(alice, 0, dl);\n        usd.permit(alice, bob, 5e18, dl, v, r, s);\n        assertEq(usd.allowance(alice, bob), 5e18);\n        vm.expectRevert(); usd.permit(alice, bob, 5e18, dl, v, r, s); // nonce used\n        (v, r, s) = _sig(alice, 1, dl);                                  // valid here, replayed on another chain\n        vm.chainId(chain);\n        vm.expectRevert(); usd.permit(alice, bob, 5e18, dl, v, r, s);\n    }\n    function test_C3_permitRefusesErc1271() public {\n        W1271 w = new W1271();\n        uint256 dl = block.timestamp + 1 hours;\n        (uint8 v, bytes32 r, bytes32 s) = _sig(address(w), 0, dl);\n        vm.expectRevert(); usd.permit(address(w), bob, 5e18, dl, v, r, s);\n        assertEq(usd.allowance(address(w), bob), 0);\n    }\n}\n"
 }
}