From 7a73cd9bab1a94628946a533dbd33c5eb9647c2e Mon Sep 17 00:00:00 2001 From: douglasacost Date: Thu, 22 Oct 2026 17:05:09 -0400 Subject: [PATCH 01/18] feat(tipping): immutable Tipping contract with on-chain recipient resolution (local, not deployed) --- src/tipping/ITipping.sol | 46 ++++++++++ src/tipping/Tipping.sol | 181 +++++++++++++++++++++++++++++++++++++ test/tipping/Tipping.t.sol | 170 ++++++++++++++++++++++++++++++++++ 3 files changed, 397 insertions(+) create mode 100644 src/tipping/ITipping.sol create mode 100644 src/tipping/Tipping.sol create mode 100644 test/tipping/Tipping.t.sol diff --git a/src/tipping/ITipping.sol b/src/tipping/ITipping.sol new file mode 100644 index 00000000..f4277480 --- /dev/null +++ b/src/tipping/ITipping.sol @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: BSD-3-Clause-Clear +pragma solidity ^0.8.26; + +/** + * @title ITipping + * @notice NODL tips on NFTs with on-chain recipient resolution. The event and error surface + * is what the feed indexer consumes (nft-feed-indexer design §6.2); keep it stable. + */ +interface ITipping { + /// @notice A tip was paid. `amount` is gross (what the tipper gave); `fee` went to the fee recipient. + event Tipped( + address indexed tipper, + address indexed collection, + uint256 indexed tokenId, + address recipient, + uint256 amount, + uint256 fee + ); + /// @notice A ContentSign-type collection was added to or removed from the allowlist. + event CollectionAllowed(address indexed collection, bool allowed); + /// @notice The registered creator of a factory collection changed (zero clears the entry). + event CreatorSet(address indexed collection, address indexed creator); + event MinTipUpdated(uint256 minTipAmount); + event FeeUpdated(uint16 feeBps); + event FeeRecipientUpdated(address indexed feeRecipient); + + error ZeroAddress(); + error BelowMinimum(uint256 amount, uint256 minTipAmount); + error SelfTip(); + error UnknownCollection(address collection); + error UnknownToken(address collection, uint256 tokenId); + error NoRecipient(address collection, uint256 tokenId); + error NotCollectionOwner(address collection, address account); + error FeeTooHigh(uint16 feeBps); + + function tip(address collection, uint256 tokenId, uint256 amount) external; + function registerCollection(address collection) external; + function resolveRecipient(address collection, uint256 tokenId) external view returns (address); + + function nodl() external view returns (address); + function minTipAmount() external view returns (uint256); + function feeBps() external view returns (uint16); + function feeRecipient() external view returns (address); + function contentSignAllowed(address collection) external view returns (bool); + function creatorOf(address collection) external view returns (address); +} diff --git a/src/tipping/Tipping.sol b/src/tipping/Tipping.sol new file mode 100644 index 00000000..31add886 --- /dev/null +++ b/src/tipping/Tipping.sol @@ -0,0 +1,181 @@ +// SPDX-License-Identifier: BSD-3-Clause-Clear +pragma solidity ^0.8.26; + +import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; +import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol"; +import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; +import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol"; +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; +import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; +import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; +import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; +import {IERC2981} from "@openzeppelin/contracts/interfaces/IERC2981.sol"; +import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; + +import {ITipping} from "./ITipping.sol"; + +/** + * @title Tipping + * @notice Immutable NODL tipping for Nodle NFTs (nft-feed-indexer design §6.2). No proxy and + * no upgrade path on purpose: an allowance granted to this address can only ever be + * spent by the approver's own `tip` calls, because `transferFrom` is only called with + * `from == msg.sender`. Everything that may change lives in storage behind roles. + * + * Recipient resolution (never caller-supplied): + * 1. `contentSignAllowed[collection]` → `ownerOf(tokenId)`. + * 2. `creatorOf[collection] != 0` → ERC-2981 receiver for the token if non-zero, + * else the registered creator. ERC-1155 ids with + * `totalSupply == 0` revert. + * 3. otherwise → `UnknownCollection`. + * + * Roles: DEFAULT_ADMIN_ROLE (fee, fee recipient, minimum, pause), REGISTRY_ROLE (allowlist, + * creator registry). `registerCollection` is permissionless for a collection's OWNER_ROLE. + */ +contract Tipping is ITipping, AccessControl, ReentrancyGuard, Pausable { + using SafeERC20 for IERC20; + + bytes32 public constant REGISTRY_ROLE = keccak256("REGISTRY_ROLE"); + /// @dev OWNER_ROLE of the factory collections (UserCollection721/1155). + bytes32 public constant COLLECTION_OWNER_ROLE = keccak256("OWNER_ROLE"); + uint16 public constant MAX_FEE_BPS = 1000; + uint256 public constant BPS = 10_000; + /// @dev Gas cap for every static lookup into a collection. + uint256 public constant LOOKUP_GAS = 100_000; + + IERC20 private immutable _nodl; + + uint256 public minTipAmount; + uint16 public feeBps; + address public feeRecipient; + mapping(address collection => bool) public contentSignAllowed; + mapping(address collection => address creator) public creatorOf; + + constructor(address nodlToken, address admin, address registry, uint256 initialMinTip) { + if (nodlToken == address(0) || admin == address(0) || registry == address(0)) revert ZeroAddress(); + _nodl = IERC20(nodlToken); + _grantRole(DEFAULT_ADMIN_ROLE, admin); + _grantRole(REGISTRY_ROLE, registry); + minTipAmount = initialMinTip; + feeRecipient = admin; + emit MinTipUpdated(initialMinTip); + emit FeeUpdated(0); + emit FeeRecipientUpdated(admin); + } + + // ───────── Tipping ───────── + + /// @inheritdoc ITipping + function tip(address collection, uint256 tokenId, uint256 amount) external whenNotPaused nonReentrant { + if (amount < minTipAmount) revert BelowMinimum(amount, minTipAmount); + address recipient = _resolve(collection, tokenId); + if (recipient == msg.sender) revert SelfTip(); + + uint256 fee = (amount * feeBps) / BPS; + // Only ever pulls from msg.sender: the property the immutability argument rests on. + _nodl.safeTransferFrom(msg.sender, recipient, amount - fee); + if (fee > 0) _nodl.safeTransferFrom(msg.sender, feeRecipient, fee); + + emit Tipped(msg.sender, collection, tokenId, recipient, amount, fee); + } + + /// @inheritdoc ITipping + function resolveRecipient(address collection, uint256 tokenId) external view returns (address) { + return _resolve(collection, tokenId); + } + + function _resolve(address collection, uint256 tokenId) internal view returns (address recipient) { + if (contentSignAllowed[collection]) { + (bool ok, bytes memory data) = collection.staticcall{gas: LOOKUP_GAS}( + abi.encodeCall(IERC721.ownerOf, (tokenId)) + ); + if (!ok || data.length < 32) revert UnknownToken(collection, tokenId); + recipient = abi.decode(data, (address)); + if (recipient == address(0)) revert NoRecipient(collection, tokenId); + return recipient; + } + + address creator = creatorOf[collection]; + if (creator == address(0)) revert UnknownCollection(collection); + + if (_supports(collection, type(IERC1155).interfaceId)) { + (bool ok, bytes memory data) = collection.staticcall{gas: LOOKUP_GAS}( + abi.encodeWithSignature("totalSupply(uint256)", tokenId) + ); + if (!ok || data.length < 32 || abi.decode(data, (uint256)) == 0) revert UnknownToken(collection, tokenId); + } + + (bool rOk, bytes memory rData) = collection.staticcall{gas: LOOKUP_GAS}( + abi.encodeCall(IERC2981.royaltyInfo, (tokenId, 1e18)) + ); + if (rOk && rData.length >= 64) { + (address receiver,) = abi.decode(rData, (address, uint256)); + if (receiver != address(0)) return receiver; + } + return creator; + } + + function _supports(address target, bytes4 interfaceId) internal view returns (bool) { + (bool ok, bytes memory data) = target.staticcall{gas: LOOKUP_GAS}( + abi.encodeCall(IERC165.supportsInterface, (interfaceId)) + ); + return ok && data.length >= 32 && abi.decode(data, (bool)); + } + + // ───────── Registry ───────── + + /// @inheritdoc ITipping + /// @dev Permissionless: succeeds only for an account holding the collection's OWNER_ROLE. + function registerCollection(address collection) external { + if (collection == address(0)) revert ZeroAddress(); + (bool ok, bytes memory data) = collection.staticcall{gas: LOOKUP_GAS}( + abi.encodeCall(IAccessControl.hasRole, (COLLECTION_OWNER_ROLE, msg.sender)) + ); + if (!ok || data.length < 32 || !abi.decode(data, (bool))) revert NotCollectionOwner(collection, msg.sender); + creatorOf[collection] = msg.sender; + emit CreatorSet(collection, msg.sender); + } + + function setCreator(address collection, address creator) external onlyRole(REGISTRY_ROLE) { + if (collection == address(0)) revert ZeroAddress(); + creatorOf[collection] = creator; + emit CreatorSet(collection, creator); + } + + function setCollectionAllowed(address collection, bool allowed) external onlyRole(REGISTRY_ROLE) { + if (collection == address(0)) revert ZeroAddress(); + contentSignAllowed[collection] = allowed; + emit CollectionAllowed(collection, allowed); + } + + // ───────── Admin ───────── + + function setMinTipAmount(uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) { + minTipAmount = amount; + emit MinTipUpdated(amount); + } + + function setFee(uint16 bps) external onlyRole(DEFAULT_ADMIN_ROLE) { + if (bps > MAX_FEE_BPS) revert FeeTooHigh(bps); + feeBps = bps; + emit FeeUpdated(bps); + } + + function setFeeRecipient(address recipient) external onlyRole(DEFAULT_ADMIN_ROLE) { + if (recipient == address(0)) revert ZeroAddress(); + feeRecipient = recipient; + emit FeeRecipientUpdated(recipient); + } + + function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { + _pause(); + } + + function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { + _unpause(); + } + + /// @inheritdoc ITipping + function nodl() external view returns (address) { + return address(_nodl); + } +} diff --git a/test/tipping/Tipping.t.sol b/test/tipping/Tipping.t.sol new file mode 100644 index 00000000..fbcf6bea --- /dev/null +++ b/test/tipping/Tipping.t.sol @@ -0,0 +1,170 @@ +// SPDX-License-Identifier: BSD-3-Clause-Clear +pragma solidity ^0.8.26; + +import {Test} from "forge-std/Test.sol"; +import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import {ERC1155} from "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; +import {ERC1155Supply} from "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol"; +import {ERC2981} from "@openzeppelin/contracts/token/common/ERC2981.sol"; +import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; + +import {Tipping} from "../../src/tipping/Tipping.sol"; +import {ITipping} from "../../src/tipping/ITipping.sol"; + +contract TokenMock is ERC20 { + constructor() ERC20("NODL", "NODL") {} + function mint(address to, uint256 amount) external { _mint(to, amount); } +} + +contract ContentSignMock is ERC721 { + constructor() ERC721("CS", "CS") {} + function mint(address to, uint256 id) external { _mint(to, id); } +} + +/// @dev Mirrors what the tipping contract reads from a factory collection: OWNER_ROLE, ERC-2981. +contract Collection721Mock is ERC721, ERC2981, AccessControl { + bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); + constructor(address owner) ERC721("C", "C") { _grantRole(OWNER_ROLE, owner); } + function mint(address to, uint256 id) external { _mint(to, id); } + function setRoyalty(address r, uint96 bps) external { _setDefaultRoyalty(r, bps); } + function supportsInterface(bytes4 i) public view override(ERC721, ERC2981, AccessControl) returns (bool) { + return super.supportsInterface(i); + } +} + +contract Collection1155Mock is ERC1155Supply, ERC2981 { + constructor() ERC1155("") {} + function mint(address to, uint256 id, uint256 n) external { _mint(to, id, n, ""); } + function setRoyalty(address r, uint96 bps) external { _setDefaultRoyalty(r, bps); } + function supportsInterface(bytes4 i) public view override(ERC1155, ERC2981) returns (bool) { + return super.supportsInterface(i); + } +} + +contract TippingTest is Test { + TokenMock internal nodl; + Tipping internal tipping; + ContentSignMock internal cs; + Collection721Mock internal c721; + Collection1155Mock internal c1155; + + address internal constant ADMIN = address(0xAD); + address internal constant REGISTRY = address(0x09); + address internal constant CREATOR = address(0xCAFE); + address internal constant ALICE = address(0xA1); + address internal constant BOB = address(0xB0); + address internal constant SPLITTER = address(0x5111); + uint256 internal constant MIN = 1e18; + + function setUp() public { + nodl = new TokenMock(); + tipping = new Tipping(address(nodl), ADMIN, REGISTRY, MIN); + cs = new ContentSignMock(); + c721 = new Collection721Mock(CREATOR); + c1155 = new Collection1155Mock(); + nodl.mint(ALICE, 1_000e18); + vm.prank(ALICE); + nodl.approve(address(tipping), type(uint256).max); + vm.prank(REGISTRY); + tipping.setCollectionAllowed(address(cs), true); + vm.prank(REGISTRY); + tipping.setCreator(address(c1155), CREATOR); + } + + function test_contentSign_tipGoesToOwner() public { + cs.mint(BOB, 7); + vm.expectEmit(true, true, true, true); + emit ITipping.Tipped(ALICE, address(cs), 7, BOB, 5e18, 0); + vm.prank(ALICE); + tipping.tip(address(cs), 7, 5e18); + assertEq(nodl.balanceOf(BOB), 5e18); + } + + function test_contentSign_unmintedReverts() public { + vm.prank(ALICE); + vm.expectRevert(abi.encodeWithSelector(ITipping.UnknownToken.selector, address(cs), 1)); + tipping.tip(address(cs), 1, 5e18); + } + + function test_registerCollection_ownerOnly() public { + vm.prank(ALICE); + vm.expectRevert(abi.encodeWithSelector(ITipping.NotCollectionOwner.selector, address(c721), ALICE)); + tipping.registerCollection(address(c721)); + vm.prank(CREATOR); + tipping.registerCollection(address(c721)); + assertEq(tipping.creatorOf(address(c721)), CREATOR); + } + + function test_factory721_royaltyReceiverElseCreator() public { + vm.prank(CREATOR); + tipping.registerCollection(address(c721)); + c721.mint(BOB, 1); + vm.prank(ALICE); + tipping.tip(address(c721), 1, 2e18); + assertEq(nodl.balanceOf(CREATOR), 2e18); + c721.setRoyalty(SPLITTER, 500); + vm.prank(ALICE); + tipping.tip(address(c721), 1, 2e18); + assertEq(nodl.balanceOf(SPLITTER), 2e18); + } + + function test_factory1155_zeroSupplyReverts_thenResolves() public { + vm.prank(ALICE); + vm.expectRevert(abi.encodeWithSelector(ITipping.UnknownToken.selector, address(c1155), 3)); + tipping.tip(address(c1155), 3, 2e18); + c1155.mint(BOB, 3, 10); + vm.prank(ALICE); + tipping.tip(address(c1155), 3, 2e18); + assertEq(nodl.balanceOf(CREATOR), 2e18); + } + + function test_unknownCollectionReverts() public { + vm.prank(ALICE); + vm.expectRevert(abi.encodeWithSelector(ITipping.UnknownCollection.selector, address(0x1234))); + tipping.tip(address(0x1234), 1, 2e18); + } + + function test_selfTipAndDustRevert() public { + cs.mint(ALICE, 9); + vm.startPrank(ALICE); + vm.expectRevert(ITipping.SelfTip.selector); + tipping.tip(address(cs), 9, 2e18); + vm.expectRevert(abi.encodeWithSelector(ITipping.BelowMinimum.selector, 1, MIN)); + tipping.tip(address(cs), 9, 1); + vm.stopPrank(); + } + + function test_feeSplitAndCap() public { + vm.prank(ADMIN); + tipping.setFee(250); + vm.prank(ADMIN); + tipping.setFeeRecipient(address(0xFEE)); + cs.mint(BOB, 1); + vm.prank(ALICE); + tipping.tip(address(cs), 1, 100e18); + assertEq(nodl.balanceOf(BOB), 97.5e18); + assertEq(nodl.balanceOf(address(0xFEE)), 2.5e18); + vm.prank(ADMIN); + vm.expectRevert(abi.encodeWithSelector(ITipping.FeeTooHigh.selector, 1001)); + tipping.setFee(1001); + } + + function test_pauseBlocksTips() public { + vm.prank(ADMIN); + tipping.pause(); + cs.mint(BOB, 1); + vm.prank(ALICE); + vm.expectRevert(); + tipping.tip(address(cs), 1, 2e18); + } + + function test_rolesSeparated() public { + vm.prank(ADMIN); + vm.expectRevert(); + tipping.setCollectionAllowed(address(cs), false); + vm.prank(REGISTRY); + vm.expectRevert(); + tipping.setFee(1); + } +} From 0e8d8bd136e0493cbd16d869f23591c06e5dba9d Mon Sep 17 00:00:00 2001 From: douglasacost Date: Thu, 22 Oct 2026 17:13:01 -0400 Subject: [PATCH 02/18] fix(tipping): zero-amount guard, single registration, fee-recipient sanity --- src/tipping/ITipping.sol | 4 ++++ src/tipping/Tipping.sol | 21 +++++++++++++++++---- test/tipping/Tipping.t.sol | 30 +++++++++++++++++++++++++++--- 3 files changed, 48 insertions(+), 7 deletions(-) diff --git a/src/tipping/ITipping.sol b/src/tipping/ITipping.sol index f4277480..c55e0362 100644 --- a/src/tipping/ITipping.sol +++ b/src/tipping/ITipping.sol @@ -23,6 +23,8 @@ interface ITipping { event MinTipUpdated(uint256 minTipAmount); event FeeUpdated(uint16 feeBps); event FeeRecipientUpdated(address indexed feeRecipient); + // `Paused(address)` / `Unpaused(address)` come from OpenZeppelin Pausable and are part of + // the indexed surface too; do not strip them from the generated ABI. error ZeroAddress(); error BelowMinimum(uint256 amount, uint256 minTipAmount); @@ -32,6 +34,8 @@ interface ITipping { error NoRecipient(address collection, uint256 tokenId); error NotCollectionOwner(address collection, address account); error FeeTooHigh(uint16 feeBps); + error AlreadyRegistered(address collection); + error InvalidFeeRecipient(address recipient); function tip(address collection, uint256 tokenId, uint256 amount) external; function registerCollection(address collection) external; diff --git a/src/tipping/Tipping.sol b/src/tipping/Tipping.sol index 31add886..cf3621b3 100644 --- a/src/tipping/Tipping.sol +++ b/src/tipping/Tipping.sol @@ -14,6 +14,11 @@ import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import {ITipping} from "./ITipping.sol"; +/// @dev The subset of ERC1155Supply the resolver reads. +interface IERC1155Supply { + function totalSupply(uint256 id) external view returns (uint256); +} + /** * @title Tipping * @notice Immutable NODL tipping for Nodle NFTs (nft-feed-indexer design §6.2). No proxy and @@ -39,7 +44,8 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard, Pausable { bytes32 public constant COLLECTION_OWNER_ROLE = keccak256("OWNER_ROLE"); uint16 public constant MAX_FEE_BPS = 1000; uint256 public constant BPS = 10_000; - /// @dev Gas cap for every static lookup into a collection. + /// @dev Gas cap for every static lookup into a collection. Sized for the EVM; confirm on + /// EraVM through the real ContentSign/UserCollection proxies before deploy (slice 6). uint256 public constant LOOKUP_GAS = 100_000; IERC20 private immutable _nodl; @@ -66,7 +72,8 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard, Pausable { /// @inheritdoc ITipping function tip(address collection, uint256 tokenId, uint256 amount) external whenNotPaused nonReentrant { - if (amount < minTipAmount) revert BelowMinimum(amount, minTipAmount); + // Zero tips are never meaningful, even when the admin sets the minimum to zero. + if (amount == 0 || amount < minTipAmount) revert BelowMinimum(amount, minTipAmount); address recipient = _resolve(collection, tokenId); if (recipient == msg.sender) revert SelfTip(); @@ -99,7 +106,7 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard, Pausable { if (_supports(collection, type(IERC1155).interfaceId)) { (bool ok, bytes memory data) = collection.staticcall{gas: LOOKUP_GAS}( - abi.encodeWithSignature("totalSupply(uint256)", tokenId) + abi.encodeCall(IERC1155Supply.totalSupply, (tokenId)) ); if (!ok || data.length < 32 || abi.decode(data, (uint256)) == 0) revert UnknownToken(collection, tokenId); } @@ -124,9 +131,13 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard, Pausable { // ───────── Registry ───────── /// @inheritdoc ITipping - /// @dev Permissionless: succeeds only for an account holding the collection's OWNER_ROLE. + /// @dev Permissionless: succeeds only for an account holding the collection's OWNER_ROLE, + /// and only once. An entry set by REGISTRY_ROLE wins; changes go through the operator. + /// Any contract that attests OWNER_ROLE for the caller can be registered, not only + /// factory collections; the indexer records such collections as UNKNOWN. function registerCollection(address collection) external { if (collection == address(0)) revert ZeroAddress(); + if (creatorOf[collection] != address(0)) revert AlreadyRegistered(collection); (bool ok, bytes memory data) = collection.staticcall{gas: LOOKUP_GAS}( abi.encodeCall(IAccessControl.hasRole, (COLLECTION_OWNER_ROLE, msg.sender)) ); @@ -162,6 +173,8 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard, Pausable { function setFeeRecipient(address recipient) external onlyRole(DEFAULT_ADMIN_ROLE) { if (recipient == address(0)) revert ZeroAddress(); + // No rescue path exists in an immutable contract: fees sent here or to the token are lost. + if (recipient == address(this) || recipient == address(_nodl)) revert InvalidFeeRecipient(recipient); feeRecipient = recipient; emit FeeRecipientUpdated(recipient); } diff --git a/test/tipping/Tipping.t.sol b/test/tipping/Tipping.t.sol index fbcf6bea..1456b7b8 100644 --- a/test/tipping/Tipping.t.sol +++ b/test/tipping/Tipping.t.sol @@ -8,6 +8,8 @@ import {ERC1155} from "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import {ERC1155Supply} from "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol"; import {ERC2981} from "@openzeppelin/contracts/token/common/ERC2981.sol"; import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; +import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol"; +import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol"; import {Tipping} from "../../src/tipping/Tipping.sol"; import {ITipping} from "../../src/tipping/ITipping.sol"; @@ -94,6 +96,27 @@ contract TippingTest is Test { vm.prank(CREATOR); tipping.registerCollection(address(c721)); assertEq(tipping.creatorOf(address(c721)), CREATOR); + vm.prank(CREATOR); + vm.expectRevert(abi.encodeWithSelector(ITipping.AlreadyRegistered.selector, address(c721))); + tipping.registerCollection(address(c721)); + } + + function test_zeroAmountRevertsEvenWithZeroMinimum() public { + vm.prank(ADMIN); + tipping.setMinTipAmount(0); + cs.mint(BOB, 1); + vm.prank(ALICE); + vm.expectRevert(abi.encodeWithSelector(ITipping.BelowMinimum.selector, 0, 0)); + tipping.tip(address(cs), 1, 0); + } + + function test_feeRecipientCannotBeSelfOrToken() public { + vm.startPrank(ADMIN); + vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidFeeRecipient.selector, address(tipping))); + tipping.setFeeRecipient(address(tipping)); + vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidFeeRecipient.selector, address(nodl))); + tipping.setFeeRecipient(address(nodl)); + vm.stopPrank(); } function test_factory721_royaltyReceiverElseCreator() public { @@ -155,16 +178,17 @@ contract TippingTest is Test { tipping.pause(); cs.mint(BOB, 1); vm.prank(ALICE); - vm.expectRevert(); + vm.expectRevert(Pausable.EnforcedPause.selector); tipping.tip(address(cs), 1, 2e18); } function test_rolesSeparated() public { + bytes32 registryRole = tipping.REGISTRY_ROLE(); vm.prank(ADMIN); - vm.expectRevert(); + vm.expectRevert(abi.encodeWithSelector(IAccessControl.AccessControlUnauthorizedAccount.selector, ADMIN, registryRole)); tipping.setCollectionAllowed(address(cs), false); vm.prank(REGISTRY); - vm.expectRevert(); + vm.expectRevert(abi.encodeWithSelector(IAccessControl.AccessControlUnauthorizedAccount.selector, REGISTRY, bytes32(0))); tipping.setFee(1); } } From f2354a9d9c1159fc0e7db73dadeaa2be59903825 Mon Sep 17 00:00:00 2001 From: douglasacost Date: Tue, 27 Oct 2026 12:35:24 -0400 Subject: [PATCH 03/18] test(tipping): full suite (31 tests, 97% line coverage), local only --- test/tipping/Tipping.t.sol | 447 +++++++++++++++++++++++++++++++++---- 1 file changed, 409 insertions(+), 38 deletions(-) diff --git a/test/tipping/Tipping.t.sol b/test/tipping/Tipping.t.sol index 1456b7b8..03b78dc1 100644 --- a/test/tipping/Tipping.t.sol +++ b/test/tipping/Tipping.t.sol @@ -14,22 +14,58 @@ import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol"; import {Tipping} from "../../src/tipping/Tipping.sol"; import {ITipping} from "../../src/tipping/ITipping.sol"; +/// @dev Records every `transferFrom` so tests can prove the contract only ever pulls from the caller. contract TokenMock is ERC20 { + address[] public froms; + address[] public tos; + uint256[] public amounts; + constructor() ERC20("NODL", "NODL") {} - function mint(address to, uint256 amount) external { _mint(to, amount); } + + function mint(address to, uint256 amount) external { + _mint(to, amount); + } + + function transferFrom(address from, address to, uint256 value) public override returns (bool) { + froms.push(from); + tos.push(to); + amounts.push(value); + return super.transferFrom(from, to, value); + } + + function transfers() external view returns (uint256) { + return froms.length; + } } contract ContentSignMock is ERC721 { constructor() ERC721("CS", "CS") {} - function mint(address to, uint256 id) external { _mint(to, id); } + + function mint(address to, uint256 id) external { + _mint(to, id); + } } /// @dev Mirrors what the tipping contract reads from a factory collection: OWNER_ROLE, ERC-2981. contract Collection721Mock is ERC721, ERC2981, AccessControl { bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); - constructor(address owner) ERC721("C", "C") { _grantRole(OWNER_ROLE, owner); } - function mint(address to, uint256 id) external { _mint(to, id); } - function setRoyalty(address r, uint96 bps) external { _setDefaultRoyalty(r, bps); } + + constructor(address owner) ERC721("C", "C") { + _grantRole(OWNER_ROLE, owner); + } + + function mint(address to, uint256 id) external { + _mint(to, id); + } + + function setRoyalty(address r, uint96 bps) external { + _setDefaultRoyalty(r, bps); + } + + function deleteRoyalty() external { + _deleteDefaultRoyalty(); + } + function supportsInterface(bytes4 i) public view override(ERC721, ERC2981, AccessControl) returns (bool) { return super.supportsInterface(i); } @@ -37,13 +73,44 @@ contract Collection721Mock is ERC721, ERC2981, AccessControl { contract Collection1155Mock is ERC1155Supply, ERC2981 { constructor() ERC1155("") {} - function mint(address to, uint256 id, uint256 n) external { _mint(to, id, n, ""); } - function setRoyalty(address r, uint96 bps) external { _setDefaultRoyalty(r, bps); } + + function mint(address to, uint256 id, uint256 n) external { + _mint(to, id, n, ""); + } + + function setRoyalty(address r, uint96 bps) external { + _setDefaultRoyalty(r, bps); + } + function supportsInterface(bytes4 i) public view override(ERC1155, ERC2981) returns (bool) { return super.supportsInterface(i); } } +/// @dev Burns all forwarded gas on every call: the lookup gas cap must contain it. +contract GasBombMock { + fallback() external { + while (true) {} + } +} + +/// @dev Returns malformed data (too short) for every call. +contract ShortReturnMock { + fallback() external { + assembly { + mstore(0, 1) + return(0, 8) + } + } +} + +/// @dev `hasRole` reports true for everyone: any such contract can be registered by anyone. +contract OpenOwnerMock { + function hasRole(bytes32, address) external pure returns (bool) { + return true; + } +} + contract TippingTest is Test { TokenMock internal nodl; Tipping internal tipping; @@ -74,13 +141,51 @@ contract TippingTest is Test { tipping.setCreator(address(c1155), CREATOR); } + // ───────── Constructor ───────── + + function test_constructor_state() public view { + assertEq(tipping.nodl(), address(nodl)); + assertEq(tipping.minTipAmount(), MIN); + assertEq(tipping.feeBps(), 0); + assertEq(tipping.feeRecipient(), ADMIN); + assertTrue(tipping.hasRole(tipping.DEFAULT_ADMIN_ROLE(), ADMIN)); + assertTrue(tipping.hasRole(tipping.REGISTRY_ROLE(), REGISTRY)); + assertFalse(tipping.paused()); + assertEq(tipping.COLLECTION_OWNER_ROLE(), keccak256("OWNER_ROLE")); + } + + function test_constructor_emitsInitialSettings() public { + vm.expectEmit(true, true, true, true); + emit ITipping.MinTipUpdated(3); + vm.expectEmit(true, true, true, true); + emit ITipping.FeeUpdated(0); + vm.expectEmit(true, true, true, true); + emit ITipping.FeeRecipientUpdated(ADMIN); + new Tipping(address(nodl), ADMIN, REGISTRY, 3); + } + + function test_constructor_rejectsZeroAddresses() public { + vm.expectRevert(ITipping.ZeroAddress.selector); + new Tipping(address(0), ADMIN, REGISTRY, MIN); + vm.expectRevert(ITipping.ZeroAddress.selector); + new Tipping(address(nodl), address(0), REGISTRY, MIN); + vm.expectRevert(ITipping.ZeroAddress.selector); + new Tipping(address(nodl), ADMIN, address(0), MIN); + } + + // ───────── ContentSign path ───────── + function test_contentSign_tipGoesToOwner() public { cs.mint(BOB, 7); + assertEq(tipping.resolveRecipient(address(cs), 7), BOB); vm.expectEmit(true, true, true, true); emit ITipping.Tipped(ALICE, address(cs), 7, BOB, 5e18, 0); vm.prank(ALICE); tipping.tip(address(cs), 7, 5e18); assertEq(nodl.balanceOf(BOB), 5e18); + assertEq(nodl.balanceOf(ALICE), 995e18); + // A zero fee means a single transfer, straight to the recipient. + assertEq(nodl.transfers(), 1); } function test_contentSign_unmintedReverts() public { @@ -89,47 +194,62 @@ contract TippingTest is Test { tipping.tip(address(cs), 1, 5e18); } - function test_registerCollection_ownerOnly() public { - vm.prank(ALICE); - vm.expectRevert(abi.encodeWithSelector(ITipping.NotCollectionOwner.selector, address(c721), ALICE)); - tipping.registerCollection(address(c721)); - vm.prank(CREATOR); - tipping.registerCollection(address(c721)); - assertEq(tipping.creatorOf(address(c721)), CREATOR); - vm.prank(CREATOR); - vm.expectRevert(abi.encodeWithSelector(ITipping.AlreadyRegistered.selector, address(c721))); - tipping.registerCollection(address(c721)); + function test_contentSign_burnedTokenReverts() public { + // ERC721 `ownerOf` reverts for a burned token; an owner-less success is covered by the mock below. + cs.mint(BOB, 2); + vm.prank(BOB); + cs.transferFrom(BOB, address(0xDEAD), 2); + assertEq(tipping.resolveRecipient(address(cs), 2), address(0xDEAD)); } - function test_zeroAmountRevertsEvenWithZeroMinimum() public { - vm.prank(ADMIN); - tipping.setMinTipAmount(0); - cs.mint(BOB, 1); - vm.prank(ALICE); - vm.expectRevert(abi.encodeWithSelector(ITipping.BelowMinimum.selector, 0, 0)); - tipping.tip(address(cs), 1, 0); + function test_contentSign_zeroOwnerReverts() public { + // A contract whose `ownerOf` answers address(0) is not a valid recipient. + ZeroOwnerMock z = new ZeroOwnerMock(); + vm.prank(REGISTRY); + tipping.setCollectionAllowed(address(z), true); + vm.expectRevert(abi.encodeWithSelector(ITipping.NoRecipient.selector, address(z), 1)); + tipping.resolveRecipient(address(z), 1); } - function test_feeRecipientCannotBeSelfOrToken() public { - vm.startPrank(ADMIN); - vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidFeeRecipient.selector, address(tipping))); - tipping.setFeeRecipient(address(tipping)); - vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidFeeRecipient.selector, address(nodl))); - tipping.setFeeRecipient(address(nodl)); - vm.stopPrank(); + function test_contentSign_disallowedFallsThroughToRegistry() public { + cs.mint(BOB, 7); + vm.prank(REGISTRY); + vm.expectEmit(true, true, true, true); + emit ITipping.CollectionAllowed(address(cs), false); + tipping.setCollectionAllowed(address(cs), false); + assertFalse(tipping.contentSignAllowed(address(cs))); + vm.prank(ALICE); + vm.expectRevert(abi.encodeWithSelector(ITipping.UnknownCollection.selector, address(cs))); + tipping.tip(address(cs), 7, 5e18); } + // ───────── Factory path ───────── + function test_factory721_royaltyReceiverElseCreator() public { vm.prank(CREATOR); tipping.registerCollection(address(c721)); c721.mint(BOB, 1); + assertEq(tipping.resolveRecipient(address(c721), 1), CREATOR); vm.prank(ALICE); tipping.tip(address(c721), 1, 2e18); assertEq(nodl.balanceOf(CREATOR), 2e18); + c721.setRoyalty(SPLITTER, 500); + assertEq(tipping.resolveRecipient(address(c721), 1), SPLITTER); vm.prank(ALICE); tipping.tip(address(c721), 1, 2e18); assertEq(nodl.balanceOf(SPLITTER), 2e18); + + // Deleting the royalty makes `royaltyInfo` answer address(0): back to the creator. + c721.deleteRoyalty(); + assertEq(tipping.resolveRecipient(address(c721), 1), CREATOR); + } + + function test_factory721_unmintedTokenStillResolves() public { + // ERC-721 ids are not supply-checked: the creator is paid for any id of a registered collection. + vm.prank(CREATOR); + tipping.registerCollection(address(c721)); + assertEq(tipping.resolveRecipient(address(c721), 999), CREATOR); } function test_factory1155_zeroSupplyReverts_thenResolves() public { @@ -142,10 +262,133 @@ contract TippingTest is Test { assertEq(nodl.balanceOf(CREATOR), 2e18); } + function test_factory1155_royaltyReceiver() public { + c1155.mint(BOB, 3, 10); + c1155.setRoyalty(SPLITTER, 100); + assertEq(tipping.resolveRecipient(address(c1155), 3), SPLITTER); + } + + function test_registeredContractWithoutErc165ResolvesToCreator() public { + // No `supportsInterface`, no `royaltyInfo`: every lookup fails softly and the creator is paid. + vm.prank(REGISTRY); + tipping.setCreator(address(nodl), CREATOR); + assertEq(tipping.resolveRecipient(address(nodl), 1), CREATOR); + } + + function test_registeredContractWithShortReturnsResolvesToCreator() public { + ShortReturnMock s = new ShortReturnMock(); + vm.prank(REGISTRY); + tipping.setCreator(address(s), CREATOR); + assertEq(tipping.resolveRecipient(address(s), 1), CREATOR); + vm.prank(REGISTRY); + tipping.setCollectionAllowed(address(s), true); + vm.expectRevert(abi.encodeWithSelector(ITipping.UnknownToken.selector, address(s), 1)); + tipping.resolveRecipient(address(s), 1); + } + function test_unknownCollectionReverts() public { vm.prank(ALICE); vm.expectRevert(abi.encodeWithSelector(ITipping.UnknownCollection.selector, address(0x1234))); tipping.tip(address(0x1234), 1, 2e18); + // An ERC-2981 contract that nobody registered is unknown too: the registry is the gate. + vm.expectRevert(abi.encodeWithSelector(ITipping.UnknownCollection.selector, address(c721))); + tipping.resolveRecipient(address(c721), 1); + } + + function test_lookupGasIsCapped() public { + GasBombMock bomb = new GasBombMock(); + vm.prank(REGISTRY); + tipping.setCollectionAllowed(address(bomb), true); + uint256 before = gasleft(); + vm.expectRevert(abi.encodeWithSelector(ITipping.UnknownToken.selector, address(bomb), 1)); + tipping.resolveRecipient(address(bomb), 1); + assertLt(before - gasleft(), 3 * tipping.LOOKUP_GAS()); + + vm.prank(REGISTRY); + tipping.setCollectionAllowed(address(bomb), false); + vm.prank(REGISTRY); + tipping.setCreator(address(bomb), CREATOR); + before = gasleft(); + // supportsInterface and royaltyInfo both burn their cap; the creator is still resolved. + assertEq(tipping.resolveRecipient(address(bomb), 1), CREATOR); + assertLt(before - gasleft(), 4 * tipping.LOOKUP_GAS()); + } + + // ───────── Registry ───────── + + function test_registerCollection_ownerOnly() public { + vm.prank(ALICE); + vm.expectRevert(abi.encodeWithSelector(ITipping.NotCollectionOwner.selector, address(c721), ALICE)); + tipping.registerCollection(address(c721)); + vm.prank(CREATOR); + vm.expectEmit(true, true, true, true); + emit ITipping.CreatorSet(address(c721), CREATOR); + tipping.registerCollection(address(c721)); + assertEq(tipping.creatorOf(address(c721)), CREATOR); + vm.prank(CREATOR); + vm.expectRevert(abi.encodeWithSelector(ITipping.AlreadyRegistered.selector, address(c721))); + tipping.registerCollection(address(c721)); + } + + function test_registerCollection_rejectsZeroAndEoa() public { + vm.expectRevert(ITipping.ZeroAddress.selector); + tipping.registerCollection(address(0)); + // An EOA answers every staticcall with empty data. + vm.prank(ALICE); + vm.expectRevert(abi.encodeWithSelector(ITipping.NotCollectionOwner.selector, address(0xE0A), ALICE)); + tipping.registerCollection(address(0xE0A)); + } + + function test_registerCollection_anyContractAttestingOwnerRole() public { + OpenOwnerMock open = new OpenOwnerMock(); + vm.prank(BOB); + tipping.registerCollection(address(open)); + assertEq(tipping.creatorOf(address(open)), BOB); + } + + function test_registryEntryWinsAndCanBeCleared() public { + vm.prank(REGISTRY); + tipping.setCreator(address(c721), SPLITTER); + vm.prank(CREATOR); + vm.expectRevert(abi.encodeWithSelector(ITipping.AlreadyRegistered.selector, address(c721))); + tipping.registerCollection(address(c721)); + + vm.prank(REGISTRY); + vm.expectEmit(true, true, true, true); + emit ITipping.CreatorSet(address(c721), address(0)); + tipping.setCreator(address(c721), address(0)); + vm.expectRevert(abi.encodeWithSelector(ITipping.UnknownCollection.selector, address(c721))); + tipping.resolveRecipient(address(c721), 1); + + vm.prank(CREATOR); + tipping.registerCollection(address(c721)); + assertEq(tipping.creatorOf(address(c721)), CREATOR); + } + + function test_registrySettersRejectZeroCollection() public { + vm.startPrank(REGISTRY); + vm.expectRevert(ITipping.ZeroAddress.selector); + tipping.setCreator(address(0), CREATOR); + vm.expectRevert(ITipping.ZeroAddress.selector); + tipping.setCollectionAllowed(address(0), true); + vm.stopPrank(); + } + + // ───────── Guards ───────── + + function test_zeroAmountRevertsEvenWithZeroMinimum() public { + vm.prank(ADMIN); + vm.expectEmit(true, true, true, true); + emit ITipping.MinTipUpdated(0); + tipping.setMinTipAmount(0); + cs.mint(BOB, 1); + vm.prank(ALICE); + vm.expectRevert(abi.encodeWithSelector(ITipping.BelowMinimum.selector, 0, 0)); + tipping.tip(address(cs), 1, 0); + // One wei is fine once the minimum is zero. + vm.prank(ALICE); + tipping.tip(address(cs), 1, 1); + assertEq(nodl.balanceOf(BOB), 1); } function test_selfTipAndDustRevert() public { @@ -158,37 +401,165 @@ contract TippingTest is Test { vm.stopPrank(); } + function test_insufficientAllowanceOrBalanceReverts() public { + cs.mint(BOB, 1); + nodl.mint(address(0xC0), 10e18); + vm.prank(address(0xC0)); + vm.expectRevert(); + tipping.tip(address(cs), 1, 2e18); + vm.prank(address(0xC0)); + nodl.approve(address(tipping), type(uint256).max); + vm.prank(address(0xC0)); + vm.expectRevert(); + tipping.tip(address(cs), 1, 11e18); + } + + function test_pauseBlocksTips() public { + vm.prank(ADMIN); + vm.expectEmit(true, true, true, true); + emit Pausable.Paused(ADMIN); + tipping.pause(); + cs.mint(BOB, 1); + vm.prank(ALICE); + vm.expectRevert(Pausable.EnforcedPause.selector); + tipping.tip(address(cs), 1, 2e18); + // Resolution stays readable while paused; the registry keeps working. + assertEq(tipping.resolveRecipient(address(cs), 1), BOB); + vm.prank(REGISTRY); + tipping.setCreator(address(c721), CREATOR); + + vm.prank(ADMIN); + vm.expectEmit(true, true, true, true); + emit Pausable.Unpaused(ADMIN); + tipping.unpause(); + vm.prank(ALICE); + tipping.tip(address(cs), 1, 2e18); + assertEq(nodl.balanceOf(BOB), 2e18); + } + + // ───────── Fees ───────── + function test_feeSplitAndCap() public { vm.prank(ADMIN); + vm.expectEmit(true, true, true, true); + emit ITipping.FeeUpdated(250); tipping.setFee(250); vm.prank(ADMIN); + vm.expectEmit(true, true, true, true); + emit ITipping.FeeRecipientUpdated(address(0xFEE)); tipping.setFeeRecipient(address(0xFEE)); cs.mint(BOB, 1); + vm.expectEmit(true, true, true, true); + emit ITipping.Tipped(ALICE, address(cs), 1, BOB, 100e18, 2.5e18); vm.prank(ALICE); tipping.tip(address(cs), 1, 100e18); assertEq(nodl.balanceOf(BOB), 97.5e18); assertEq(nodl.balanceOf(address(0xFEE)), 2.5e18); + assertEq(nodl.transfers(), 2); + vm.prank(ADMIN); vm.expectRevert(abi.encodeWithSelector(ITipping.FeeTooHigh.selector, 1001)); tipping.setFee(1001); + vm.prank(ADMIN); + tipping.setFee(1000); + assertEq(tipping.feeBps(), 1000); } - function test_pauseBlocksTips() public { + function test_feeRoundsDownInFavourOfRecipient() public { vm.prank(ADMIN); - tipping.pause(); + tipping.setFee(1); // 0.01% + vm.prank(ADMIN); + tipping.setMinTipAmount(0); cs.mint(BOB, 1); vm.prank(ALICE); - vm.expectRevert(Pausable.EnforcedPause.selector); - tipping.tip(address(cs), 1, 2e18); + tipping.tip(address(cs), 1, 9_999); + assertEq(nodl.balanceOf(BOB), 9_999); + assertEq(nodl.balanceOf(ADMIN), 0); + } + + function test_feeRecipientCannotBeZeroSelfOrToken() public { + vm.startPrank(ADMIN); + vm.expectRevert(ITipping.ZeroAddress.selector); + tipping.setFeeRecipient(address(0)); + vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidFeeRecipient.selector, address(tipping))); + tipping.setFeeRecipient(address(tipping)); + vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidFeeRecipient.selector, address(nodl))); + tipping.setFeeRecipient(address(nodl)); + vm.stopPrank(); } + // ───────── Roles ───────── + function test_rolesSeparated() public { bytes32 registryRole = tipping.REGISTRY_ROLE(); - vm.prank(ADMIN); + vm.startPrank(ADMIN); vm.expectRevert(abi.encodeWithSelector(IAccessControl.AccessControlUnauthorizedAccount.selector, ADMIN, registryRole)); tipping.setCollectionAllowed(address(cs), false); - vm.prank(REGISTRY); - vm.expectRevert(abi.encodeWithSelector(IAccessControl.AccessControlUnauthorizedAccount.selector, REGISTRY, bytes32(0))); + vm.expectRevert(abi.encodeWithSelector(IAccessControl.AccessControlUnauthorizedAccount.selector, ADMIN, registryRole)); + tipping.setCreator(address(c721), CREATOR); + vm.stopPrank(); + + vm.startPrank(REGISTRY); + bytes memory denied = abi.encodeWithSelector(IAccessControl.AccessControlUnauthorizedAccount.selector, REGISTRY, bytes32(0)); + vm.expectRevert(denied); tipping.setFee(1); + vm.expectRevert(denied); + tipping.setFeeRecipient(address(0xFEE)); + vm.expectRevert(denied); + tipping.setMinTipAmount(1); + vm.expectRevert(denied); + tipping.pause(); + vm.expectRevert(denied); + tipping.unpause(); + vm.stopPrank(); + } + + // ───────── Fuzz ───────── + + /// @dev The immutability argument: NODL only ever leaves the caller's own balance. + function testFuzz_transferFromOnlyFromCaller(address tipper, uint256 amount, uint16 bps) public { + vm.assume(tipper != address(0) && tipper != BOB && tipper != ADMIN && tipper != address(nodl) && tipper != address(tipping)); + amount = bound(amount, MIN, 1e30); + bps = uint16(bound(bps, 0, 1000)); + vm.prank(ADMIN); + tipping.setFee(bps); + cs.mint(BOB, 1); + nodl.mint(tipper, amount); + vm.prank(tipper); + nodl.approve(address(tipping), amount); + + vm.prank(tipper); + tipping.tip(address(cs), 1, amount); + + uint256 fee = (amount * bps) / 10_000; + uint256 n = nodl.transfers(); + uint256 moved; + for (uint256 i; i < n; i++) { + assertEq(nodl.froms(i), tipper); + moved += nodl.amounts(i); + } + assertEq(moved, amount); + assertEq(nodl.balanceOf(tipper), 0); + assertEq(nodl.balanceOf(BOB), amount - fee); + assertEq(nodl.balanceOf(ADMIN), fee); + assertEq(n, fee > 0 ? 2 : 1); + } + + function testFuzz_belowMinimumReverts(uint256 minimum, uint256 amount) public { + minimum = bound(minimum, 1, 1e30); + amount = bound(amount, 0, minimum - 1); + vm.prank(ADMIN); + tipping.setMinTipAmount(minimum); + cs.mint(BOB, 1); + vm.prank(ALICE); + vm.expectRevert(abi.encodeWithSelector(ITipping.BelowMinimum.selector, amount, minimum)); + tipping.tip(address(cs), 1, amount); + } +} + +/// @dev `ownerOf` succeeds with address(0): the resolver must not pay the zero address. +contract ZeroOwnerMock { + function ownerOf(uint256) external pure returns (address) { + return address(0); } } From 18889a820c357dba8f891c39855c877158b3f93d Mon Sep 17 00:00:00 2001 From: douglasacost Date: Tue, 27 Oct 2026 13:17:40 -0400 Subject: [PATCH 04/18] feat(tipping): fork test, deploy and seed scripts, EraVM gas check, coverage gate - test/tipping/TippingZkSyncFork.t.sol: The Turtle registers via OWNER_ROLE and resolves to its creator, a legacy ClickContentSign token resolves to its owner (skipped without ZKSYNC_RPC_URL) - LOOKUP_GAS checked on EraVM with eth_call gas limits against mainnet: heaviest lookup (royaltyInfo through the Turtle proxy) needs ~70k including node overhead, cap is 100k - script/DeployTippingZkSync.s.sol (constructor-only deploy) and script/SeedTippingZkSync.s.sol (idempotent allowlist + creator seed) - CI: coverage job includes test/tipping, 95% line gate on src/tipping --- .github/workflows/checks.yml | 35 +++++++++- script/DeployTippingZkSync.s.sol | 56 ++++++++++++++++ script/SeedTippingZkSync.s.sol | 58 +++++++++++++++++ src/tipping/Tipping.sol | 27 ++++---- test/tipping/Tipping.t.sol | 16 +++-- test/tipping/TippingZkSyncFork.t.sol | 96 ++++++++++++++++++++++++++++ 6 files changed, 269 insertions(+), 19 deletions(-) create mode 100644 script/DeployTippingZkSync.s.sol create mode 100644 script/SeedTippingZkSync.s.sol create mode 100644 test/tipping/TippingZkSyncFork.t.sol diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 449de7dc..7c4918fe 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -53,7 +53,7 @@ jobs: run: yarn - name: Run coverage - run: forge coverage --match-path "test/{Swarm*,ServiceProvider,FleetIdentity,collections/*}*.t.sol" --ir-minimum --report lcov --report-file coverage.lcov + run: forge coverage --match-path "test/{Swarm*,ServiceProvider,FleetIdentity,collections/*,tipping/*}*.t.sol" --ir-minimum --report lcov --report-file coverage.lcov - name: Upload coverage report uses: actions/upload-artifact@v4 @@ -144,6 +144,39 @@ jobs: echo "Coverage check passed: $COVERAGE% >= $THRESHOLD%" + - name: Check line coverage threshold (tipping) + run: | + # Extract line coverage from lcov report for src/tipping/ contracts only + LINES_FOUND=$(awk ' + /^SF:.*src\/tipping\// { in_section = 1 } + /^end_of_record/ { in_section = 0 } + in_section && /^LF:/ { sum += substr($0, 4) } + END { print sum+0 } + ' coverage.lcov) + + LINES_HIT=$(awk ' + /^SF:.*src\/tipping\// { in_section = 1 } + /^end_of_record/ { in_section = 0 } + in_section && /^LH:/ { sum += substr($0, 4) } + END { print sum+0 } + ' coverage.lcov) + + if [ "$LINES_FOUND" -eq 0 ]; then + echo "Error: No lines found in coverage report for src/tipping/" + exit 1 + fi + + COVERAGE=$(awk "BEGIN {printf \"%.2f\", ($LINES_HIT / $LINES_FOUND) * 100}") + echo "Tipping line coverage: $COVERAGE% ($LINES_HIT / $LINES_FOUND lines)" + + THRESHOLD=95 + if awk "BEGIN {exit !($COVERAGE < $THRESHOLD)}"; then + echo "Error: Line coverage ($COVERAGE%) is below the required threshold ($THRESHOLD%)" + exit 1 + fi + + echo "Coverage check passed: $COVERAGE% >= $THRESHOLD%" + Specification-PDF: runs-on: ubuntu-latest if: github.event_name == 'pull_request' && github.base_ref == 'main' diff --git a/script/DeployTippingZkSync.s.sol b/script/DeployTippingZkSync.s.sol new file mode 100644 index 00000000..8357c096 --- /dev/null +++ b/script/DeployTippingZkSync.s.sol @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: BSD-3-Clause-Clear +pragma solidity ^0.8.26; + +import {Script, console} from "forge-std/Script.sol"; + +import {Tipping} from "../src/tipping/Tipping.sol"; + +/** + * @title DeployTippingZkSync + * @notice Deploys the immutable `Tipping` contract (nft-feed-indexer design §6.2, meta#242). + * No proxy, no initializer: the constructor sets everything, so a mistaken input + * means a new deployment, not an upgrade. Fee starts at 0 with the admin as recipient. + * + * Usage (zkSync Sepolia first, then mainnet): + * forge script script/DeployTippingZkSync.s.sol --rpc-url $L2_RPC --broadcast --zksync + * + * Environment Variables: + * - DEPLOYER_PRIVATE_KEY: Private key with ETH for gas. + * - N_TIPPING_NODL: NODL ERC-20 on the target chain. + * - N_TIPPING_ADMIN: Multisig that will hold DEFAULT_ADMIN_ROLE (fee, fee recipient, minimum, pause). + * - N_TIPPING_REGISTRY: Operator key that will hold REGISTRY_ROLE (allowlist, creator registry); + * the same key that calls `CollectionFactory.createCollection`. + * - N_TIPPING_MIN_TIP: Initial `minTipAmount` in NODL wei (e.g. 1000000000000000000 for 1 NODL). + */ +contract DeployTippingZkSync is Script { + address public tipping; + + function run() external { + uint256 deployerPrivateKey = vm.envUint("DEPLOYER_PRIVATE_KEY"); + address nodl = vm.envAddress("N_TIPPING_NODL"); + address admin = vm.envAddress("N_TIPPING_ADMIN"); + address registry = vm.envAddress("N_TIPPING_REGISTRY"); + uint256 minTip = vm.envUint("N_TIPPING_MIN_TIP"); + + require(nodl != address(0), "N_TIPPING_NODL is zero"); + require(nodl.code.length > 0, "N_TIPPING_NODL is not a contract"); + require(admin != address(0), "N_TIPPING_ADMIN is zero"); + require(registry != address(0), "N_TIPPING_REGISTRY is zero"); + + console.log("=== Deploying Tipping on ZkSync ==="); + console.log("NODL:", nodl); + console.log("Admin:", admin); + console.log("Registry:", registry); + console.log("Min tip (wei):", minTip); + console.log(""); + + vm.startBroadcast(deployerPrivateKey); + tipping = address(new Tipping(nodl, admin, registry, minTip)); + vm.stopBroadcast(); + + console.log("Tipping:", tipping); + console.log(""); + console.log("Next: record the address and deploy block in the indexer (chains.ts `tipping`),"); + console.log("then run script/SeedTippingZkSync.s.sol with the REGISTRY key."); + } +} diff --git a/script/SeedTippingZkSync.s.sol b/script/SeedTippingZkSync.s.sol new file mode 100644 index 00000000..0b353199 --- /dev/null +++ b/script/SeedTippingZkSync.s.sol @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: BSD-3-Clause-Clear +pragma solidity ^0.8.26; + +import {Script, console} from "forge-std/Script.sol"; + +import {Tipping} from "../src/tipping/Tipping.sol"; + +/** + * @title SeedTippingZkSync + * @notice One-off registry seed after deployment (meta#242): allowlists the ContentSign-type + * contracts and registers the creator of every factory collection created before + * `Tipping` existed. Later collections register themselves (owner calls + * `registerCollection`) or are set by the operator at creation time. + * + * Idempotent: entries already in the wanted state are skipped, so the script can be + * re-run after a partial broadcast. + * + * Usage: + * forge script script/SeedTippingZkSync.s.sol --rpc-url $L2_RPC --broadcast --zksync + * + * Environment Variables: + * - REGISTRY_PRIVATE_KEY: Key holding REGISTRY_ROLE on `Tipping`. + * - N_TIPPING: Deployed `Tipping` address. + * - N_TIPPING_ALLOWLIST: Comma-separated ContentSign-type contracts to allowlist + * (mainnet: the four legacy ClickContentSign contracts). + * - N_TIPPING_COLLECTIONS: Comma-separated factory collections (from `CollectionCreated`). + * - N_TIPPING_CREATORS: Comma-separated creators, same order (`CollectionCreated.owner`). + * Both may be empty on a fresh chain. + */ +contract SeedTippingZkSync is Script { + function run() external { + uint256 registryKey = vm.envUint("REGISTRY_PRIVATE_KEY"); + Tipping tipping = Tipping(vm.envAddress("N_TIPPING")); + address[] memory allow = vm.envOr("N_TIPPING_ALLOWLIST", ",", new address[](0)); + address[] memory collections = vm.envOr("N_TIPPING_COLLECTIONS", ",", new address[](0)); + address[] memory creators = vm.envOr("N_TIPPING_CREATORS", ",", new address[](0)); + require(collections.length == creators.length, "collections/creators length mismatch"); + + console.log("=== Seeding Tipping registry ==="); + console.log("Tipping:", address(tipping)); + console.log("Allowlist entries:", allow.length); + console.log("Creator entries:", collections.length); + + vm.startBroadcast(registryKey); + for (uint256 i; i < allow.length; i++) { + if (tipping.contentSignAllowed(allow[i])) continue; + tipping.setCollectionAllowed(allow[i], true); + console.log("allowed:", allow[i]); + } + for (uint256 i; i < collections.length; i++) { + require(creators[i] != address(0), "creator is zero"); + if (tipping.creatorOf(collections[i]) == creators[i]) continue; + tipping.setCreator(collections[i], creators[i]); + console.log("creator set:", collections[i], creators[i]); + } + vm.stopBroadcast(); + } +} diff --git a/src/tipping/Tipping.sol b/src/tipping/Tipping.sol index cf3621b3..691745c3 100644 --- a/src/tipping/Tipping.sol +++ b/src/tipping/Tipping.sol @@ -44,8 +44,11 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard, Pausable { bytes32 public constant COLLECTION_OWNER_ROLE = keccak256("OWNER_ROLE"); uint16 public constant MAX_FEE_BPS = 1000; uint256 public constant BPS = 10_000; - /// @dev Gas cap for every static lookup into a collection. Sized for the EVM; confirm on - /// EraVM through the real ContentSign/UserCollection proxies before deploy (slice 6). + /// @dev Gas cap for every static lookup into a collection. Checked on EraVM (zkSync Era + /// mainnet, 2026-10-27) through the real contracts with `eth_call` gas limits: a trivial + /// call needs ~59k including the node's call overhead, and the heaviest lookup + /// (`royaltyInfo` through The Turtle's ERC1967 proxy) ~70k, so each lookup itself is + /// well under 12k. See test/tipping/TippingZkSyncFork.t.sol. uint256 public constant LOOKUP_GAS = 100_000; IERC20 private immutable _nodl; @@ -92,9 +95,8 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard, Pausable { function _resolve(address collection, uint256 tokenId) internal view returns (address recipient) { if (contentSignAllowed[collection]) { - (bool ok, bytes memory data) = collection.staticcall{gas: LOOKUP_GAS}( - abi.encodeCall(IERC721.ownerOf, (tokenId)) - ); + (bool ok, bytes memory data) = + collection.staticcall{gas: LOOKUP_GAS}(abi.encodeCall(IERC721.ownerOf, (tokenId))); if (!ok || data.length < 32) revert UnknownToken(collection, tokenId); recipient = abi.decode(data, (address)); if (recipient == address(0)) revert NoRecipient(collection, tokenId); @@ -105,15 +107,13 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard, Pausable { if (creator == address(0)) revert UnknownCollection(collection); if (_supports(collection, type(IERC1155).interfaceId)) { - (bool ok, bytes memory data) = collection.staticcall{gas: LOOKUP_GAS}( - abi.encodeCall(IERC1155Supply.totalSupply, (tokenId)) - ); + (bool ok, bytes memory data) = + collection.staticcall{gas: LOOKUP_GAS}(abi.encodeCall(IERC1155Supply.totalSupply, (tokenId))); if (!ok || data.length < 32 || abi.decode(data, (uint256)) == 0) revert UnknownToken(collection, tokenId); } - (bool rOk, bytes memory rData) = collection.staticcall{gas: LOOKUP_GAS}( - abi.encodeCall(IERC2981.royaltyInfo, (tokenId, 1e18)) - ); + (bool rOk, bytes memory rData) = + collection.staticcall{gas: LOOKUP_GAS}(abi.encodeCall(IERC2981.royaltyInfo, (tokenId, 1e18))); if (rOk && rData.length >= 64) { (address receiver,) = abi.decode(rData, (address, uint256)); if (receiver != address(0)) return receiver; @@ -122,9 +122,8 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard, Pausable { } function _supports(address target, bytes4 interfaceId) internal view returns (bool) { - (bool ok, bytes memory data) = target.staticcall{gas: LOOKUP_GAS}( - abi.encodeCall(IERC165.supportsInterface, (interfaceId)) - ); + (bool ok, bytes memory data) = + target.staticcall{gas: LOOKUP_GAS}(abi.encodeCall(IERC165.supportsInterface, (interfaceId))); return ok && data.length >= 32 && abi.decode(data, (bool)); } diff --git a/test/tipping/Tipping.t.sol b/test/tipping/Tipping.t.sol index 03b78dc1..1dcc64d5 100644 --- a/test/tipping/Tipping.t.sol +++ b/test/tipping/Tipping.t.sol @@ -493,14 +493,19 @@ contract TippingTest is Test { function test_rolesSeparated() public { bytes32 registryRole = tipping.REGISTRY_ROLE(); vm.startPrank(ADMIN); - vm.expectRevert(abi.encodeWithSelector(IAccessControl.AccessControlUnauthorizedAccount.selector, ADMIN, registryRole)); + vm.expectRevert( + abi.encodeWithSelector(IAccessControl.AccessControlUnauthorizedAccount.selector, ADMIN, registryRole) + ); tipping.setCollectionAllowed(address(cs), false); - vm.expectRevert(abi.encodeWithSelector(IAccessControl.AccessControlUnauthorizedAccount.selector, ADMIN, registryRole)); + vm.expectRevert( + abi.encodeWithSelector(IAccessControl.AccessControlUnauthorizedAccount.selector, ADMIN, registryRole) + ); tipping.setCreator(address(c721), CREATOR); vm.stopPrank(); vm.startPrank(REGISTRY); - bytes memory denied = abi.encodeWithSelector(IAccessControl.AccessControlUnauthorizedAccount.selector, REGISTRY, bytes32(0)); + bytes memory denied = + abi.encodeWithSelector(IAccessControl.AccessControlUnauthorizedAccount.selector, REGISTRY, bytes32(0)); vm.expectRevert(denied); tipping.setFee(1); vm.expectRevert(denied); @@ -518,7 +523,10 @@ contract TippingTest is Test { /// @dev The immutability argument: NODL only ever leaves the caller's own balance. function testFuzz_transferFromOnlyFromCaller(address tipper, uint256 amount, uint16 bps) public { - vm.assume(tipper != address(0) && tipper != BOB && tipper != ADMIN && tipper != address(nodl) && tipper != address(tipping)); + vm.assume( + tipper != address(0) && tipper != BOB && tipper != ADMIN && tipper != address(nodl) + && tipper != address(tipping) + ); amount = bound(amount, MIN, 1e30); bps = uint16(bound(bps, 0, 1000)); vm.prank(ADMIN); diff --git a/test/tipping/TippingZkSyncFork.t.sol b/test/tipping/TippingZkSyncFork.t.sol new file mode 100644 index 00000000..d7fa8e68 --- /dev/null +++ b/test/tipping/TippingZkSyncFork.t.sol @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: BSD-3-Clause-Clear +pragma solidity ^0.8.26; + +import {Test} from "forge-std/Test.sol"; +import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; + +import {Tipping} from "../../src/tipping/Tipping.sol"; +import {ITipping} from "../../src/tipping/ITipping.sol"; + +/** + * @title TippingZkSyncForkTest + * @notice Recipient resolution against the real zkSync Era mainnet contracts: The Turtle + * (factory ERC-1155) resolves to its registered creator, and a legacy ClickContentSign + * token resolves to its owner. Also the EraVM check for `LOOKUP_GAS`: every static + * lookup through the real proxies must fit the cap (meta#242 acceptance). + * + * Skipped unless ZKSYNC_RPC_URL is set: + * ZKSYNC_RPC_URL=https://mainnet.era.zksync.io forge test --match-contract TippingZkSyncForkTest -vv + * + * On a plain fork the forked contracts run as EVM bytecode, so the gas numbers are EVM + * numbers. `forge test --zksync` crashes in this repo's linker (foundry-zksync v0.1.9, + * "no EVM bytecode (or unlinked)"), so the EraVM figure for `LOOKUP_GAS` was taken with + * `cast call --gas-limit` against mainnet instead (2026-10-27): minimum eth_call gas that + * succeeds, node overhead included: name() 59,375 (baseline); ownerOf 59,375; + * supportsInterface 65,625; totalSupply 67,187; hasRole 68,750; royaltyInfo 70,312. + */ +contract TippingZkSyncForkTest is Test { + address internal constant TURTLE = 0x08820bBb37B401983683334B00668a2a8555CC74; + address internal constant TURTLE_OWNER = 0xfe74C8C3f3F1ca3D4b523fd1AE7A3d82dbAc5eCe; + address internal constant CLICK_CONTENTSIGN = 0x95b3641d549f719eb5105f9550Eca4A7A2F305De; + uint256 internal constant CLICK_TOKEN = 1; + + address internal constant ADMIN = address(0xAD); + address internal constant REGISTRY = address(0x09); + + Tipping internal tipping; + bool internal skipAll; + + function setUp() public { + string memory rpc = vm.envOr("ZKSYNC_RPC_URL", string("")); + if (bytes(rpc).length == 0) { + skipAll = true; + return; + } + vm.createSelectFork(rpc); + // The token address only has to be non-zero for resolution tests; no transfer happens here. + tipping = new Tipping(address(0x1), ADMIN, REGISTRY, 1e18); + vm.prank(REGISTRY); + tipping.setCollectionAllowed(CLICK_CONTENTSIGN, true); + } + + function test_turtle_registersByOwnerAndResolvesToCreator() public { + if (skipAll) return; + // Permissionless path: the collection attests OWNER_ROLE for the caller. + vm.prank(TURTLE_OWNER); + tipping.registerCollection(TURTLE); + assertEq(tipping.creatorOf(TURTLE), TURTLE_OWNER); + // No royalties on The Turtle: the creator is the recipient. + assertEq(tipping.resolveRecipient(TURTLE, 0), TURTLE_OWNER); + // Unminted id: supply is zero. + vm.expectRevert(abi.encodeWithSelector(ITipping.UnknownToken.selector, TURTLE, 999)); + tipping.resolveRecipient(TURTLE, 999); + } + + function test_turtle_nonOwnerCannotRegister() public { + if (skipAll) return; + vm.prank(ADMIN); + vm.expectRevert(abi.encodeWithSelector(ITipping.NotCollectionOwner.selector, TURTLE, ADMIN)); + tipping.registerCollection(TURTLE); + } + + function test_clickContentSign_resolvesToOwner() public { + if (skipAll) return; + address owner = IERC721(CLICK_CONTENTSIGN).ownerOf(CLICK_TOKEN); + assertTrue(owner != address(0)); + assertEq(tipping.resolveRecipient(CLICK_CONTENTSIGN, CLICK_TOKEN), owner); + } + + /// @dev EraVM gas check: the whole resolution, three capped lookups included, must be far + /// below what a tip transaction carries. Prints the measurement for the deploy record. + function test_lookupGasFitsOnEraVm() public { + if (skipAll) return; + vm.prank(TURTLE_OWNER); + tipping.registerCollection(TURTLE); + uint256 g0 = gasleft(); + tipping.resolveRecipient(TURTLE, 0); + uint256 turtleGas = g0 - gasleft(); + g0 = gasleft(); + tipping.resolveRecipient(CLICK_CONTENTSIGN, CLICK_TOKEN); + uint256 clickGas = g0 - gasleft(); + emit log_named_uint("resolve(The Turtle) gas", turtleGas); + emit log_named_uint("resolve(ClickContentSign) gas", clickGas); + assertLt(turtleGas, 3 * tipping.LOOKUP_GAS()); + assertLt(clickGas, tipping.LOOKUP_GAS()); + } +} From 79662b78779771c1b9f68c89691529f08a84e1d2 Mon Sep 17 00:00:00 2001 From: douglasacost Date: Tue, 27 Oct 2026 14:21:39 -0400 Subject: [PATCH 05/18] feat(tipping): agnostic signature-authorized tipping (any ERC-20, any NFT, account tips) Replaces the on-chain registry/allowlist with an EIP-712 authorization signed by a rotatable signer (the feed API). The contract knows nothing about tokens or NFTs: - tip(TipAuthorization, signature): tipper == msg.sender, signer, deadline, single-use nonce - tipAccount(token, to, amount): caller-named recipient, no signature - fee <= 10% starting at 0, admin-only setters, pause, ERC-1271 signers supported - 25 tests (95.7% line coverage), fuzz that transferFrom is only ever from the caller, fuzz that the digest binds every field - deploy script takes admin + signer; seed script and fork test removed --- script/DeployTippingZkSync.s.sol | 26 +- script/SeedTippingZkSync.s.sol | 58 --- src/tipping/ITipping.sol | 54 ++- src/tipping/Tipping.sol | 194 +++------ test/tipping/Tipping.t.sol | 630 ++++++++++++--------------- test/tipping/TippingZkSyncFork.t.sol | 96 ---- 6 files changed, 392 insertions(+), 666 deletions(-) delete mode 100644 script/SeedTippingZkSync.s.sol delete mode 100644 test/tipping/TippingZkSyncFork.t.sol diff --git a/script/DeployTippingZkSync.s.sol b/script/DeployTippingZkSync.s.sol index 8357c096..bfdcaa49 100644 --- a/script/DeployTippingZkSync.s.sol +++ b/script/DeployTippingZkSync.s.sol @@ -16,41 +16,33 @@ import {Tipping} from "../src/tipping/Tipping.sol"; * * Environment Variables: * - DEPLOYER_PRIVATE_KEY: Private key with ETH for gas. - * - N_TIPPING_NODL: NODL ERC-20 on the target chain. - * - N_TIPPING_ADMIN: Multisig that will hold DEFAULT_ADMIN_ROLE (fee, fee recipient, minimum, pause). - * - N_TIPPING_REGISTRY: Operator key that will hold REGISTRY_ROLE (allowlist, creator registry); - * the same key that calls `CollectionFactory.createCollection`. - * - N_TIPPING_MIN_TIP: Initial `minTipAmount` in NODL wei (e.g. 1000000000000000000 for 1 NODL). + * - N_TIPPING_ADMIN: Multisig that will hold DEFAULT_ADMIN_ROLE (fee, fee recipient, signer, pause). + * - N_TIPPING_SIGNER: Address whose EIP-712 signatures authorize post tips (the feed API's + * signing key, or an ERC-1271 contract). Rotatable by the admin. */ contract DeployTippingZkSync is Script { address public tipping; function run() external { uint256 deployerPrivateKey = vm.envUint("DEPLOYER_PRIVATE_KEY"); - address nodl = vm.envAddress("N_TIPPING_NODL"); address admin = vm.envAddress("N_TIPPING_ADMIN"); - address registry = vm.envAddress("N_TIPPING_REGISTRY"); - uint256 minTip = vm.envUint("N_TIPPING_MIN_TIP"); + address signer = vm.envAddress("N_TIPPING_SIGNER"); - require(nodl != address(0), "N_TIPPING_NODL is zero"); - require(nodl.code.length > 0, "N_TIPPING_NODL is not a contract"); require(admin != address(0), "N_TIPPING_ADMIN is zero"); - require(registry != address(0), "N_TIPPING_REGISTRY is zero"); + require(signer != address(0), "N_TIPPING_SIGNER is zero"); console.log("=== Deploying Tipping on ZkSync ==="); - console.log("NODL:", nodl); console.log("Admin:", admin); - console.log("Registry:", registry); - console.log("Min tip (wei):", minTip); + console.log("Signer:", signer); console.log(""); vm.startBroadcast(deployerPrivateKey); - tipping = address(new Tipping(nodl, admin, registry, minTip)); + tipping = address(new Tipping(admin, signer)); vm.stopBroadcast(); console.log("Tipping:", tipping); console.log(""); - console.log("Next: record the address and deploy block in the indexer (chains.ts `tipping`),"); - console.log("then run script/SeedTippingZkSync.s.sol with the REGISTRY key."); + console.log("Next: record the address and deploy block in the indexer (chains.ts `tipping`)"); + console.log("and point the feed API's tip authorizer at it (same chain id, same address)."); } } diff --git a/script/SeedTippingZkSync.s.sol b/script/SeedTippingZkSync.s.sol deleted file mode 100644 index 0b353199..00000000 --- a/script/SeedTippingZkSync.s.sol +++ /dev/null @@ -1,58 +0,0 @@ -// SPDX-License-Identifier: BSD-3-Clause-Clear -pragma solidity ^0.8.26; - -import {Script, console} from "forge-std/Script.sol"; - -import {Tipping} from "../src/tipping/Tipping.sol"; - -/** - * @title SeedTippingZkSync - * @notice One-off registry seed after deployment (meta#242): allowlists the ContentSign-type - * contracts and registers the creator of every factory collection created before - * `Tipping` existed. Later collections register themselves (owner calls - * `registerCollection`) or are set by the operator at creation time. - * - * Idempotent: entries already in the wanted state are skipped, so the script can be - * re-run after a partial broadcast. - * - * Usage: - * forge script script/SeedTippingZkSync.s.sol --rpc-url $L2_RPC --broadcast --zksync - * - * Environment Variables: - * - REGISTRY_PRIVATE_KEY: Key holding REGISTRY_ROLE on `Tipping`. - * - N_TIPPING: Deployed `Tipping` address. - * - N_TIPPING_ALLOWLIST: Comma-separated ContentSign-type contracts to allowlist - * (mainnet: the four legacy ClickContentSign contracts). - * - N_TIPPING_COLLECTIONS: Comma-separated factory collections (from `CollectionCreated`). - * - N_TIPPING_CREATORS: Comma-separated creators, same order (`CollectionCreated.owner`). - * Both may be empty on a fresh chain. - */ -contract SeedTippingZkSync is Script { - function run() external { - uint256 registryKey = vm.envUint("REGISTRY_PRIVATE_KEY"); - Tipping tipping = Tipping(vm.envAddress("N_TIPPING")); - address[] memory allow = vm.envOr("N_TIPPING_ALLOWLIST", ",", new address[](0)); - address[] memory collections = vm.envOr("N_TIPPING_COLLECTIONS", ",", new address[](0)); - address[] memory creators = vm.envOr("N_TIPPING_CREATORS", ",", new address[](0)); - require(collections.length == creators.length, "collections/creators length mismatch"); - - console.log("=== Seeding Tipping registry ==="); - console.log("Tipping:", address(tipping)); - console.log("Allowlist entries:", allow.length); - console.log("Creator entries:", collections.length); - - vm.startBroadcast(registryKey); - for (uint256 i; i < allow.length; i++) { - if (tipping.contentSignAllowed(allow[i])) continue; - tipping.setCollectionAllowed(allow[i], true); - console.log("allowed:", allow[i]); - } - for (uint256 i; i < collections.length; i++) { - require(creators[i] != address(0), "creator is zero"); - if (tipping.creatorOf(collections[i]) == creators[i]) continue; - tipping.setCreator(collections[i], creators[i]); - console.log("creator set:", collections[i], creators[i]); - } - vm.stopBroadcast(); - } -} diff --git a/src/tipping/ITipping.sol b/src/tipping/ITipping.sol index c55e0362..c47c543f 100644 --- a/src/tipping/ITipping.sol +++ b/src/tipping/ITipping.sol @@ -3,48 +3,60 @@ pragma solidity ^0.8.26; /** * @title ITipping - * @notice NODL tips on NFTs with on-chain recipient resolution. The event and error surface - * is what the feed indexer consumes (nft-feed-indexer design §6.2); keep it stable. + * @notice Agnostic tipping: any ERC-20, any NFT, any account. The contract knows nothing about + * the NFT; the recipient of a post tip is attested off-chain by the Nodle signer (the + * feed API resolves it from indexed data) and verified here as an EIP-712 signature. + * The event surface is what the feed indexer consumes; keep it stable. */ interface ITipping { - /// @notice A tip was paid. `amount` is gross (what the tipper gave); `fee` went to the fee recipient. + /// @notice A post was tipped. `amount` is gross (what the tipper gave); `fee` went to the fee recipient. event Tipped( address indexed tipper, address indexed collection, uint256 indexed tokenId, + address token, address recipient, uint256 amount, uint256 fee ); - /// @notice A ContentSign-type collection was added to or removed from the allowlist. - event CollectionAllowed(address indexed collection, bool allowed); - /// @notice The registered creator of a factory collection changed (zero clears the entry). - event CreatorSet(address indexed collection, address indexed creator); - event MinTipUpdated(uint256 minTipAmount); + /// @notice An account was tipped directly, not tied to a post. + event AccountTipped(address indexed tipper, address indexed to, address token, uint256 amount, uint256 fee); event FeeUpdated(uint16 feeBps); event FeeRecipientUpdated(address indexed feeRecipient); + event SignerUpdated(address indexed signer); // `Paused(address)` / `Unpaused(address)` come from OpenZeppelin Pausable and are part of // the indexed surface too; do not strip them from the generated ABI. error ZeroAddress(); - error BelowMinimum(uint256 amount, uint256 minTipAmount); + error ZeroAmount(); error SelfTip(); - error UnknownCollection(address collection); - error UnknownToken(address collection, uint256 tokenId); - error NoRecipient(address collection, uint256 tokenId); - error NotCollectionOwner(address collection, address account); + error Expired(uint256 deadline); + error NonceUsed(bytes32 nonce); + error InvalidSignature(); error FeeTooHigh(uint16 feeBps); - error AlreadyRegistered(address collection); error InvalidFeeRecipient(address recipient); - function tip(address collection, uint256 tokenId, uint256 amount) external; - function registerCollection(address collection) external; - function resolveRecipient(address collection, uint256 tokenId) external view returns (address); + /// @notice The authorization a post tip carries. Signed by `signer()` over EIP-712. + struct TipAuthorization { + address tipper; + address token; + address collection; + uint256 tokenId; + address recipient; + uint256 amount; + uint256 deadline; + bytes32 nonce; + } - function nodl() external view returns (address); - function minTipAmount() external view returns (uint256); + /// @notice Tip a post. `auth.tipper` must be the caller; `signature` is the signer's EIP-712 signature over `auth`. + function tip(TipAuthorization calldata auth, bytes calldata signature) external; + /// @notice Tip an account the caller names. No authorization needed. + function tipAccount(address token, address to, uint256 amount) external; + + function signer() external view returns (address); function feeBps() external view returns (uint16); function feeRecipient() external view returns (address); - function contentSignAllowed(address collection) external view returns (bool); - function creatorOf(address collection) external view returns (address); + function nonceUsed(bytes32 nonce) external view returns (bool); + /// @notice The EIP-712 digest the signer signs for `auth` (for clients and tests). + function hashAuthorization(TipAuthorization calldata auth) external view returns (bytes32); } diff --git a/src/tipping/Tipping.sol b/src/tipping/Tipping.sol index 691745c3..df900420 100644 --- a/src/tipping/Tipping.sol +++ b/src/tipping/Tipping.sol @@ -2,71 +2,51 @@ pragma solidity ^0.8.26; import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; -import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; -import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; -import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; -import {IERC2981} from "@openzeppelin/contracts/interfaces/IERC2981.sol"; -import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; +import {EIP712} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol"; +import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol"; import {ITipping} from "./ITipping.sol"; -/// @dev The subset of ERC1155Supply the resolver reads. -interface IERC1155Supply { - function totalSupply(uint256 id) external view returns (uint256); -} - /** * @title Tipping - * @notice Immutable NODL tipping for Nodle NFTs (nft-feed-indexer design §6.2). No proxy and - * no upgrade path on purpose: an allowance granted to this address can only ever be - * spent by the approver's own `tip` calls, because `transferFrom` is only called with - * `from == msg.sender`. Everything that may change lives in storage behind roles. + * @notice Immutable, agnostic tipping (nft-feed-indexer design §6.2). No proxy and no upgrade + * path on purpose: an allowance granted to this address can only ever be spent by the + * approver's own `tip`/`tipAccount` calls, because `transferFrom` is only called with + * `from == msg.sender`. The contract holds no funds and knows no token or collection. * - * Recipient resolution (never caller-supplied): - * 1. `contentSignAllowed[collection]` → `ownerOf(tokenId)`. - * 2. `creatorOf[collection] != 0` → ERC-2981 receiver for the token if non-zero, - * else the registered creator. ERC-1155 ids with - * `totalSupply == 0` revert. - * 3. otherwise → `UnknownCollection`. + * Post tips carry a `TipAuthorization` signed by `signer` (the Nodle feed API, which resolves + * the recipient from indexed data: holder, minter or creator, by policy that lives off-chain). + * The authorization binds the tipper, the token, the post, the recipient, the amount, a + * deadline and a single-use nonce, so a signature cannot be replayed or redirected. + * Account tips name their recipient directly and need no signature. * - * Roles: DEFAULT_ADMIN_ROLE (fee, fee recipient, minimum, pause), REGISTRY_ROLE (allowlist, - * creator registry). `registerCollection` is permissionless for a collection's OWNER_ROLE. + * Roles: DEFAULT_ADMIN_ROLE (fee, fee recipient, signer, pause). `signer` is a single address, + * rotated in one call so a leaked key stops working immediately; it may be a contract (ERC-1271). */ -contract Tipping is ITipping, AccessControl, ReentrancyGuard, Pausable { +contract Tipping is ITipping, AccessControl, ReentrancyGuard, Pausable, EIP712 { using SafeERC20 for IERC20; - bytes32 public constant REGISTRY_ROLE = keccak256("REGISTRY_ROLE"); - /// @dev OWNER_ROLE of the factory collections (UserCollection721/1155). - bytes32 public constant COLLECTION_OWNER_ROLE = keccak256("OWNER_ROLE"); uint16 public constant MAX_FEE_BPS = 1000; uint256 public constant BPS = 10_000; - /// @dev Gas cap for every static lookup into a collection. Checked on EraVM (zkSync Era - /// mainnet, 2026-10-27) through the real contracts with `eth_call` gas limits: a trivial - /// call needs ~59k including the node's call overhead, and the heaviest lookup - /// (`royaltyInfo` through The Turtle's ERC1967 proxy) ~70k, so each lookup itself is - /// well under 12k. See test/tipping/TippingZkSyncFork.t.sol. - uint256 public constant LOOKUP_GAS = 100_000; - - IERC20 private immutable _nodl; + bytes32 public constant TIP_AUTHORIZATION_TYPEHASH = keccak256( + "TipAuthorization(address tipper,address token,address collection,uint256 tokenId,address recipient,uint256 amount,uint256 deadline,bytes32 nonce)" + ); - uint256 public minTipAmount; + address public signer; uint16 public feeBps; address public feeRecipient; - mapping(address collection => bool) public contentSignAllowed; - mapping(address collection => address creator) public creatorOf; + mapping(bytes32 nonce => bool used) public nonceUsed; - constructor(address nodlToken, address admin, address registry, uint256 initialMinTip) { - if (nodlToken == address(0) || admin == address(0) || registry == address(0)) revert ZeroAddress(); - _nodl = IERC20(nodlToken); + constructor(address admin, address initialSigner) EIP712("NodleTipping", "1") { + if (admin == address(0) || initialSigner == address(0)) revert ZeroAddress(); _grantRole(DEFAULT_ADMIN_ROLE, admin); - _grantRole(REGISTRY_ROLE, registry); - minTipAmount = initialMinTip; + signer = initialSigner; feeRecipient = admin; - emit MinTipUpdated(initialMinTip); + emit SignerUpdated(initialSigner); emit FeeUpdated(0); emit FeeRecipientUpdated(admin); } @@ -74,94 +54,63 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard, Pausable { // ───────── Tipping ───────── /// @inheritdoc ITipping - function tip(address collection, uint256 tokenId, uint256 amount) external whenNotPaused nonReentrant { - // Zero tips are never meaningful, even when the admin sets the minimum to zero. - if (amount == 0 || amount < minTipAmount) revert BelowMinimum(amount, minTipAmount); - address recipient = _resolve(collection, tokenId); - if (recipient == msg.sender) revert SelfTip(); - - uint256 fee = (amount * feeBps) / BPS; - // Only ever pulls from msg.sender: the property the immutability argument rests on. - _nodl.safeTransferFrom(msg.sender, recipient, amount - fee); - if (fee > 0) _nodl.safeTransferFrom(msg.sender, feeRecipient, fee); - - emit Tipped(msg.sender, collection, tokenId, recipient, amount, fee); - } - - /// @inheritdoc ITipping - function resolveRecipient(address collection, uint256 tokenId) external view returns (address) { - return _resolve(collection, tokenId); - } - - function _resolve(address collection, uint256 tokenId) internal view returns (address recipient) { - if (contentSignAllowed[collection]) { - (bool ok, bytes memory data) = - collection.staticcall{gas: LOOKUP_GAS}(abi.encodeCall(IERC721.ownerOf, (tokenId))); - if (!ok || data.length < 32) revert UnknownToken(collection, tokenId); - recipient = abi.decode(data, (address)); - if (recipient == address(0)) revert NoRecipient(collection, tokenId); - return recipient; - } - - address creator = creatorOf[collection]; - if (creator == address(0)) revert UnknownCollection(collection); - - if (_supports(collection, type(IERC1155).interfaceId)) { - (bool ok, bytes memory data) = - collection.staticcall{gas: LOOKUP_GAS}(abi.encodeCall(IERC1155Supply.totalSupply, (tokenId))); - if (!ok || data.length < 32 || abi.decode(data, (uint256)) == 0) revert UnknownToken(collection, tokenId); + function tip(TipAuthorization calldata auth, bytes calldata signature) external whenNotPaused nonReentrant { + if ( + auth.tipper != msg.sender + || !SignatureChecker.isValidSignatureNow(signer, hashAuthorization(auth), signature) + ) { + revert InvalidSignature(); } + if (block.timestamp > auth.deadline) revert Expired(auth.deadline); + if (nonceUsed[auth.nonce]) revert NonceUsed(auth.nonce); + nonceUsed[auth.nonce] = true; - (bool rOk, bytes memory rData) = - collection.staticcall{gas: LOOKUP_GAS}(abi.encodeCall(IERC2981.royaltyInfo, (tokenId, 1e18))); - if (rOk && rData.length >= 64) { - (address receiver,) = abi.decode(rData, (address, uint256)); - if (receiver != address(0)) return receiver; - } - return creator; - } - - function _supports(address target, bytes4 interfaceId) internal view returns (bool) { - (bool ok, bytes memory data) = - target.staticcall{gas: LOOKUP_GAS}(abi.encodeCall(IERC165.supportsInterface, (interfaceId))); - return ok && data.length >= 32 && abi.decode(data, (bool)); + uint256 fee = _pay(auth.token, auth.recipient, auth.amount); + emit Tipped(msg.sender, auth.collection, auth.tokenId, auth.token, auth.recipient, auth.amount, fee); } - // ───────── Registry ───────── - /// @inheritdoc ITipping - /// @dev Permissionless: succeeds only for an account holding the collection's OWNER_ROLE, - /// and only once. An entry set by REGISTRY_ROLE wins; changes go through the operator. - /// Any contract that attests OWNER_ROLE for the caller can be registered, not only - /// factory collections; the indexer records such collections as UNKNOWN. - function registerCollection(address collection) external { - if (collection == address(0)) revert ZeroAddress(); - if (creatorOf[collection] != address(0)) revert AlreadyRegistered(collection); - (bool ok, bytes memory data) = collection.staticcall{gas: LOOKUP_GAS}( - abi.encodeCall(IAccessControl.hasRole, (COLLECTION_OWNER_ROLE, msg.sender)) - ); - if (!ok || data.length < 32 || !abi.decode(data, (bool))) revert NotCollectionOwner(collection, msg.sender); - creatorOf[collection] = msg.sender; - emit CreatorSet(collection, msg.sender); + function tipAccount(address token, address to, uint256 amount) external whenNotPaused nonReentrant { + uint256 fee = _pay(token, to, amount); + emit AccountTipped(msg.sender, to, token, amount, fee); } - function setCreator(address collection, address creator) external onlyRole(REGISTRY_ROLE) { - if (collection == address(0)) revert ZeroAddress(); - creatorOf[collection] = creator; - emit CreatorSet(collection, creator); + /// @dev Shared guards and transfers. Only ever pulls from msg.sender: the property the + /// immutability argument rests on. Returns the fee taken. + function _pay(address token, address to, uint256 amount) internal returns (uint256 fee) { + if (token == address(0) || to == address(0)) revert ZeroAddress(); + if (amount == 0) revert ZeroAmount(); + if (to == msg.sender) revert SelfTip(); + fee = (amount * feeBps) / BPS; + IERC20(token).safeTransferFrom(msg.sender, to, amount - fee); + if (fee > 0) IERC20(token).safeTransferFrom(msg.sender, feeRecipient, fee); } - function setCollectionAllowed(address collection, bool allowed) external onlyRole(REGISTRY_ROLE) { - if (collection == address(0)) revert ZeroAddress(); - contentSignAllowed[collection] = allowed; - emit CollectionAllowed(collection, allowed); + /// @inheritdoc ITipping + function hashAuthorization(TipAuthorization calldata auth) public view returns (bytes32) { + return _hashTypedDataV4( + keccak256( + abi.encode( + TIP_AUTHORIZATION_TYPEHASH, + auth.tipper, + auth.token, + auth.collection, + auth.tokenId, + auth.recipient, + auth.amount, + auth.deadline, + auth.nonce + ) + ) + ); } // ───────── Admin ───────── - function setMinTipAmount(uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) { - minTipAmount = amount; - emit MinTipUpdated(amount); + function setSigner(address newSigner) external onlyRole(DEFAULT_ADMIN_ROLE) { + if (newSigner == address(0)) revert ZeroAddress(); + signer = newSigner; + emit SignerUpdated(newSigner); } function setFee(uint16 bps) external onlyRole(DEFAULT_ADMIN_ROLE) { @@ -172,8 +121,8 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard, Pausable { function setFeeRecipient(address recipient) external onlyRole(DEFAULT_ADMIN_ROLE) { if (recipient == address(0)) revert ZeroAddress(); - // No rescue path exists in an immutable contract: fees sent here or to the token are lost. - if (recipient == address(this) || recipient == address(_nodl)) revert InvalidFeeRecipient(recipient); + // No rescue path exists in an immutable contract: fees sent to this address are lost. + if (recipient == address(this)) revert InvalidFeeRecipient(recipient); feeRecipient = recipient; emit FeeRecipientUpdated(recipient); } @@ -185,9 +134,4 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard, Pausable { function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } - - /// @inheritdoc ITipping - function nodl() external view returns (address) { - return address(_nodl); - } } diff --git a/test/tipping/Tipping.t.sol b/test/tipping/Tipping.t.sol index 1dcc64d5..573ec1f3 100644 --- a/test/tipping/Tipping.t.sol +++ b/test/tipping/Tipping.t.sol @@ -3,13 +3,10 @@ pragma solidity ^0.8.26; import {Test} from "forge-std/Test.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; -import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -import {ERC1155} from "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; -import {ERC1155Supply} from "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol"; -import {ERC2981} from "@openzeppelin/contracts/token/common/ERC2981.sol"; -import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol"; import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol"; +import {IERC1271} from "@openzeppelin/contracts/interfaces/IERC1271.sol"; +import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import {Tipping} from "../../src/tipping/Tipping.sol"; import {ITipping} from "../../src/tipping/ITipping.sol"; @@ -17,10 +14,9 @@ import {ITipping} from "../../src/tipping/ITipping.sol"; /// @dev Records every `transferFrom` so tests can prove the contract only ever pulls from the caller. contract TokenMock is ERC20 { address[] public froms; - address[] public tos; uint256[] public amounts; - constructor() ERC20("NODL", "NODL") {} + constructor(string memory sym) ERC20(sym, sym) {} function mint(address to, uint256 amount) external { _mint(to, amount); @@ -28,7 +24,6 @@ contract TokenMock is ERC20 { function transferFrom(address from, address to, uint256 value) public override returns (bool) { froms.push(from); - tos.push(to); amounts.push(value); return super.transferFrom(from, to, value); } @@ -38,403 +33,339 @@ contract TokenMock is ERC20 { } } -contract ContentSignMock is ERC721 { - constructor() ERC721("CS", "CS") {} +/// @dev An ERC-1271 signer: valid when the digest was signed by its one owner key. +contract WalletSignerMock is IERC1271 { + address internal immutable owner; - function mint(address to, uint256 id) external { - _mint(to, id); - } -} - -/// @dev Mirrors what the tipping contract reads from a factory collection: OWNER_ROLE, ERC-2981. -contract Collection721Mock is ERC721, ERC2981, AccessControl { - bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); - - constructor(address owner) ERC721("C", "C") { - _grantRole(OWNER_ROLE, owner); - } - - function mint(address to, uint256 id) external { - _mint(to, id); - } - - function setRoyalty(address r, uint96 bps) external { - _setDefaultRoyalty(r, bps); - } - - function deleteRoyalty() external { - _deleteDefaultRoyalty(); - } - - function supportsInterface(bytes4 i) public view override(ERC721, ERC2981, AccessControl) returns (bool) { - return super.supportsInterface(i); - } -} - -contract Collection1155Mock is ERC1155Supply, ERC2981 { - constructor() ERC1155("") {} - - function mint(address to, uint256 id, uint256 n) external { - _mint(to, id, n, ""); + constructor(address owner_) { + owner = owner_; } - function setRoyalty(address r, uint96 bps) external { - _setDefaultRoyalty(r, bps); - } - - function supportsInterface(bytes4 i) public view override(ERC1155, ERC2981) returns (bool) { - return super.supportsInterface(i); - } -} - -/// @dev Burns all forwarded gas on every call: the lookup gas cap must contain it. -contract GasBombMock { - fallback() external { - while (true) {} - } -} - -/// @dev Returns malformed data (too short) for every call. -contract ShortReturnMock { - fallback() external { - assembly { - mstore(0, 1) - return(0, 8) - } - } -} - -/// @dev `hasRole` reports true for everyone: any such contract can be registered by anyone. -contract OpenOwnerMock { - function hasRole(bytes32, address) external pure returns (bool) { - return true; + function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4) { + (address recovered,,) = ECDSA.tryRecover(hash, signature); + return recovered == owner ? IERC1271.isValidSignature.selector : bytes4(0); } } contract TippingTest is Test { TokenMock internal nodl; + TokenMock internal usdc; Tipping internal tipping; - ContentSignMock internal cs; - Collection721Mock internal c721; - Collection1155Mock internal c1155; address internal constant ADMIN = address(0xAD); - address internal constant REGISTRY = address(0x09); - address internal constant CREATOR = address(0xCAFE); address internal constant ALICE = address(0xA1); address internal constant BOB = address(0xB0); - address internal constant SPLITTER = address(0x5111); - uint256 internal constant MIN = 1e18; + address internal constant COLLECTION = address(0xC0111); + uint256 internal constant TOKEN_ID = 7; + + uint256 internal signerKey; + address internal signer; + uint256 internal otherKey; function setUp() public { - nodl = new TokenMock(); - tipping = new Tipping(address(nodl), ADMIN, REGISTRY, MIN); - cs = new ContentSignMock(); - c721 = new Collection721Mock(CREATOR); - c1155 = new Collection1155Mock(); + (signer, signerKey) = makeAddrAndKey("signer"); + (, otherKey) = makeAddrAndKey("other"); + nodl = new TokenMock("NODL"); + usdc = new TokenMock("USDC"); + tipping = new Tipping(ADMIN, signer); nodl.mint(ALICE, 1_000e18); - vm.prank(ALICE); + usdc.mint(ALICE, 1_000e6); + vm.startPrank(ALICE); nodl.approve(address(tipping), type(uint256).max); - vm.prank(REGISTRY); - tipping.setCollectionAllowed(address(cs), true); - vm.prank(REGISTRY); - tipping.setCreator(address(c1155), CREATOR); + usdc.approve(address(tipping), type(uint256).max); + vm.stopPrank(); + } + + // ───────── helpers ───────── + + function auth(address token, address recipient, uint256 amount) + internal + view + returns (ITipping.TipAuthorization memory) + { + return ITipping.TipAuthorization({ + tipper: ALICE, + token: token, + collection: COLLECTION, + tokenId: TOKEN_ID, + recipient: recipient, + amount: amount, + deadline: block.timestamp + 300, + nonce: keccak256(abi.encode(token, recipient, amount, block.timestamp)) + }); + } + + function copy(ITipping.TipAuthorization memory a) internal pure returns (ITipping.TipAuthorization memory b) { + b = ITipping.TipAuthorization( + a.tipper, a.token, a.collection, a.tokenId, a.recipient, a.amount, a.deadline, a.nonce + ); + } + + /// @dev Signs, then calls `tip` as `who`. Signing is an external call, so it must happen + /// before any prank or expectEmit. + function tipAs(address who, uint256 key, ITipping.TipAuthorization memory a) internal { + bytes memory sig = sign(key, a); + vm.prank(who); + tipping.tip(a, sig); + } + + /// @dev Signs first, then expects `tip` as `who` to revert with `data`. + function expectTipRevert(address who, uint256 key, ITipping.TipAuthorization memory a, bytes memory data) internal { + bytes memory sig = sign(key, a); + vm.prank(who); + vm.expectRevert(data); + tipping.tip(a, sig); + } + + function sign(uint256 key, ITipping.TipAuthorization memory a) internal view returns (bytes memory) { + (uint8 v, bytes32 r, bytes32 s) = vm.sign(key, tipping.hashAuthorization(a)); + return abi.encodePacked(r, s, v); } // ───────── Constructor ───────── function test_constructor_state() public view { - assertEq(tipping.nodl(), address(nodl)); - assertEq(tipping.minTipAmount(), MIN); + assertEq(tipping.signer(), signer); assertEq(tipping.feeBps(), 0); assertEq(tipping.feeRecipient(), ADMIN); assertTrue(tipping.hasRole(tipping.DEFAULT_ADMIN_ROLE(), ADMIN)); - assertTrue(tipping.hasRole(tipping.REGISTRY_ROLE(), REGISTRY)); assertFalse(tipping.paused()); - assertEq(tipping.COLLECTION_OWNER_ROLE(), keccak256("OWNER_ROLE")); } function test_constructor_emitsInitialSettings() public { vm.expectEmit(true, true, true, true); - emit ITipping.MinTipUpdated(3); + emit ITipping.SignerUpdated(signer); vm.expectEmit(true, true, true, true); emit ITipping.FeeUpdated(0); vm.expectEmit(true, true, true, true); emit ITipping.FeeRecipientUpdated(ADMIN); - new Tipping(address(nodl), ADMIN, REGISTRY, 3); + new Tipping(ADMIN, signer); } function test_constructor_rejectsZeroAddresses() public { vm.expectRevert(ITipping.ZeroAddress.selector); - new Tipping(address(0), ADMIN, REGISTRY, MIN); - vm.expectRevert(ITipping.ZeroAddress.selector); - new Tipping(address(nodl), address(0), REGISTRY, MIN); + new Tipping(address(0), signer); vm.expectRevert(ITipping.ZeroAddress.selector); - new Tipping(address(nodl), ADMIN, address(0), MIN); + new Tipping(ADMIN, address(0)); + } + + function test_eip712Domain() public view { + (, string memory name, string memory version, uint256 chainId, address verifying,,) = tipping.eip712Domain(); + assertEq(name, "NodleTipping"); + assertEq(version, "1"); + assertEq(chainId, block.chainid); + assertEq(verifying, address(tipping)); } - // ───────── ContentSign path ───────── + // ───────── Post tips ───────── - function test_contentSign_tipGoesToOwner() public { - cs.mint(BOB, 7); - assertEq(tipping.resolveRecipient(address(cs), 7), BOB); + function test_tip_paysRecipientAndMarksNonce() public { + ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 5e18); + bytes memory sig = sign(signerKey, a); vm.expectEmit(true, true, true, true); - emit ITipping.Tipped(ALICE, address(cs), 7, BOB, 5e18, 0); + emit ITipping.Tipped(ALICE, COLLECTION, TOKEN_ID, address(nodl), BOB, 5e18, 0); vm.prank(ALICE); - tipping.tip(address(cs), 7, 5e18); + tipping.tip(a, sig); assertEq(nodl.balanceOf(BOB), 5e18); assertEq(nodl.balanceOf(ALICE), 995e18); + assertTrue(tipping.nonceUsed(a.nonce)); // A zero fee means a single transfer, straight to the recipient. assertEq(nodl.transfers(), 1); } - function test_contentSign_unmintedReverts() public { - vm.prank(ALICE); - vm.expectRevert(abi.encodeWithSelector(ITipping.UnknownToken.selector, address(cs), 1)); - tipping.tip(address(cs), 1, 5e18); - } - - function test_contentSign_burnedTokenReverts() public { - // ERC721 `ownerOf` reverts for a burned token; an owner-less success is covered by the mock below. - cs.mint(BOB, 2); - vm.prank(BOB); - cs.transferFrom(BOB, address(0xDEAD), 2); - assertEq(tipping.resolveRecipient(address(cs), 2), address(0xDEAD)); + function test_tip_anyErc20() public { + ITipping.TipAuthorization memory a = auth(address(usdc), BOB, 25e6); + tipAs(ALICE, signerKey, a); + assertEq(usdc.balanceOf(BOB), 25e6); + assertEq(nodl.balanceOf(BOB), 0); } - function test_contentSign_zeroOwnerReverts() public { - // A contract whose `ownerOf` answers address(0) is not a valid recipient. - ZeroOwnerMock z = new ZeroOwnerMock(); - vm.prank(REGISTRY); - tipping.setCollectionAllowed(address(z), true); - vm.expectRevert(abi.encodeWithSelector(ITipping.NoRecipient.selector, address(z), 1)); - tipping.resolveRecipient(address(z), 1); - } - - function test_contentSign_disallowedFallsThroughToRegistry() public { - cs.mint(BOB, 7); - vm.prank(REGISTRY); - vm.expectEmit(true, true, true, true); - emit ITipping.CollectionAllowed(address(cs), false); - tipping.setCollectionAllowed(address(cs), false); - assertFalse(tipping.contentSignAllowed(address(cs))); + function test_tip_nonceCannotBeReplayed() public { + ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 5e18); + bytes memory sig = sign(signerKey, a); vm.prank(ALICE); - vm.expectRevert(abi.encodeWithSelector(ITipping.UnknownCollection.selector, address(cs))); - tipping.tip(address(cs), 7, 5e18); + tipping.tip(a, sig); + vm.prank(ALICE); + vm.expectRevert(abi.encodeWithSelector(ITipping.NonceUsed.selector, a.nonce)); + tipping.tip(a, sig); } - // ───────── Factory path ───────── - - function test_factory721_royaltyReceiverElseCreator() public { - vm.prank(CREATOR); - tipping.registerCollection(address(c721)); - c721.mint(BOB, 1); - assertEq(tipping.resolveRecipient(address(c721), 1), CREATOR); + function test_tip_expiredReverts() public { + ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 5e18); + bytes memory sig = sign(signerKey, a); + vm.warp(a.deadline + 1); vm.prank(ALICE); - tipping.tip(address(c721), 1, 2e18); - assertEq(nodl.balanceOf(CREATOR), 2e18); - - c721.setRoyalty(SPLITTER, 500); - assertEq(tipping.resolveRecipient(address(c721), 1), SPLITTER); + vm.expectRevert(abi.encodeWithSelector(ITipping.Expired.selector, a.deadline)); + tipping.tip(a, sig); + // Exactly at the deadline is still valid. + vm.warp(a.deadline); vm.prank(ALICE); - tipping.tip(address(c721), 1, 2e18); - assertEq(nodl.balanceOf(SPLITTER), 2e18); - - // Deleting the royalty makes `royaltyInfo` answer address(0): back to the creator. - c721.deleteRoyalty(); - assertEq(tipping.resolveRecipient(address(c721), 1), CREATOR); + tipping.tip(a, sig); + assertEq(nodl.balanceOf(BOB), 5e18); } - function test_factory721_unmintedTokenStillResolves() public { - // ERC-721 ids are not supply-checked: the creator is paid for any id of a registered collection. - vm.prank(CREATOR); - tipping.registerCollection(address(c721)); - assertEq(tipping.resolveRecipient(address(c721), 999), CREATOR); + function test_tip_wrongSignerReverts() public { + ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 5e18); + expectTipRevert(ALICE, otherKey, a, abi.encodeWithSelector(ITipping.InvalidSignature.selector)); } - function test_factory1155_zeroSupplyReverts_thenResolves() public { - vm.prank(ALICE); - vm.expectRevert(abi.encodeWithSelector(ITipping.UnknownToken.selector, address(c1155), 3)); - tipping.tip(address(c1155), 3, 2e18); - c1155.mint(BOB, 3, 10); + function test_tip_malformedSignatureReverts() public { + ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 5e18); vm.prank(ALICE); - tipping.tip(address(c1155), 3, 2e18); - assertEq(nodl.balanceOf(CREATOR), 2e18); + vm.expectRevert(ITipping.InvalidSignature.selector); + tipping.tip(a, hex"deadbeef"); } - function test_factory1155_royaltyReceiver() public { - c1155.mint(BOB, 3, 10); - c1155.setRoyalty(SPLITTER, 100); - assertEq(tipping.resolveRecipient(address(c1155), 3), SPLITTER); + function test_tip_callerMustBeTipper() public { + ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 5e18); + bytes memory sig = sign(signerKey, a); + nodl.mint(address(0xC0), 10e18); + vm.prank(address(0xC0)); + nodl.approve(address(tipping), type(uint256).max); + vm.prank(address(0xC0)); + vm.expectRevert(ITipping.InvalidSignature.selector); + tipping.tip(a, sig); } - function test_registeredContractWithoutErc165ResolvesToCreator() public { - // No `supportsInterface`, no `royaltyInfo`: every lookup fails softly and the creator is paid. - vm.prank(REGISTRY); - tipping.setCreator(address(nodl), CREATOR); - assertEq(tipping.resolveRecipient(address(nodl), 1), CREATOR); - } + function test_tip_tamperedFieldsInvalidateSignature() public { + ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 5e18); + bytes memory sig = sign(signerKey, a); - function test_registeredContractWithShortReturnsResolvesToCreator() public { - ShortReturnMock s = new ShortReturnMock(); - vm.prank(REGISTRY); - tipping.setCreator(address(s), CREATOR); - assertEq(tipping.resolveRecipient(address(s), 1), CREATOR); - vm.prank(REGISTRY); - tipping.setCollectionAllowed(address(s), true); - vm.expectRevert(abi.encodeWithSelector(ITipping.UnknownToken.selector, address(s), 1)); - tipping.resolveRecipient(address(s), 1); - } + ITipping.TipAuthorization memory t = copy(a); + t.recipient = address(0xBAD); + vm.prank(ALICE); + vm.expectRevert(ITipping.InvalidSignature.selector); + tipping.tip(t, sig); - function test_unknownCollectionReverts() public { + t = copy(a); + t.amount = 500e18; vm.prank(ALICE); - vm.expectRevert(abi.encodeWithSelector(ITipping.UnknownCollection.selector, address(0x1234))); - tipping.tip(address(0x1234), 1, 2e18); - // An ERC-2981 contract that nobody registered is unknown too: the registry is the gate. - vm.expectRevert(abi.encodeWithSelector(ITipping.UnknownCollection.selector, address(c721))); - tipping.resolveRecipient(address(c721), 1); - } - - function test_lookupGasIsCapped() public { - GasBombMock bomb = new GasBombMock(); - vm.prank(REGISTRY); - tipping.setCollectionAllowed(address(bomb), true); - uint256 before = gasleft(); - vm.expectRevert(abi.encodeWithSelector(ITipping.UnknownToken.selector, address(bomb), 1)); - tipping.resolveRecipient(address(bomb), 1); - assertLt(before - gasleft(), 3 * tipping.LOOKUP_GAS()); - - vm.prank(REGISTRY); - tipping.setCollectionAllowed(address(bomb), false); - vm.prank(REGISTRY); - tipping.setCreator(address(bomb), CREATOR); - before = gasleft(); - // supportsInterface and royaltyInfo both burn their cap; the creator is still resolved. - assertEq(tipping.resolveRecipient(address(bomb), 1), CREATOR); - assertLt(before - gasleft(), 4 * tipping.LOOKUP_GAS()); - } - - // ───────── Registry ───────── - - function test_registerCollection_ownerOnly() public { + vm.expectRevert(ITipping.InvalidSignature.selector); + tipping.tip(t, sig); + + t = copy(a); + t.token = address(usdc); vm.prank(ALICE); - vm.expectRevert(abi.encodeWithSelector(ITipping.NotCollectionOwner.selector, address(c721), ALICE)); - tipping.registerCollection(address(c721)); - vm.prank(CREATOR); - vm.expectEmit(true, true, true, true); - emit ITipping.CreatorSet(address(c721), CREATOR); - tipping.registerCollection(address(c721)); - assertEq(tipping.creatorOf(address(c721)), CREATOR); - vm.prank(CREATOR); - vm.expectRevert(abi.encodeWithSelector(ITipping.AlreadyRegistered.selector, address(c721))); - tipping.registerCollection(address(c721)); + vm.expectRevert(ITipping.InvalidSignature.selector); + tipping.tip(t, sig); + + t = copy(a); + t.tokenId = 8; + vm.prank(ALICE); + vm.expectRevert(ITipping.InvalidSignature.selector); + tipping.tip(t, sig); + + t = copy(a); + t.deadline += 1; + vm.prank(ALICE); + vm.expectRevert(ITipping.InvalidSignature.selector); + tipping.tip(t, sig); } - function test_registerCollection_rejectsZeroAndEoa() public { - vm.expectRevert(ITipping.ZeroAddress.selector); - tipping.registerCollection(address(0)); - // An EOA answers every staticcall with empty data. + function test_tip_rotatedSignerInvalidatesOldSignatures() public { + ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 5e18); + bytes memory sig = sign(signerKey, a); + (address next, uint256 nextKey) = makeAddrAndKey("next"); + vm.prank(ADMIN); + vm.expectEmit(true, true, true, true); + emit ITipping.SignerUpdated(next); + tipping.setSigner(next); vm.prank(ALICE); - vm.expectRevert(abi.encodeWithSelector(ITipping.NotCollectionOwner.selector, address(0xE0A), ALICE)); - tipping.registerCollection(address(0xE0A)); + vm.expectRevert(ITipping.InvalidSignature.selector); + tipping.tip(a, sig); + tipAs(ALICE, nextKey, a); + assertEq(nodl.balanceOf(BOB), 5e18); } - function test_registerCollection_anyContractAttestingOwnerRole() public { - OpenOwnerMock open = new OpenOwnerMock(); - vm.prank(BOB); - tipping.registerCollection(address(open)); - assertEq(tipping.creatorOf(address(open)), BOB); + function test_tip_contractSigner() public { + WalletSignerMock wallet = new WalletSignerMock(signer); + vm.prank(ADMIN); + tipping.setSigner(address(wallet)); + ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 5e18); + tipAs(ALICE, signerKey, a); + assertEq(nodl.balanceOf(BOB), 5e18); + expectTipRevert( + ALICE, otherKey, auth(address(nodl), BOB, 1e18), abi.encodeWithSelector(ITipping.InvalidSignature.selector) + ); } - function test_registryEntryWinsAndCanBeCleared() public { - vm.prank(REGISTRY); - tipping.setCreator(address(c721), SPLITTER); - vm.prank(CREATOR); - vm.expectRevert(abi.encodeWithSelector(ITipping.AlreadyRegistered.selector, address(c721))); - tipping.registerCollection(address(c721)); + function test_tip_guards() public { + ITipping.TipAuthorization memory a = auth(address(nodl), ALICE, 5e18); + expectTipRevert(ALICE, signerKey, a, abi.encodeWithSelector(ITipping.SelfTip.selector)); - vm.prank(REGISTRY); - vm.expectEmit(true, true, true, true); - emit ITipping.CreatorSet(address(c721), address(0)); - tipping.setCreator(address(c721), address(0)); - vm.expectRevert(abi.encodeWithSelector(ITipping.UnknownCollection.selector, address(c721))); - tipping.resolveRecipient(address(c721), 1); + a = auth(address(nodl), BOB, 0); + expectTipRevert(ALICE, signerKey, a, abi.encodeWithSelector(ITipping.ZeroAmount.selector)); - vm.prank(CREATOR); - tipping.registerCollection(address(c721)); - assertEq(tipping.creatorOf(address(c721)), CREATOR); + a = auth(address(nodl), address(0), 5e18); + expectTipRevert(ALICE, signerKey, a, abi.encodeWithSelector(ITipping.ZeroAddress.selector)); + + a = auth(address(0), BOB, 5e18); + expectTipRevert(ALICE, signerKey, a, abi.encodeWithSelector(ITipping.ZeroAddress.selector)); } - function test_registrySettersRejectZeroCollection() public { - vm.startPrank(REGISTRY); - vm.expectRevert(ITipping.ZeroAddress.selector); - tipping.setCreator(address(0), CREATOR); - vm.expectRevert(ITipping.ZeroAddress.selector); - tipping.setCollectionAllowed(address(0), true); - vm.stopPrank(); + function test_tip_insufficientAllowanceOrBalanceReverts() public { + nodl.mint(address(0xC0), 10e18); + ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 2e18); + a.tipper = address(0xC0); + bytes memory sig = sign(signerKey, a); + vm.prank(address(0xC0)); + vm.expectRevert(); + tipping.tip(a, sig); + vm.prank(address(0xC0)); + nodl.approve(address(tipping), type(uint256).max); + a.amount = 11e18; + sig = sign(signerKey, a); + vm.prank(address(0xC0)); + vm.expectRevert(); + tipping.tip(a, sig); } - // ───────── Guards ───────── + // ───────── Account tips ───────── - function test_zeroAmountRevertsEvenWithZeroMinimum() public { - vm.prank(ADMIN); + function test_tipAccount_paysNamedAddress() public { vm.expectEmit(true, true, true, true); - emit ITipping.MinTipUpdated(0); - tipping.setMinTipAmount(0); - cs.mint(BOB, 1); + emit ITipping.AccountTipped(ALICE, BOB, address(usdc), 10e6, 0); vm.prank(ALICE); - vm.expectRevert(abi.encodeWithSelector(ITipping.BelowMinimum.selector, 0, 0)); - tipping.tip(address(cs), 1, 0); - // One wei is fine once the minimum is zero. - vm.prank(ALICE); - tipping.tip(address(cs), 1, 1); - assertEq(nodl.balanceOf(BOB), 1); + tipping.tipAccount(address(usdc), BOB, 10e6); + assertEq(usdc.balanceOf(BOB), 10e6); } - function test_selfTipAndDustRevert() public { - cs.mint(ALICE, 9); + function test_tipAccount_guards() public { vm.startPrank(ALICE); vm.expectRevert(ITipping.SelfTip.selector); - tipping.tip(address(cs), 9, 2e18); - vm.expectRevert(abi.encodeWithSelector(ITipping.BelowMinimum.selector, 1, MIN)); - tipping.tip(address(cs), 9, 1); + tipping.tipAccount(address(nodl), ALICE, 1e18); + vm.expectRevert(ITipping.ZeroAmount.selector); + tipping.tipAccount(address(nodl), BOB, 0); + vm.expectRevert(ITipping.ZeroAddress.selector); + tipping.tipAccount(address(nodl), address(0), 1e18); + vm.expectRevert(ITipping.ZeroAddress.selector); + tipping.tipAccount(address(0), BOB, 1e18); vm.stopPrank(); } - function test_insufficientAllowanceOrBalanceReverts() public { - cs.mint(BOB, 1); - nodl.mint(address(0xC0), 10e18); - vm.prank(address(0xC0)); - vm.expectRevert(); - tipping.tip(address(cs), 1, 2e18); - vm.prank(address(0xC0)); - nodl.approve(address(tipping), type(uint256).max); - vm.prank(address(0xC0)); - vm.expectRevert(); - tipping.tip(address(cs), 1, 11e18); - } + // ───────── Pause ───────── - function test_pauseBlocksTips() public { + function test_pauseBlocksBothPaths() public { vm.prank(ADMIN); vm.expectEmit(true, true, true, true); emit Pausable.Paused(ADMIN); tipping.pause(); - cs.mint(BOB, 1); + ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 5e18); + bytes memory sig = sign(signerKey, a); + vm.prank(ALICE); + vm.expectRevert(Pausable.EnforcedPause.selector); + tipping.tip(a, sig); vm.prank(ALICE); vm.expectRevert(Pausable.EnforcedPause.selector); - tipping.tip(address(cs), 1, 2e18); - // Resolution stays readable while paused; the registry keeps working. - assertEq(tipping.resolveRecipient(address(cs), 1), BOB); - vm.prank(REGISTRY); - tipping.setCreator(address(c721), CREATOR); + tipping.tipAccount(address(nodl), BOB, 1e18); vm.prank(ADMIN); vm.expectEmit(true, true, true, true); emit Pausable.Unpaused(ADMIN); tipping.unpause(); vm.prank(ALICE); - tipping.tip(address(cs), 1, 2e18); - assertEq(nodl.balanceOf(BOB), 2e18); + tipping.tip(a, sig); + assertEq(nodl.balanceOf(BOB), 5e18); } // ───────── Fees ───────── @@ -448,15 +379,22 @@ contract TippingTest is Test { vm.expectEmit(true, true, true, true); emit ITipping.FeeRecipientUpdated(address(0xFEE)); tipping.setFeeRecipient(address(0xFEE)); - cs.mint(BOB, 1); + + ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 100e18); + bytes memory sig = sign(signerKey, a); vm.expectEmit(true, true, true, true); - emit ITipping.Tipped(ALICE, address(cs), 1, BOB, 100e18, 2.5e18); + emit ITipping.Tipped(ALICE, COLLECTION, TOKEN_ID, address(nodl), BOB, 100e18, 2.5e18); vm.prank(ALICE); - tipping.tip(address(cs), 1, 100e18); + tipping.tip(a, sig); assertEq(nodl.balanceOf(BOB), 97.5e18); assertEq(nodl.balanceOf(address(0xFEE)), 2.5e18); assertEq(nodl.transfers(), 2); + vm.prank(ALICE); + tipping.tipAccount(address(usdc), BOB, 100e6); + assertEq(usdc.balanceOf(BOB), 97.5e6); + assertEq(usdc.balanceOf(address(0xFEE)), 2.5e6); + vm.prank(ADMIN); vm.expectRevert(abi.encodeWithSelector(ITipping.FeeTooHigh.selector, 1001)); tipping.setFee(1001); @@ -468,76 +406,69 @@ contract TippingTest is Test { function test_feeRoundsDownInFavourOfRecipient() public { vm.prank(ADMIN); tipping.setFee(1); // 0.01% - vm.prank(ADMIN); - tipping.setMinTipAmount(0); - cs.mint(BOB, 1); vm.prank(ALICE); - tipping.tip(address(cs), 1, 9_999); + tipping.tipAccount(address(nodl), BOB, 9_999); assertEq(nodl.balanceOf(BOB), 9_999); assertEq(nodl.balanceOf(ADMIN), 0); } - function test_feeRecipientCannotBeZeroSelfOrToken() public { + function test_feeRecipientCannotBeZeroOrSelf() public { vm.startPrank(ADMIN); vm.expectRevert(ITipping.ZeroAddress.selector); tipping.setFeeRecipient(address(0)); vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidFeeRecipient.selector, address(tipping))); tipping.setFeeRecipient(address(tipping)); - vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidFeeRecipient.selector, address(nodl))); - tipping.setFeeRecipient(address(nodl)); vm.stopPrank(); } // ───────── Roles ───────── - function test_rolesSeparated() public { - bytes32 registryRole = tipping.REGISTRY_ROLE(); - vm.startPrank(ADMIN); - vm.expectRevert( - abi.encodeWithSelector(IAccessControl.AccessControlUnauthorizedAccount.selector, ADMIN, registryRole) - ); - tipping.setCollectionAllowed(address(cs), false); - vm.expectRevert( - abi.encodeWithSelector(IAccessControl.AccessControlUnauthorizedAccount.selector, ADMIN, registryRole) - ); - tipping.setCreator(address(c721), CREATOR); - vm.stopPrank(); - - vm.startPrank(REGISTRY); + function test_adminOnly() public { bytes memory denied = - abi.encodeWithSelector(IAccessControl.AccessControlUnauthorizedAccount.selector, REGISTRY, bytes32(0)); + abi.encodeWithSelector(IAccessControl.AccessControlUnauthorizedAccount.selector, ALICE, bytes32(0)); + vm.startPrank(ALICE); vm.expectRevert(denied); - tipping.setFee(1); + tipping.setSigner(BOB); vm.expectRevert(denied); - tipping.setFeeRecipient(address(0xFEE)); + tipping.setFee(1); vm.expectRevert(denied); - tipping.setMinTipAmount(1); + tipping.setFeeRecipient(BOB); vm.expectRevert(denied); tipping.pause(); vm.expectRevert(denied); tipping.unpause(); vm.stopPrank(); + vm.prank(ADMIN); + vm.expectRevert(ITipping.ZeroAddress.selector); + tipping.setSigner(address(0)); } // ───────── Fuzz ───────── - /// @dev The immutability argument: NODL only ever leaves the caller's own balance. - function testFuzz_transferFromOnlyFromCaller(address tipper, uint256 amount, uint16 bps) public { + /// @dev The immutability argument: tokens only ever leave the caller's own balance. + function testFuzz_transferFromOnlyFromCaller(address tipper, uint256 amount, uint16 bps, bool viaAuth) public { vm.assume( tipper != address(0) && tipper != BOB && tipper != ADMIN && tipper != address(nodl) && tipper != address(tipping) ); - amount = bound(amount, MIN, 1e30); + amount = bound(amount, 1, 1e30); bps = uint16(bound(bps, 0, 1000)); vm.prank(ADMIN); tipping.setFee(bps); - cs.mint(BOB, 1); nodl.mint(tipper, amount); vm.prank(tipper); nodl.approve(address(tipping), amount); - vm.prank(tipper); - tipping.tip(address(cs), 1, amount); + if (viaAuth) { + ITipping.TipAuthorization memory a = auth(address(nodl), BOB, amount); + a.tipper = tipper; + bytes memory sig = sign(signerKey, a); + vm.prank(tipper); + tipping.tip(a, sig); + } else { + vm.prank(tipper); + tipping.tipAccount(address(nodl), BOB, amount); + } uint256 fee = (amount * bps) / 10_000; uint256 n = nodl.transfers(); @@ -553,21 +484,22 @@ contract TippingTest is Test { assertEq(n, fee > 0 ? 2 : 1); } - function testFuzz_belowMinimumReverts(uint256 minimum, uint256 amount) public { - minimum = bound(minimum, 1, 1e30); - amount = bound(amount, 0, minimum - 1); - vm.prank(ADMIN); - tipping.setMinTipAmount(minimum); - cs.mint(BOB, 1); - vm.prank(ALICE); - vm.expectRevert(abi.encodeWithSelector(ITipping.BelowMinimum.selector, amount, minimum)); - tipping.tip(address(cs), 1, amount); - } -} - -/// @dev `ownerOf` succeeds with address(0): the resolver must not pay the zero address. -contract ZeroOwnerMock { - function ownerOf(uint256) external pure returns (address) { - return address(0); + /// @dev Any single-bit change to the signed fields produces a different digest. + function testFuzz_digestBindsEveryField(ITipping.TipAuthorization memory a, uint8 field, uint256 delta) + public + view + { + vm.assume(delta != 0); + ITipping.TipAuthorization memory b = copy(a); + field = uint8(bound(field, 0, 7)); + if (field == 0) b.tipper = address(uint160(a.tipper) ^ uint160(delta | 1)); + else if (field == 1) b.token = address(uint160(a.token) ^ uint160(delta | 1)); + else if (field == 2) b.collection = address(uint160(a.collection) ^ uint160(delta | 1)); + else if (field == 3) b.tokenId = a.tokenId ^ delta; + else if (field == 4) b.recipient = address(uint160(a.recipient) ^ uint160(delta | 1)); + else if (field == 5) b.amount = a.amount ^ delta; + else if (field == 6) b.deadline = a.deadline ^ delta; + else b.nonce = a.nonce ^ bytes32(delta); + assertTrue(tipping.hashAuthorization(a) != tipping.hashAuthorization(b)); } } diff --git a/test/tipping/TippingZkSyncFork.t.sol b/test/tipping/TippingZkSyncFork.t.sol deleted file mode 100644 index d7fa8e68..00000000 --- a/test/tipping/TippingZkSyncFork.t.sol +++ /dev/null @@ -1,96 +0,0 @@ -// SPDX-License-Identifier: BSD-3-Clause-Clear -pragma solidity ^0.8.26; - -import {Test} from "forge-std/Test.sol"; -import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; - -import {Tipping} from "../../src/tipping/Tipping.sol"; -import {ITipping} from "../../src/tipping/ITipping.sol"; - -/** - * @title TippingZkSyncForkTest - * @notice Recipient resolution against the real zkSync Era mainnet contracts: The Turtle - * (factory ERC-1155) resolves to its registered creator, and a legacy ClickContentSign - * token resolves to its owner. Also the EraVM check for `LOOKUP_GAS`: every static - * lookup through the real proxies must fit the cap (meta#242 acceptance). - * - * Skipped unless ZKSYNC_RPC_URL is set: - * ZKSYNC_RPC_URL=https://mainnet.era.zksync.io forge test --match-contract TippingZkSyncForkTest -vv - * - * On a plain fork the forked contracts run as EVM bytecode, so the gas numbers are EVM - * numbers. `forge test --zksync` crashes in this repo's linker (foundry-zksync v0.1.9, - * "no EVM bytecode (or unlinked)"), so the EraVM figure for `LOOKUP_GAS` was taken with - * `cast call --gas-limit` against mainnet instead (2026-10-27): minimum eth_call gas that - * succeeds, node overhead included: name() 59,375 (baseline); ownerOf 59,375; - * supportsInterface 65,625; totalSupply 67,187; hasRole 68,750; royaltyInfo 70,312. - */ -contract TippingZkSyncForkTest is Test { - address internal constant TURTLE = 0x08820bBb37B401983683334B00668a2a8555CC74; - address internal constant TURTLE_OWNER = 0xfe74C8C3f3F1ca3D4b523fd1AE7A3d82dbAc5eCe; - address internal constant CLICK_CONTENTSIGN = 0x95b3641d549f719eb5105f9550Eca4A7A2F305De; - uint256 internal constant CLICK_TOKEN = 1; - - address internal constant ADMIN = address(0xAD); - address internal constant REGISTRY = address(0x09); - - Tipping internal tipping; - bool internal skipAll; - - function setUp() public { - string memory rpc = vm.envOr("ZKSYNC_RPC_URL", string("")); - if (bytes(rpc).length == 0) { - skipAll = true; - return; - } - vm.createSelectFork(rpc); - // The token address only has to be non-zero for resolution tests; no transfer happens here. - tipping = new Tipping(address(0x1), ADMIN, REGISTRY, 1e18); - vm.prank(REGISTRY); - tipping.setCollectionAllowed(CLICK_CONTENTSIGN, true); - } - - function test_turtle_registersByOwnerAndResolvesToCreator() public { - if (skipAll) return; - // Permissionless path: the collection attests OWNER_ROLE for the caller. - vm.prank(TURTLE_OWNER); - tipping.registerCollection(TURTLE); - assertEq(tipping.creatorOf(TURTLE), TURTLE_OWNER); - // No royalties on The Turtle: the creator is the recipient. - assertEq(tipping.resolveRecipient(TURTLE, 0), TURTLE_OWNER); - // Unminted id: supply is zero. - vm.expectRevert(abi.encodeWithSelector(ITipping.UnknownToken.selector, TURTLE, 999)); - tipping.resolveRecipient(TURTLE, 999); - } - - function test_turtle_nonOwnerCannotRegister() public { - if (skipAll) return; - vm.prank(ADMIN); - vm.expectRevert(abi.encodeWithSelector(ITipping.NotCollectionOwner.selector, TURTLE, ADMIN)); - tipping.registerCollection(TURTLE); - } - - function test_clickContentSign_resolvesToOwner() public { - if (skipAll) return; - address owner = IERC721(CLICK_CONTENTSIGN).ownerOf(CLICK_TOKEN); - assertTrue(owner != address(0)); - assertEq(tipping.resolveRecipient(CLICK_CONTENTSIGN, CLICK_TOKEN), owner); - } - - /// @dev EraVM gas check: the whole resolution, three capped lookups included, must be far - /// below what a tip transaction carries. Prints the measurement for the deploy record. - function test_lookupGasFitsOnEraVm() public { - if (skipAll) return; - vm.prank(TURTLE_OWNER); - tipping.registerCollection(TURTLE); - uint256 g0 = gasleft(); - tipping.resolveRecipient(TURTLE, 0); - uint256 turtleGas = g0 - gasleft(); - g0 = gasleft(); - tipping.resolveRecipient(CLICK_CONTENTSIGN, CLICK_TOKEN); - uint256 clickGas = g0 - gasleft(); - emit log_named_uint("resolve(The Turtle) gas", turtleGas); - emit log_named_uint("resolve(ClickContentSign) gas", clickGas); - assertLt(turtleGas, 3 * tipping.LOOKUP_GAS()); - assertLt(clickGas, tipping.LOOKUP_GAS()); - } -} From 9f6438cd62b1f2cc4bacd6322de7da57387b65a0 Mon Sep 17 00:00:00 2001 From: douglasacost Date: Tue, 27 Oct 2026 14:55:52 -0400 Subject: [PATCH 06/18] test(tipping): rename mock field for spell check --- test/tipping/Tipping.t.sol | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/tipping/Tipping.t.sol b/test/tipping/Tipping.t.sol index 573ec1f3..39e702a5 100644 --- a/test/tipping/Tipping.t.sol +++ b/test/tipping/Tipping.t.sol @@ -13,7 +13,7 @@ import {ITipping} from "../../src/tipping/ITipping.sol"; /// @dev Records every `transferFrom` so tests can prove the contract only ever pulls from the caller. contract TokenMock is ERC20 { - address[] public froms; + address[] public senders; uint256[] public amounts; constructor(string memory sym) ERC20(sym, sym) {} @@ -23,13 +23,13 @@ contract TokenMock is ERC20 { } function transferFrom(address from, address to, uint256 value) public override returns (bool) { - froms.push(from); + senders.push(from); amounts.push(value); return super.transferFrom(from, to, value); } function transfers() external view returns (uint256) { - return froms.length; + return senders.length; } } @@ -474,7 +474,7 @@ contract TippingTest is Test { uint256 n = nodl.transfers(); uint256 moved; for (uint256 i; i < n; i++) { - assertEq(nodl.froms(i), tipper); + assertEq(nodl.senders(i), tipper); moved += nodl.amounts(i); } assertEq(moved, amount); From 9a9bfa7cbd3fcadf82b0c665b1263d6ca7200cc7 Mon Sep 17 00:00:00 2001 From: douglasacost Date: Tue, 27 Oct 2026 22:08:01 -0400 Subject: [PATCH 07/18] ops(tipping): zksync deploy wrapper that moves the L1-only files aside for the compile --- ops/deploy_tipping_zksync.sh | 54 ++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100755 ops/deploy_tipping_zksync.sh diff --git a/ops/deploy_tipping_zksync.sh b/ops/deploy_tipping_zksync.sh new file mode 100755 index 00000000..07e2f8c8 --- /dev/null +++ b/ops/deploy_tipping_zksync.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +# Deploys the immutable Tipping contract on zkSync (Sepolia or mainnet) with forge --zksync. +# zksolc cannot compile the L1-only SwarmRegistryL1Upgradeable (EXTCODECOPY), so the L1-only +# files are moved aside for the compile and restored on exit, exactly as +# ops/deploy_collection_factory_zksync.sh and ops/upgrade_collection_factory_zksync.sh do. +# +# Usage: +# DEPLOYER_PRIVATE_KEY=0x… N_TIPPING_ADMIN=0x… N_TIPPING_SIGNER=0x… \ +# ops/deploy_tipping_zksync.sh [--broadcast] +# +# Without --broadcast the script simulates only. The broadcast JSON lands in +# broadcast/DeployTippingZkSync.s.sol//run-latest.json; verify afterwards with +# python3 ops/verify_zksync_contracts.py --broadcast . +set -euo pipefail +cd "$(dirname "$0")/.." + +NETWORK="${1:-}"; BROADCAST="${2:-}" +case "$NETWORK" in + testnet) RPC_URL="${L2_RPC:-https://sepolia.era.zksync.dev}" ;; + mainnet) RPC_URL="${L2_RPC:-https://mainnet.era.zksync.io}" ;; + *) echo "usage: $0 [--broadcast]"; exit 1 ;; +esac +: "${DEPLOYER_PRIVATE_KEY:?}" "${N_TIPPING_ADMIN:?}" "${N_TIPPING_SIGNER:?}" +[[ "$DEPLOYER_PRIVATE_KEY" == 0x* ]] || export DEPLOYER_PRIVATE_KEY="0x${DEPLOYER_PRIVATE_KEY}" +if [[ "$NETWORK" == "mainnet" && "$BROADCAST" == "--broadcast" && "${CONFIRM_MAINNET:-}" != "YES" ]]; then + echo "mainnet broadcast requires CONFIRM_MAINNET=YES"; exit 1 +fi + +L1_BACKUP_DIR="/tmp/rollup-l1-backup-tipping" +restore_l1_contracts() { + [ -d "$L1_BACKUP_DIR" ] || return 0 + [ -f "$L1_BACKUP_DIR/SwarmRegistryL1Upgradeable.sol" ] && mv "$L1_BACKUP_DIR/SwarmRegistryL1Upgradeable.sol" src/swarms/ + [ -f "$L1_BACKUP_DIR/SwarmRegistryL1.t.sol" ] && mv "$L1_BACKUP_DIR/SwarmRegistryL1.t.sol" test/ + [ -d "$L1_BACKUP_DIR/upgrade-demo" ] && mv "$L1_BACKUP_DIR/upgrade-demo" test/ + [ -f "$L1_BACKUP_DIR/DeploySwarmUpgradeable.s.sol" ] && mv "$L1_BACKUP_DIR/DeploySwarmUpgradeable.s.sol" script/ + [ -f "$L1_BACKUP_DIR/UpgradeSwarm.s.sol" ] && mv "$L1_BACKUP_DIR/UpgradeSwarm.s.sol" script/ + rm -rf "$L1_BACKUP_DIR" + echo "L1-only contracts restored" +} +move_l1_contracts() { + [ -d "$L1_BACKUP_DIR" ] && restore_l1_contracts + mkdir -p "$L1_BACKUP_DIR" + [ -f src/swarms/SwarmRegistryL1Upgradeable.sol ] && mv src/swarms/SwarmRegistryL1Upgradeable.sol "$L1_BACKUP_DIR/" + [ -f test/SwarmRegistryL1.t.sol ] && mv test/SwarmRegistryL1.t.sol "$L1_BACKUP_DIR/" + [ -d test/upgrade-demo ] && mv test/upgrade-demo "$L1_BACKUP_DIR/" + [ -f script/DeploySwarmUpgradeable.s.sol ] && mv script/DeploySwarmUpgradeable.s.sol "$L1_BACKUP_DIR/" + [ -f script/UpgradeSwarm.s.sol ] && mv script/UpgradeSwarm.s.sol "$L1_BACKUP_DIR/" + echo "L1-only contracts moved aside for the zksync compile" +} +trap restore_l1_contracts EXIT +move_l1_contracts + +echo "network=$NETWORK rpc=$RPC_URL admin=$N_TIPPING_ADMIN signer=$N_TIPPING_SIGNER broadcast=${BROADCAST:-no}" +forge script script/DeployTippingZkSync.s.sol --rpc-url "$RPC_URL" --zksync --skip test ${BROADCAST:+--broadcast --slow} From f97b7d440ba13cb12ef39eaad1a73a7b8cad68ad Mon Sep 17 00:00:00 2001 From: douglasacost Date: Wed, 28 Oct 2026 00:27:54 -0400 Subject: [PATCH 08/18] ops(verify): inline Foundry remappings into imports; the explorer now rejects settings.remappings The zkSync verification API (checked 2026-10-28) returns 400 "settings.remappings is not supported; imports must match sources keys exactly". Source keys are already project-relative, so rewriting @openzeppelin/... imports to their remapped paths and dropping the setting gives full verification again. Verified Tipping on mainnet and Sepolia with it. --- ops/verify_zksync_contracts.py | 40 +++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/ops/verify_zksync_contracts.py b/ops/verify_zksync_contracts.py index 7be8463f..43204640 100755 --- a/ops/verify_zksync_contracts.py +++ b/ops/verify_zksync_contracts.py @@ -166,6 +166,44 @@ def fix_traversal_imports(std_json: dict) -> int: return changed +def apply_remappings(std_json: dict) -> int: + """Inline Foundry remappings into import statements and drop `settings.remappings`. + + Since 2026-10 the explorer verifier rejects `settings.remappings` ("imports must match + `sources` keys exactly"). Source keys are already project-relative (e.g. + lib/openzeppelin-contracts/contracts/...), so rewriting `@openzeppelin/contracts/X` to + its remapped path makes every import match a key. Longest remapping prefix wins. + Returns the number of import lines rewritten. + """ + remappings = std_json.get("settings", {}).pop("remappings", None) or [] + pairs = [] + for r in remappings: + if "=" in r: + prefix, target = r.split("=", 1) + pairs.append((prefix, target)) + pairs.sort(key=lambda x: -len(x[0])) + source_keys = set(std_json["sources"].keys()) + pattern = re.compile(r'(import\s+.*?["\'])([^"\'.][^"\']*)(["\'].*)') + changed = 0 + for src_key in list(std_json["sources"].keys()): + lines = std_json["sources"][src_key]["content"].split("\n") + out = [] + for line in lines: + m = pattern.match(line) + if m: + prefix, path, suffix = m.groups() + for rp, target in pairs: + if path.startswith(rp): + new_path = target + path[len(rp):] + if new_path in source_keys: + line = prefix + new_path + suffix + changed += 1 + break + out.append(line) + std_json["sources"][src_key]["content"] = "\n".join(out) + return changed + + def generate_standard_json( address: str, contract: str, @@ -258,7 +296,7 @@ def verify_one( std_json = generate_standard_json( address, contract, constructor_args, solc_version, project_root ) - fixes = fix_traversal_imports(std_json) + fixes = apply_remappings(std_json) + fix_traversal_imports(std_json) print(f"done (rewrote {fixes} imports)") # Step 2: Submit From 4fd981619770e873ff3b8f14c8e108bc5d1242a2 Mon Sep 17 00:00:00 2001 From: douglasacost Date: Wed, 28 Oct 2026 20:51:30 -0400 Subject: [PATCH 09/18] feat(tipping): drop Pausable (review decision 2026-10-28) The contract holds no funds and only moves the caller's own tokens, so an admin power to stop tipping protects nobody; signer rotation already covers a leaked key. Removes pause/unpause, the whenNotPaused guards and the Paused/Unpaused events. Takes effect at the next deployment: the live mainnet and Sepolia contracts are immutable and keep pause. --- script/DeployTippingZkSync.s.sol | 2 +- src/tipping/ITipping.sol | 2 -- src/tipping/Tipping.sol | 19 ++++++------------- test/tipping/Tipping.t.sol | 31 ------------------------------- 4 files changed, 7 insertions(+), 47 deletions(-) diff --git a/script/DeployTippingZkSync.s.sol b/script/DeployTippingZkSync.s.sol index bfdcaa49..25dcd2e7 100644 --- a/script/DeployTippingZkSync.s.sol +++ b/script/DeployTippingZkSync.s.sol @@ -16,7 +16,7 @@ import {Tipping} from "../src/tipping/Tipping.sol"; * * Environment Variables: * - DEPLOYER_PRIVATE_KEY: Private key with ETH for gas. - * - N_TIPPING_ADMIN: Multisig that will hold DEFAULT_ADMIN_ROLE (fee, fee recipient, signer, pause). + * - N_TIPPING_ADMIN: Multisig that will hold DEFAULT_ADMIN_ROLE (fee, fee recipient, signer). * - N_TIPPING_SIGNER: Address whose EIP-712 signatures authorize post tips (the feed API's * signing key, or an ERC-1271 contract). Rotatable by the admin. */ diff --git a/src/tipping/ITipping.sol b/src/tipping/ITipping.sol index c47c543f..06743f53 100644 --- a/src/tipping/ITipping.sol +++ b/src/tipping/ITipping.sol @@ -24,8 +24,6 @@ interface ITipping { event FeeUpdated(uint16 feeBps); event FeeRecipientUpdated(address indexed feeRecipient); event SignerUpdated(address indexed signer); - // `Paused(address)` / `Unpaused(address)` come from OpenZeppelin Pausable and are part of - // the indexed surface too; do not strip them from the generated ABI. error ZeroAddress(); error ZeroAmount(); diff --git a/src/tipping/Tipping.sol b/src/tipping/Tipping.sol index df900420..b7451b27 100644 --- a/src/tipping/Tipping.sol +++ b/src/tipping/Tipping.sol @@ -3,7 +3,6 @@ pragma solidity ^0.8.26; import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; -import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {EIP712} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol"; @@ -24,10 +23,12 @@ import {ITipping} from "./ITipping.sol"; * deadline and a single-use nonce, so a signature cannot be replayed or redirected. * Account tips name their recipient directly and need no signature. * - * Roles: DEFAULT_ADMIN_ROLE (fee, fee recipient, signer, pause). `signer` is a single address, + * Roles: DEFAULT_ADMIN_ROLE (fee, fee recipient, signer). There is no pause: the contract holds + * no funds and only moves the caller's own tokens, so nobody needs the power to stop people + * from tipping each other (review decision 2026-10-28). `signer` is a single address, * rotated in one call so a leaked key stops working immediately; it may be a contract (ERC-1271). */ -contract Tipping is ITipping, AccessControl, ReentrancyGuard, Pausable, EIP712 { +contract Tipping is ITipping, AccessControl, ReentrancyGuard, EIP712 { using SafeERC20 for IERC20; uint16 public constant MAX_FEE_BPS = 1000; @@ -54,7 +55,7 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard, Pausable, EIP712 { // ───────── Tipping ───────── /// @inheritdoc ITipping - function tip(TipAuthorization calldata auth, bytes calldata signature) external whenNotPaused nonReentrant { + function tip(TipAuthorization calldata auth, bytes calldata signature) external nonReentrant { if ( auth.tipper != msg.sender || !SignatureChecker.isValidSignatureNow(signer, hashAuthorization(auth), signature) @@ -70,7 +71,7 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard, Pausable, EIP712 { } /// @inheritdoc ITipping - function tipAccount(address token, address to, uint256 amount) external whenNotPaused nonReentrant { + function tipAccount(address token, address to, uint256 amount) external nonReentrant { uint256 fee = _pay(token, to, amount); emit AccountTipped(msg.sender, to, token, amount, fee); } @@ -126,12 +127,4 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard, Pausable, EIP712 { feeRecipient = recipient; emit FeeRecipientUpdated(recipient); } - - function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { - _pause(); - } - - function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { - _unpause(); - } } diff --git a/test/tipping/Tipping.t.sol b/test/tipping/Tipping.t.sol index 39e702a5..5f772419 100644 --- a/test/tipping/Tipping.t.sol +++ b/test/tipping/Tipping.t.sol @@ -4,7 +4,6 @@ pragma solidity ^0.8.26; import {Test} from "forge-std/Test.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol"; -import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol"; import {IERC1271} from "@openzeppelin/contracts/interfaces/IERC1271.sol"; import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; @@ -129,7 +128,6 @@ contract TippingTest is Test { assertEq(tipping.feeBps(), 0); assertEq(tipping.feeRecipient(), ADMIN); assertTrue(tipping.hasRole(tipping.DEFAULT_ADMIN_ROLE(), ADMIN)); - assertFalse(tipping.paused()); } function test_constructor_emitsInitialSettings() public { @@ -343,31 +341,6 @@ contract TippingTest is Test { vm.stopPrank(); } - // ───────── Pause ───────── - - function test_pauseBlocksBothPaths() public { - vm.prank(ADMIN); - vm.expectEmit(true, true, true, true); - emit Pausable.Paused(ADMIN); - tipping.pause(); - ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 5e18); - bytes memory sig = sign(signerKey, a); - vm.prank(ALICE); - vm.expectRevert(Pausable.EnforcedPause.selector); - tipping.tip(a, sig); - vm.prank(ALICE); - vm.expectRevert(Pausable.EnforcedPause.selector); - tipping.tipAccount(address(nodl), BOB, 1e18); - - vm.prank(ADMIN); - vm.expectEmit(true, true, true, true); - emit Pausable.Unpaused(ADMIN); - tipping.unpause(); - vm.prank(ALICE); - tipping.tip(a, sig); - assertEq(nodl.balanceOf(BOB), 5e18); - } - // ───────── Fees ───────── function test_feeSplitAndCap() public { @@ -433,10 +406,6 @@ contract TippingTest is Test { tipping.setFee(1); vm.expectRevert(denied); tipping.setFeeRecipient(BOB); - vm.expectRevert(denied); - tipping.pause(); - vm.expectRevert(denied); - tipping.unpause(); vm.stopPrank(); vm.prank(ADMIN); vm.expectRevert(ITipping.ZeroAddress.selector); From f1a2649827f5c7b851724df130f992a22c25156e Mon Sep 17 00:00:00 2001 From: douglasacost Date: Wed, 28 Oct 2026 21:02:55 -0400 Subject: [PATCH 10/18] feat(tipping): v2 resolves the recipient on-chain; no backend signature Review decisions 2026-10-28 (points 2 and 4): tip(collection, standard, tokenId, token, amount) pays ownerOf(tokenId) for ERC-721 and the ERC-2981 royalty receiver for ERC-1155 (after rejecting ids with zero tracked supply when the collection exposes totalSupply). Lookups are STATICCALLs behind try/catch: a hostile collection can only make the tip revert. Drops EIP-712 TipAuthorization, signer, nonces and deadlines; adds recipientOf() for clients. Errors: NotAContract, InvalidToken, NoRecipient. Admin keeps fee and fee recipient. 24 tests, 100 % line coverage on src/tipping. Takes effect at the v2 deployment. --- ops/deploy_tipping_zksync.sh | 6 +- script/DeployTippingZkSync.s.sol | 19 +- src/tipping/ITipping.sol | 45 ++- src/tipping/Tipping.sol | 120 ++++---- test/tipping/Tipping.t.sol | 475 ++++++++++++++----------------- 5 files changed, 292 insertions(+), 373 deletions(-) diff --git a/ops/deploy_tipping_zksync.sh b/ops/deploy_tipping_zksync.sh index 07e2f8c8..ca8bae62 100755 --- a/ops/deploy_tipping_zksync.sh +++ b/ops/deploy_tipping_zksync.sh @@ -5,7 +5,7 @@ # ops/deploy_collection_factory_zksync.sh and ops/upgrade_collection_factory_zksync.sh do. # # Usage: -# DEPLOYER_PRIVATE_KEY=0x… N_TIPPING_ADMIN=0x… N_TIPPING_SIGNER=0x… \ +# DEPLOYER_PRIVATE_KEY=0x… N_TIPPING_ADMIN=0x… \ # ops/deploy_tipping_zksync.sh [--broadcast] # # Without --broadcast the script simulates only. The broadcast JSON lands in @@ -20,7 +20,7 @@ case "$NETWORK" in mainnet) RPC_URL="${L2_RPC:-https://mainnet.era.zksync.io}" ;; *) echo "usage: $0 [--broadcast]"; exit 1 ;; esac -: "${DEPLOYER_PRIVATE_KEY:?}" "${N_TIPPING_ADMIN:?}" "${N_TIPPING_SIGNER:?}" +: "${DEPLOYER_PRIVATE_KEY:?}" "${N_TIPPING_ADMIN:?}" [[ "$DEPLOYER_PRIVATE_KEY" == 0x* ]] || export DEPLOYER_PRIVATE_KEY="0x${DEPLOYER_PRIVATE_KEY}" if [[ "$NETWORK" == "mainnet" && "$BROADCAST" == "--broadcast" && "${CONFIRM_MAINNET:-}" != "YES" ]]; then echo "mainnet broadcast requires CONFIRM_MAINNET=YES"; exit 1 @@ -50,5 +50,5 @@ move_l1_contracts() { trap restore_l1_contracts EXIT move_l1_contracts -echo "network=$NETWORK rpc=$RPC_URL admin=$N_TIPPING_ADMIN signer=$N_TIPPING_SIGNER broadcast=${BROADCAST:-no}" +echo "network=$NETWORK rpc=$RPC_URL admin=$N_TIPPING_ADMIN broadcast=${BROADCAST:-no}" forge script script/DeployTippingZkSync.s.sol --rpc-url "$RPC_URL" --zksync --skip test ${BROADCAST:+--broadcast --slow} diff --git a/script/DeployTippingZkSync.s.sol b/script/DeployTippingZkSync.s.sol index 25dcd2e7..f9efa434 100644 --- a/script/DeployTippingZkSync.s.sol +++ b/script/DeployTippingZkSync.s.sol @@ -11,14 +11,12 @@ import {Tipping} from "../src/tipping/Tipping.sol"; * No proxy, no initializer: the constructor sets everything, so a mistaken input * means a new deployment, not an upgrade. Fee starts at 0 with the admin as recipient. * - * Usage (zkSync Sepolia first, then mainnet): - * forge script script/DeployTippingZkSync.s.sol --rpc-url $L2_RPC --broadcast --zksync + * Usage: ops/deploy_tipping_zksync.sh [--broadcast] + * (moves the L1-only swarm files aside; plain `forge script --zksync` fails to compile) * * Environment Variables: - * - DEPLOYER_PRIVATE_KEY: Private key with ETH for gas. - * - N_TIPPING_ADMIN: Multisig that will hold DEFAULT_ADMIN_ROLE (fee, fee recipient, signer). - * - N_TIPPING_SIGNER: Address whose EIP-712 signatures authorize post tips (the feed API's - * signing key, or an ERC-1271 contract). Rotatable by the admin. + * - DEPLOYER_PRIVATE_KEY: Private key with ETH for gas (gets no role). + * - N_TIPPING_ADMIN: Multisig that will hold DEFAULT_ADMIN_ROLE (fee, fee recipient). */ contract DeployTippingZkSync is Script { address public tipping; @@ -26,23 +24,18 @@ contract DeployTippingZkSync is Script { function run() external { uint256 deployerPrivateKey = vm.envUint("DEPLOYER_PRIVATE_KEY"); address admin = vm.envAddress("N_TIPPING_ADMIN"); - address signer = vm.envAddress("N_TIPPING_SIGNER"); - require(admin != address(0), "N_TIPPING_ADMIN is zero"); - require(signer != address(0), "N_TIPPING_SIGNER is zero"); console.log("=== Deploying Tipping on ZkSync ==="); console.log("Admin:", admin); - console.log("Signer:", signer); console.log(""); vm.startBroadcast(deployerPrivateKey); - tipping = address(new Tipping(admin, signer)); + tipping = address(new Tipping(admin)); vm.stopBroadcast(); console.log("Tipping:", tipping); console.log(""); - console.log("Next: record the address and deploy block in the indexer (chains.ts `tipping`)"); - console.log("and point the feed API's tip authorizer at it (same chain id, same address)."); + console.log("Next: record the address and deploy block in the indexer (chains.ts `tipping`)."); } } diff --git a/src/tipping/ITipping.sol b/src/tipping/ITipping.sol index 06743f53..4f99faa4 100644 --- a/src/tipping/ITipping.sol +++ b/src/tipping/ITipping.sol @@ -3,12 +3,18 @@ pragma solidity ^0.8.26; /** * @title ITipping - * @notice Agnostic tipping: any ERC-20, any NFT, any account. The contract knows nothing about - * the NFT; the recipient of a post tip is attested off-chain by the Nodle signer (the - * feed API resolves it from indexed data) and verified here as an EIP-712 signature. + * @notice Agnostic tipping: any ERC-20, any NFT, any account. The recipient of a post tip is + * resolved on-chain from the NFT itself: the current owner for ERC-721, the ERC-2981 + * royalty receiver for ERC-1155 (editions have many holders; the royalty receiver is the + * creator's payout address). No backend involvement, no signature, no allowlist. * The event surface is what the feed indexer consumes; keep it stable. */ interface ITipping { + enum Standard { + ERC721, + ERC1155 + } + /// @notice A post was tipped. `amount` is gross (what the tipper gave); `fee` went to the fee recipient. event Tipped( address indexed tipper, @@ -23,38 +29,25 @@ interface ITipping { event AccountTipped(address indexed tipper, address indexed to, address token, uint256 amount, uint256 fee); event FeeUpdated(uint16 feeBps); event FeeRecipientUpdated(address indexed feeRecipient); - event SignerUpdated(address indexed signer); error ZeroAddress(); error ZeroAmount(); error SelfTip(); - error Expired(uint256 deadline); - error NonceUsed(bytes32 nonce); - error InvalidSignature(); + error NotAContract(address collection); + /// @notice The NFT does not exist for the given standard (ownerOf reverted, or an ERC-1155 id with zero supply). + error InvalidToken(address collection, uint256 tokenId); + /// @notice The NFT exists but names nobody to pay (zero owner, or an ERC-1155 without a royalty receiver). + error NoRecipient(address collection, uint256 tokenId); error FeeTooHigh(uint16 feeBps); error InvalidFeeRecipient(address recipient); - /// @notice The authorization a post tip carries. Signed by `signer()` over EIP-712. - struct TipAuthorization { - address tipper; - address token; - address collection; - uint256 tokenId; - address recipient; - uint256 amount; - uint256 deadline; - bytes32 nonce; - } - - /// @notice Tip a post. `auth.tipper` must be the caller; `signature` is the signer's EIP-712 signature over `auth`. - function tip(TipAuthorization calldata auth, bytes calldata signature) external; - /// @notice Tip an account the caller names. No authorization needed. + /// @notice Tip the NFT `tokenId` of `collection` with `amount` of `token`. The recipient is resolved on-chain. + function tip(address collection, Standard standard, uint256 tokenId, address token, uint256 amount) external; + /// @notice Tip an account the caller names. function tipAccount(address token, address to, uint256 amount) external; - function signer() external view returns (address); + /// @notice Who a tip of this NFT would pay right now; reverts the way `tip` would. + function recipientOf(address collection, Standard standard, uint256 tokenId) external view returns (address); function feeBps() external view returns (uint16); function feeRecipient() external view returns (address); - function nonceUsed(bytes32 nonce) external view returns (bool); - /// @notice The EIP-712 digest the signer signs for `auth` (for clients and tests). - function hashAuthorization(TipAuthorization calldata auth) external view returns (bytes32); } diff --git a/src/tipping/Tipping.sol b/src/tipping/Tipping.sol index b7451b27..699e8aaf 100644 --- a/src/tipping/Tipping.sol +++ b/src/tipping/Tipping.sol @@ -5,49 +5,44 @@ import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; -import {EIP712} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol"; -import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol"; +import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; +import {IERC2981} from "@openzeppelin/contracts/interfaces/IERC2981.sol"; import {ITipping} from "./ITipping.sol"; +/// @dev ERC-1155 supply extension (OpenZeppelin ERC1155Supply); optional on the collection. +interface IERC1155SupplyLike { + function totalSupply(uint256 id) external view returns (uint256); +} + /** * @title Tipping - * @notice Immutable, agnostic tipping (nft-feed-indexer design §6.2). No proxy and no upgrade - * path on purpose: an allowance granted to this address can only ever be spent by the - * approver's own `tip`/`tipAccount` calls, because `transferFrom` is only called with - * `from == msg.sender`. The contract holds no funds and knows no token or collection. + * @notice Immutable, agnostic tipping (nft-feed-indexer design §6.2, v2 of 2026-10-28). No proxy, + * no upgrade path, no pause, no backend signature: an allowance granted to this address + * can only ever be spent by the approver's own `tip`/`tipAccount` calls, because + * `transferFrom` is only called with `from == msg.sender`. The contract holds no funds. * - * Post tips carry a `TipAuthorization` signed by `signer` (the Nodle feed API, which resolves - * the recipient from indexed data: holder, minter or creator, by policy that lives off-chain). - * The authorization binds the tipper, the token, the post, the recipient, the amount, a - * deadline and a single-use nonce, so a signature cannot be replayed or redirected. - * Account tips name their recipient directly and need no signature. + * Post tips resolve the recipient from the NFT: `ownerOf(tokenId)` for ERC-721, the ERC-2981 + * royalty receiver for ERC-1155 (an edition has many holders; its royalty receiver is where the + * creator is paid). The caller states the standard; a wrong standard simply fails to resolve. + * The lookups are `view` calls (STATICCALL), so a hostile collection can only make the tip + * revert or burn the tipper's own gas. Account tips name their recipient directly. * - * Roles: DEFAULT_ADMIN_ROLE (fee, fee recipient, signer). There is no pause: the contract holds - * no funds and only moves the caller's own tokens, so nobody needs the power to stop people - * from tipping each other (review decision 2026-10-28). `signer` is a single address, - * rotated in one call so a leaked key stops working immediately; it may be a contract (ERC-1271). + * Roles: DEFAULT_ADMIN_ROLE (fee ≤ 10 %, fee recipient). */ -contract Tipping is ITipping, AccessControl, ReentrancyGuard, EIP712 { +contract Tipping is ITipping, AccessControl, ReentrancyGuard { using SafeERC20 for IERC20; uint16 public constant MAX_FEE_BPS = 1000; uint256 public constant BPS = 10_000; - bytes32 public constant TIP_AUTHORIZATION_TYPEHASH = keccak256( - "TipAuthorization(address tipper,address token,address collection,uint256 tokenId,address recipient,uint256 amount,uint256 deadline,bytes32 nonce)" - ); - address public signer; uint16 public feeBps; address public feeRecipient; - mapping(bytes32 nonce => bool used) public nonceUsed; - constructor(address admin, address initialSigner) EIP712("NodleTipping", "1") { - if (admin == address(0) || initialSigner == address(0)) revert ZeroAddress(); + constructor(address admin) { + if (admin == address(0)) revert ZeroAddress(); _grantRole(DEFAULT_ADMIN_ROLE, admin); - signer = initialSigner; feeRecipient = admin; - emit SignerUpdated(initialSigner); emit FeeUpdated(0); emit FeeRecipientUpdated(admin); } @@ -55,19 +50,13 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard, EIP712 { // ───────── Tipping ───────── /// @inheritdoc ITipping - function tip(TipAuthorization calldata auth, bytes calldata signature) external nonReentrant { - if ( - auth.tipper != msg.sender - || !SignatureChecker.isValidSignatureNow(signer, hashAuthorization(auth), signature) - ) { - revert InvalidSignature(); - } - if (block.timestamp > auth.deadline) revert Expired(auth.deadline); - if (nonceUsed[auth.nonce]) revert NonceUsed(auth.nonce); - nonceUsed[auth.nonce] = true; - - uint256 fee = _pay(auth.token, auth.recipient, auth.amount); - emit Tipped(msg.sender, auth.collection, auth.tokenId, auth.token, auth.recipient, auth.amount, fee); + function tip(address collection, Standard standard, uint256 tokenId, address token, uint256 amount) + external + nonReentrant + { + address recipient = _resolve(collection, standard, tokenId); + uint256 fee = _pay(token, recipient, amount); + emit Tipped(msg.sender, collection, tokenId, token, recipient, amount, fee); } /// @inheritdoc ITipping @@ -76,6 +65,36 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard, EIP712 { emit AccountTipped(msg.sender, to, token, amount, fee); } + /// @inheritdoc ITipping + function recipientOf(address collection, Standard standard, uint256 tokenId) external view returns (address) { + return _resolve(collection, standard, tokenId); + } + + /// @dev ERC-721: the current owner. ERC-1155: the ERC-2981 receiver for the id, after + /// rejecting ids whose tracked supply is zero (when the collection exposes totalSupply(id)). + function _resolve(address collection, Standard standard, uint256 tokenId) internal view returns (address) { + if (collection.code.length == 0) revert NotAContract(collection); + if (standard == Standard.ERC721) { + try IERC721(collection).ownerOf(tokenId) returns (address owner) { + if (owner == address(0)) revert NoRecipient(collection, tokenId); + return owner; + } catch { + revert InvalidToken(collection, tokenId); + } + } + try IERC1155SupplyLike(collection).totalSupply(tokenId) returns (uint256 supply) { + if (supply == 0) revert InvalidToken(collection, tokenId); + } catch { + // No supply extension: the royalty lookup below is the only check available. + } + try IERC2981(collection).royaltyInfo(tokenId, BPS) returns (address receiver, uint256) { + if (receiver == address(0)) revert NoRecipient(collection, tokenId); + return receiver; + } catch { + revert NoRecipient(collection, tokenId); + } + } + /// @dev Shared guards and transfers. Only ever pulls from msg.sender: the property the /// immutability argument rests on. Returns the fee taken. function _pay(address token, address to, uint256 amount) internal returns (uint256 fee) { @@ -87,33 +106,8 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard, EIP712 { if (fee > 0) IERC20(token).safeTransferFrom(msg.sender, feeRecipient, fee); } - /// @inheritdoc ITipping - function hashAuthorization(TipAuthorization calldata auth) public view returns (bytes32) { - return _hashTypedDataV4( - keccak256( - abi.encode( - TIP_AUTHORIZATION_TYPEHASH, - auth.tipper, - auth.token, - auth.collection, - auth.tokenId, - auth.recipient, - auth.amount, - auth.deadline, - auth.nonce - ) - ) - ); - } - // ───────── Admin ───────── - function setSigner(address newSigner) external onlyRole(DEFAULT_ADMIN_ROLE) { - if (newSigner == address(0)) revert ZeroAddress(); - signer = newSigner; - emit SignerUpdated(newSigner); - } - function setFee(uint16 bps) external onlyRole(DEFAULT_ADMIN_ROLE) { if (bps > MAX_FEE_BPS) revert FeeTooHigh(bps); feeBps = bps; diff --git a/test/tipping/Tipping.t.sol b/test/tipping/Tipping.t.sol index 5f772419..e8a62d63 100644 --- a/test/tipping/Tipping.t.sol +++ b/test/tipping/Tipping.t.sol @@ -3,9 +3,12 @@ pragma solidity ^0.8.26; import {Test} from "forge-std/Test.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import {ERC1155} from "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; +import {ERC1155Supply} from "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol"; +import {ERC2981} from "@openzeppelin/contracts/token/common/ERC2981.sol"; import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol"; -import {IERC1271} from "@openzeppelin/contracts/interfaces/IERC1271.sol"; -import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; +import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import {Tipping} from "../../src/tipping/Tipping.sol"; import {ITipping} from "../../src/tipping/ITipping.sol"; @@ -32,41 +35,94 @@ contract TokenMock is ERC20 { } } -/// @dev An ERC-1271 signer: valid when the digest was signed by its one owner key. -contract WalletSignerMock is IERC1271 { - address internal immutable owner; +/// @dev A Click-style post: plain ERC-721, transferable, no royalties. +contract Post721 is ERC721 { + constructor() ERC721("Click", "CLK") {} - constructor(address owner_) { - owner = owner_; + function mint(address to, uint256 id) external { + _mint(to, id); } - function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4) { - (address recovered,,) = ECDSA.tryRecover(hash, signature); - return recovered == owner ? IERC1271.isValidSignature.selector : bytes4(0); + function burn(uint256 id) external { + _burn(id); + } +} + +/// @dev A factory-style edition: ERC-1155 with supply tracking and a default royalty receiver. +contract Edition1155 is ERC1155Supply, ERC2981 { + constructor() ERC1155("ipfs://x") {} + + function mint(address to, uint256 id, uint256 amount) external { + _mint(to, id, amount, ""); + } + + function burn(address from, uint256 id, uint256 amount) external { + _burn(from, id, amount); + } + + function setRoyalty(address receiver, uint96 bps) external { + if (receiver == address(0)) _deleteDefaultRoyalty(); + else _setDefaultRoyalty(receiver, bps); + } + + function supportsInterface(bytes4 id) public view override(ERC1155, ERC2981) returns (bool) { + return super.supportsInterface(id); + } +} + +/// @dev An ERC-1155 that tracks no supply and pays no royalties (nothing to resolve). +contract Bare1155 is ERC1155 { + constructor() ERC1155("ipfs://y") {} + + function mint(address to, uint256 id, uint256 amount) external { + _mint(to, id, amount, ""); + } +} + +/// @dev A hostile "collection": ownerOf tries to re-enter the tipping contract. +contract ReentrantCollection { + Tipping internal immutable tipping; + address internal immutable token; + + constructor(Tipping t, address tok) { + tipping = t; + token = tok; + } + + function ownerOf(uint256) external returns (address) { + tipping.tipAccount(token, address(0xBEEF), 1); + return address(this); } } contract TippingTest is Test { TokenMock internal nodl; TokenMock internal usdc; + Post721 internal post; + Edition1155 internal edition; + Bare1155 internal bare; Tipping internal tipping; address internal constant ADMIN = address(0xAD); address internal constant ALICE = address(0xA1); address internal constant BOB = address(0xB0); - address internal constant COLLECTION = address(0xC0111); - uint256 internal constant TOKEN_ID = 7; - - uint256 internal signerKey; - address internal signer; - uint256 internal otherKey; + address internal constant CREATOR = address(0xC4); + uint256 internal constant POST_ID = 7; + uint256 internal constant EDITION_ID = 0; function setUp() public { - (signer, signerKey) = makeAddrAndKey("signer"); - (, otherKey) = makeAddrAndKey("other"); nodl = new TokenMock("NODL"); usdc = new TokenMock("USDC"); - tipping = new Tipping(ADMIN, signer); + post = new Post721(); + edition = new Edition1155(); + bare = new Bare1155(); + tipping = new Tipping(ADMIN); + + post.mint(BOB, POST_ID); + edition.mint(ALICE, EDITION_ID, 100); + edition.setRoyalty(CREATOR, 500); + bare.mint(BOB, 1, 1); + nodl.mint(ALICE, 1_000e18); usdc.mint(ALICE, 1_000e6); vm.startPrank(ALICE); @@ -75,269 +131,194 @@ contract TippingTest is Test { vm.stopPrank(); } - // ───────── helpers ───────── - - function auth(address token, address recipient, uint256 amount) - internal - view - returns (ITipping.TipAuthorization memory) - { - return ITipping.TipAuthorization({ - tipper: ALICE, - token: token, - collection: COLLECTION, - tokenId: TOKEN_ID, - recipient: recipient, - amount: amount, - deadline: block.timestamp + 300, - nonce: keccak256(abi.encode(token, recipient, amount, block.timestamp)) - }); - } - - function copy(ITipping.TipAuthorization memory a) internal pure returns (ITipping.TipAuthorization memory b) { - b = ITipping.TipAuthorization( - a.tipper, a.token, a.collection, a.tokenId, a.recipient, a.amount, a.deadline, a.nonce - ); - } - - /// @dev Signs, then calls `tip` as `who`. Signing is an external call, so it must happen - /// before any prank or expectEmit. - function tipAs(address who, uint256 key, ITipping.TipAuthorization memory a) internal { - bytes memory sig = sign(key, a); - vm.prank(who); - tipping.tip(a, sig); - } - - /// @dev Signs first, then expects `tip` as `who` to revert with `data`. - function expectTipRevert(address who, uint256 key, ITipping.TipAuthorization memory a, bytes memory data) internal { - bytes memory sig = sign(key, a); + function tipPost(address who, uint256 amount) internal { vm.prank(who); - vm.expectRevert(data); - tipping.tip(a, sig); - } - - function sign(uint256 key, ITipping.TipAuthorization memory a) internal view returns (bytes memory) { - (uint8 v, bytes32 r, bytes32 s) = vm.sign(key, tipping.hashAuthorization(a)); - return abi.encodePacked(r, s, v); + tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, address(nodl), amount); } // ───────── Constructor ───────── function test_constructor_state() public view { - assertEq(tipping.signer(), signer); assertEq(tipping.feeBps(), 0); assertEq(tipping.feeRecipient(), ADMIN); assertTrue(tipping.hasRole(tipping.DEFAULT_ADMIN_ROLE(), ADMIN)); } function test_constructor_emitsInitialSettings() public { - vm.expectEmit(true, true, true, true); - emit ITipping.SignerUpdated(signer); vm.expectEmit(true, true, true, true); emit ITipping.FeeUpdated(0); vm.expectEmit(true, true, true, true); emit ITipping.FeeRecipientUpdated(ADMIN); - new Tipping(ADMIN, signer); + new Tipping(ADMIN); } - function test_constructor_rejectsZeroAddresses() public { + function test_constructor_rejectsZeroAdmin() public { vm.expectRevert(ITipping.ZeroAddress.selector); - new Tipping(address(0), signer); - vm.expectRevert(ITipping.ZeroAddress.selector); - new Tipping(ADMIN, address(0)); - } - - function test_eip712Domain() public view { - (, string memory name, string memory version, uint256 chainId, address verifying,,) = tipping.eip712Domain(); - assertEq(name, "NodleTipping"); - assertEq(version, "1"); - assertEq(chainId, block.chainid); - assertEq(verifying, address(tipping)); + new Tipping(address(0)); } - // ───────── Post tips ───────── + // ───────── ERC-721 posts ───────── - function test_tip_paysRecipientAndMarksNonce() public { - ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 5e18); - bytes memory sig = sign(signerKey, a); + function test_tip721_paysCurrentOwner() public { vm.expectEmit(true, true, true, true); - emit ITipping.Tipped(ALICE, COLLECTION, TOKEN_ID, address(nodl), BOB, 5e18, 0); - vm.prank(ALICE); - tipping.tip(a, sig); + emit ITipping.Tipped(ALICE, address(post), POST_ID, address(nodl), BOB, 5e18, 0); + tipPost(ALICE, 5e18); assertEq(nodl.balanceOf(BOB), 5e18); assertEq(nodl.balanceOf(ALICE), 995e18); - assertTrue(tipping.nonceUsed(a.nonce)); - // A zero fee means a single transfer, straight to the recipient. assertEq(nodl.transfers(), 1); } - function test_tip_anyErc20() public { - ITipping.TipAuthorization memory a = auth(address(usdc), BOB, 25e6); - tipAs(ALICE, signerKey, a); - assertEq(usdc.balanceOf(BOB), 25e6); + function test_tip721_followsTransfers() public { + vm.prank(BOB); + post.transferFrom(BOB, CREATOR, POST_ID); + assertEq(tipping.recipientOf(address(post), ITipping.Standard.ERC721, POST_ID), CREATOR); + tipPost(ALICE, 1e18); + assertEq(nodl.balanceOf(CREATOR), 1e18); assertEq(nodl.balanceOf(BOB), 0); } - function test_tip_nonceCannotBeReplayed() public { - ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 5e18); - bytes memory sig = sign(signerKey, a); - vm.prank(ALICE); - tipping.tip(a, sig); + function test_tip721_unmintedOrBurnedIsInvalid() public { vm.prank(ALICE); - vm.expectRevert(abi.encodeWithSelector(ITipping.NonceUsed.selector, a.nonce)); - tipping.tip(a, sig); - } + vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidToken.selector, address(post), 99)); + tipping.tip(address(post), ITipping.Standard.ERC721, 99, address(nodl), 1e18); - function test_tip_expiredReverts() public { - ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 5e18); - bytes memory sig = sign(signerKey, a); - vm.warp(a.deadline + 1); - vm.prank(ALICE); - vm.expectRevert(abi.encodeWithSelector(ITipping.Expired.selector, a.deadline)); - tipping.tip(a, sig); - // Exactly at the deadline is still valid. - vm.warp(a.deadline); + post.burn(POST_ID); vm.prank(ALICE); - tipping.tip(a, sig); - assertEq(nodl.balanceOf(BOB), 5e18); + vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidToken.selector, address(post), POST_ID)); + tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, address(nodl), 1e18); } - function test_tip_wrongSignerReverts() public { - ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 5e18); - expectTipRevert(ALICE, otherKey, a, abi.encodeWithSelector(ITipping.InvalidSignature.selector)); + function test_tip721_ownerCannotTipOwnPost() public { + nodl.mint(BOB, 1e18); + vm.prank(BOB); + nodl.approve(address(tipping), 1e18); + vm.prank(BOB); + vm.expectRevert(ITipping.SelfTip.selector); + tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, address(nodl), 1e18); } - function test_tip_malformedSignatureReverts() public { - ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 5e18); + function test_tip_anyErc20() public { vm.prank(ALICE); - vm.expectRevert(ITipping.InvalidSignature.selector); - tipping.tip(a, hex"deadbeef"); + tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, address(usdc), 3e6); + assertEq(usdc.balanceOf(BOB), 3e6); } - function test_tip_callerMustBeTipper() public { - ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 5e18); - bytes memory sig = sign(signerKey, a); - nodl.mint(address(0xC0), 10e18); - vm.prank(address(0xC0)); - nodl.approve(address(tipping), type(uint256).max); - vm.prank(address(0xC0)); - vm.expectRevert(ITipping.InvalidSignature.selector); - tipping.tip(a, sig); - } + // ───────── ERC-1155 editions ───────── - function test_tip_tamperedFieldsInvalidateSignature() public { - ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 5e18); - bytes memory sig = sign(signerKey, a); + function test_tip1155_paysRoyaltyReceiver() public { + vm.expectEmit(true, true, true, true); + emit ITipping.Tipped(ALICE, address(edition), EDITION_ID, address(nodl), CREATOR, 2e18, 0); + vm.prank(ALICE); + tipping.tip(address(edition), ITipping.Standard.ERC1155, EDITION_ID, address(nodl), 2e18); + assertEq(nodl.balanceOf(CREATOR), 2e18); + assertEq(tipping.recipientOf(address(edition), ITipping.Standard.ERC1155, EDITION_ID), CREATOR); + } - ITipping.TipAuthorization memory t = copy(a); - t.recipient = address(0xBAD); + function test_tip1155_zeroSupplyIsInvalid() public { vm.prank(ALICE); - vm.expectRevert(ITipping.InvalidSignature.selector); - tipping.tip(t, sig); + vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidToken.selector, address(edition), 42)); + tipping.tip(address(edition), ITipping.Standard.ERC1155, 42, address(nodl), 1e18); - t = copy(a); - t.amount = 500e18; + edition.burn(ALICE, EDITION_ID, 100); vm.prank(ALICE); - vm.expectRevert(ITipping.InvalidSignature.selector); - tipping.tip(t, sig); + vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidToken.selector, address(edition), EDITION_ID)); + tipping.tip(address(edition), ITipping.Standard.ERC1155, EDITION_ID, address(nodl), 1e18); + } - t = copy(a); - t.token = address(usdc); + function test_tip1155_noRoyaltyReceiverHasNoRecipient() public { + edition.setRoyalty(address(0), 0); vm.prank(ALICE); - vm.expectRevert(ITipping.InvalidSignature.selector); - tipping.tip(t, sig); + vm.expectRevert(abi.encodeWithSelector(ITipping.NoRecipient.selector, address(edition), EDITION_ID)); + tipping.tip(address(edition), ITipping.Standard.ERC1155, EDITION_ID, address(nodl), 1e18); - t = copy(a); - t.tokenId = 8; + // No supply extension and no ERC-2981 at all: nothing to resolve either. vm.prank(ALICE); - vm.expectRevert(ITipping.InvalidSignature.selector); - tipping.tip(t, sig); + vm.expectRevert(abi.encodeWithSelector(ITipping.NoRecipient.selector, address(bare), 1)); + tipping.tip(address(bare), ITipping.Standard.ERC1155, 1, address(nodl), 1e18); + } + + function test_tip1155_royaltyReceiverCannotTipItself() public { + nodl.mint(CREATOR, 1e18); + vm.startPrank(CREATOR); + nodl.approve(address(tipping), 1e18); + vm.expectRevert(ITipping.SelfTip.selector); + tipping.tip(address(edition), ITipping.Standard.ERC1155, EDITION_ID, address(nodl), 1e18); + vm.stopPrank(); + } + + // ───────── Resolution guards ───────── - t = copy(a); - t.deadline += 1; + function test_tip_wrongStandardFailsToResolve() public { + // ERC-1155 path on a plain ERC-721: no totalSupply, no royaltyInfo. + vm.prank(ALICE); + vm.expectRevert(abi.encodeWithSelector(ITipping.NoRecipient.selector, address(post), POST_ID)); + tipping.tip(address(post), ITipping.Standard.ERC1155, POST_ID, address(nodl), 1e18); + // ERC-721 path on an ERC-1155: no ownerOf. vm.prank(ALICE); - vm.expectRevert(ITipping.InvalidSignature.selector); - tipping.tip(t, sig); + vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidToken.selector, address(edition), EDITION_ID)); + tipping.tip(address(edition), ITipping.Standard.ERC721, EDITION_ID, address(nodl), 1e18); } - function test_tip_rotatedSignerInvalidatesOldSignatures() public { - ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 5e18); - bytes memory sig = sign(signerKey, a); - (address next, uint256 nextKey) = makeAddrAndKey("next"); - vm.prank(ADMIN); - vm.expectEmit(true, true, true, true); - emit ITipping.SignerUpdated(next); - tipping.setSigner(next); + function test_tip_collectionMustBeAContract() public { vm.prank(ALICE); - vm.expectRevert(ITipping.InvalidSignature.selector); - tipping.tip(a, sig); - tipAs(ALICE, nextKey, a); - assertEq(nodl.balanceOf(BOB), 5e18); + vm.expectRevert(abi.encodeWithSelector(ITipping.NotAContract.selector, address(0xD00D))); + tipping.tip(address(0xD00D), ITipping.Standard.ERC721, 1, address(nodl), 1e18); + vm.expectRevert(abi.encodeWithSelector(ITipping.NotAContract.selector, address(0))); + tipping.recipientOf(address(0), ITipping.Standard.ERC721, 1); } - function test_tip_contractSigner() public { - WalletSignerMock wallet = new WalletSignerMock(signer); - vm.prank(ADMIN); - tipping.setSigner(address(wallet)); - ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 5e18); - tipAs(ALICE, signerKey, a); - assertEq(nodl.balanceOf(BOB), 5e18); - expectTipRevert( - ALICE, otherKey, auth(address(nodl), BOB, 1e18), abi.encodeWithSelector(ITipping.InvalidSignature.selector) - ); + function test_tip_lookupIsStaticAndCannotReenter() public { + ReentrantCollection evil = new ReentrantCollection(tipping, address(nodl)); + // ownerOf is declared view on IERC721, so the call is a STATICCALL: the reentrant + // tipAccount inside it reverts, the try/catch turns that into InvalidToken. + vm.prank(ALICE); + vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidToken.selector, address(evil), 1)); + tipping.tip(address(evil), ITipping.Standard.ERC721, 1, address(nodl), 1e18); + assertEq(nodl.transfers(), 0); } function test_tip_guards() public { - ITipping.TipAuthorization memory a = auth(address(nodl), ALICE, 5e18); - expectTipRevert(ALICE, signerKey, a, abi.encodeWithSelector(ITipping.SelfTip.selector)); - - a = auth(address(nodl), BOB, 0); - expectTipRevert(ALICE, signerKey, a, abi.encodeWithSelector(ITipping.ZeroAmount.selector)); - - a = auth(address(nodl), address(0), 5e18); - expectTipRevert(ALICE, signerKey, a, abi.encodeWithSelector(ITipping.ZeroAddress.selector)); - - a = auth(address(0), BOB, 5e18); - expectTipRevert(ALICE, signerKey, a, abi.encodeWithSelector(ITipping.ZeroAddress.selector)); + vm.startPrank(ALICE); + vm.expectRevert(ITipping.ZeroAddress.selector); + tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, address(0), 1e18); + vm.expectRevert(ITipping.ZeroAmount.selector); + tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, address(nodl), 0); + vm.stopPrank(); } function test_tip_insufficientAllowanceOrBalanceReverts() public { - nodl.mint(address(0xC0), 10e18); - ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 2e18); - a.tipper = address(0xC0); - bytes memory sig = sign(signerKey, a); - vm.prank(address(0xC0)); + vm.prank(ALICE); + nodl.approve(address(tipping), 1e18); + vm.prank(ALICE); vm.expectRevert(); - tipping.tip(a, sig); - vm.prank(address(0xC0)); + tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, address(nodl), 2e18); + vm.prank(ALICE); nodl.approve(address(tipping), type(uint256).max); - a.amount = 11e18; - sig = sign(signerKey, a); - vm.prank(address(0xC0)); + vm.prank(ALICE); vm.expectRevert(); - tipping.tip(a, sig); + tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, address(nodl), 1_001e18); } // ───────── Account tips ───────── function test_tipAccount_paysNamedAddress() public { vm.expectEmit(true, true, true, true); - emit ITipping.AccountTipped(ALICE, BOB, address(usdc), 10e6, 0); + emit ITipping.AccountTipped(ALICE, BOB, address(nodl), 4e18, 0); vm.prank(ALICE); - tipping.tipAccount(address(usdc), BOB, 10e6); - assertEq(usdc.balanceOf(BOB), 10e6); + tipping.tipAccount(address(nodl), BOB, 4e18); + assertEq(nodl.balanceOf(BOB), 4e18); } function test_tipAccount_guards() public { vm.startPrank(ALICE); - vm.expectRevert(ITipping.SelfTip.selector); - tipping.tipAccount(address(nodl), ALICE, 1e18); - vm.expectRevert(ITipping.ZeroAmount.selector); - tipping.tipAccount(address(nodl), BOB, 0); vm.expectRevert(ITipping.ZeroAddress.selector); tipping.tipAccount(address(nodl), address(0), 1e18); vm.expectRevert(ITipping.ZeroAddress.selector); tipping.tipAccount(address(0), BOB, 1e18); + vm.expectRevert(ITipping.ZeroAmount.selector); + tipping.tipAccount(address(nodl), BOB, 0); + vm.expectRevert(ITipping.SelfTip.selector); + tipping.tipAccount(address(nodl), ALICE, 1e18); vm.stopPrank(); } @@ -349,27 +330,17 @@ contract TippingTest is Test { emit ITipping.FeeUpdated(250); tipping.setFee(250); vm.prank(ADMIN); - vm.expectEmit(true, true, true, true); - emit ITipping.FeeRecipientUpdated(address(0xFEE)); - tipping.setFeeRecipient(address(0xFEE)); + tipping.setFeeRecipient(CREATOR); - ITipping.TipAuthorization memory a = auth(address(nodl), BOB, 100e18); - bytes memory sig = sign(signerKey, a); vm.expectEmit(true, true, true, true); - emit ITipping.Tipped(ALICE, COLLECTION, TOKEN_ID, address(nodl), BOB, 100e18, 2.5e18); - vm.prank(ALICE); - tipping.tip(a, sig); + emit ITipping.Tipped(ALICE, address(post), POST_ID, address(nodl), BOB, 100e18, 2.5e18); + tipPost(ALICE, 100e18); assertEq(nodl.balanceOf(BOB), 97.5e18); - assertEq(nodl.balanceOf(address(0xFEE)), 2.5e18); + assertEq(nodl.balanceOf(CREATOR), 2.5e18); assertEq(nodl.transfers(), 2); - vm.prank(ALICE); - tipping.tipAccount(address(usdc), BOB, 100e6); - assertEq(usdc.balanceOf(BOB), 97.5e6); - assertEq(usdc.balanceOf(address(0xFEE)), 2.5e6); - vm.prank(ADMIN); - vm.expectRevert(abi.encodeWithSelector(ITipping.FeeTooHigh.selector, 1001)); + vm.expectRevert(abi.encodeWithSelector(ITipping.FeeTooHigh.selector, uint16(1001))); tipping.setFee(1001); vm.prank(ADMIN); tipping.setFee(1000); @@ -378,11 +349,12 @@ contract TippingTest is Test { function test_feeRoundsDownInFavourOfRecipient() public { vm.prank(ADMIN); - tipping.setFee(1); // 0.01% + tipping.setFee(1); vm.prank(ALICE); tipping.tipAccount(address(nodl), BOB, 9_999); assertEq(nodl.balanceOf(BOB), 9_999); assertEq(nodl.balanceOf(ADMIN), 0); + assertEq(nodl.transfers(), 1); } function test_feeRecipientCannotBeZeroOrSelf() public { @@ -391,35 +363,30 @@ contract TippingTest is Test { tipping.setFeeRecipient(address(0)); vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidFeeRecipient.selector, address(tipping))); tipping.setFeeRecipient(address(tipping)); + vm.expectEmit(true, true, true, true); + emit ITipping.FeeRecipientUpdated(BOB); + tipping.setFeeRecipient(BOB); vm.stopPrank(); + assertEq(tipping.feeRecipient(), BOB); } - // ───────── Roles ───────── - function test_adminOnly() public { bytes memory denied = abi.encodeWithSelector(IAccessControl.AccessControlUnauthorizedAccount.selector, ALICE, bytes32(0)); vm.startPrank(ALICE); vm.expectRevert(denied); - tipping.setSigner(BOB); - vm.expectRevert(denied); tipping.setFee(1); vm.expectRevert(denied); tipping.setFeeRecipient(BOB); vm.stopPrank(); - vm.prank(ADMIN); - vm.expectRevert(ITipping.ZeroAddress.selector); - tipping.setSigner(address(0)); } - // ───────── Fuzz ───────── + // ───────── Invariant ───────── - /// @dev The immutability argument: tokens only ever leave the caller's own balance. - function testFuzz_transferFromOnlyFromCaller(address tipper, uint256 amount, uint16 bps, bool viaAuth) public { - vm.assume( - tipper != address(0) && tipper != BOB && tipper != ADMIN && tipper != address(nodl) - && tipper != address(tipping) - ); + /// @dev Whatever the path, token or fee, every transferFrom has `from == msg.sender`. + function testFuzz_transferFromOnlyFromCaller(address tipper, uint256 amount, uint16 bps, uint8 path) public { + vm.assume(tipper != address(0) && tipper != BOB && tipper != CREATOR && tipper != address(tipping)); + vm.assume(tipper.code.length == 0); amount = bound(amount, 1, 1e30); bps = uint16(bound(bps, 0, 1000)); vm.prank(ADMIN); @@ -428,47 +395,19 @@ contract TippingTest is Test { vm.prank(tipper); nodl.approve(address(tipping), amount); - if (viaAuth) { - ITipping.TipAuthorization memory a = auth(address(nodl), BOB, amount); - a.tipper = tipper; - bytes memory sig = sign(signerKey, a); - vm.prank(tipper); - tipping.tip(a, sig); - } else { - vm.prank(tipper); - tipping.tipAccount(address(nodl), BOB, amount); - } + vm.prank(tipper); + if (path % 3 == 0) tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, address(nodl), amount); + else if (path % 3 == 1) tipping.tip(address(edition), ITipping.Standard.ERC1155, EDITION_ID, address(nodl), amount); + else tipping.tipAccount(address(nodl), BOB, amount); - uint256 fee = (amount * bps) / 10_000; uint256 n = nodl.transfers(); - uint256 moved; - for (uint256 i; i < n; i++) { + assertTrue(n == 1 || n == 2); + uint256 total; + for (uint256 i = 0; i < n; i++) { assertEq(nodl.senders(i), tipper); - moved += nodl.amounts(i); + total += nodl.amounts(i); } - assertEq(moved, amount); + assertEq(total, amount); assertEq(nodl.balanceOf(tipper), 0); - assertEq(nodl.balanceOf(BOB), amount - fee); - assertEq(nodl.balanceOf(ADMIN), fee); - assertEq(n, fee > 0 ? 2 : 1); - } - - /// @dev Any single-bit change to the signed fields produces a different digest. - function testFuzz_digestBindsEveryField(ITipping.TipAuthorization memory a, uint8 field, uint256 delta) - public - view - { - vm.assume(delta != 0); - ITipping.TipAuthorization memory b = copy(a); - field = uint8(bound(field, 0, 7)); - if (field == 0) b.tipper = address(uint160(a.tipper) ^ uint160(delta | 1)); - else if (field == 1) b.token = address(uint160(a.token) ^ uint160(delta | 1)); - else if (field == 2) b.collection = address(uint160(a.collection) ^ uint160(delta | 1)); - else if (field == 3) b.tokenId = a.tokenId ^ delta; - else if (field == 4) b.recipient = address(uint160(a.recipient) ^ uint160(delta | 1)); - else if (field == 5) b.amount = a.amount ^ delta; - else if (field == 6) b.deadline = a.deadline ^ delta; - else b.nonce = a.nonce ^ bytes32(delta); - assertTrue(tipping.hashAuthorization(a) != tipping.hashAuthorization(b)); } } From 9850026efb3529ae2a7c073f539fd63d31951ea4 Mon Sep 17 00:00:00 2001 From: douglasacost Date: Wed, 28 Oct 2026 21:03:27 -0400 Subject: [PATCH 11/18] test(tipping): rename for the spell check --- test/tipping/Tipping.t.sol | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/tipping/Tipping.t.sol b/test/tipping/Tipping.t.sol index e8a62d63..ce66c0f6 100644 --- a/test/tipping/Tipping.t.sol +++ b/test/tipping/Tipping.t.sol @@ -177,7 +177,7 @@ contract TippingTest is Test { assertEq(nodl.balanceOf(BOB), 0); } - function test_tip721_unmintedOrBurnedIsInvalid() public { + function test_tip721_neverMintedOrBurnedIsInvalid() public { vm.prank(ALICE); vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidToken.selector, address(post), 99)); tipping.tip(address(post), ITipping.Standard.ERC721, 99, address(nodl), 1e18); From c8aa7a9b021133cb979ac787466f0cc856e2b993 Mon Sep 17 00:00:00 2001 From: douglasacost Date: Wed, 28 Oct 2026 22:28:03 -0400 Subject: [PATCH 12/18] feat(tipping): tip() takes the recipient and verifies it against the NFT Decision 2026-10-28: nothing can be enumerated from an ERC-1155 (no owner getter, roles are not enumerable), but a claim can be checked. tip(collection, standard, tokenId, recipient, token, amount) accepts the recipient when: ERC-721, ownerOf(tokenId) == recipient; ERC-1155, recipient holds the collection's OWNER_ROLE (Nodle collections grant it to the creator), or is its Ownable owner(), or its ERC-2981 receiver for the id. Supply-tracking editions reject ids with zero supply. isRecipient() view for clients and the API. Replaces recipientOf() and NoRecipient with NotRecipient(collection, tokenId, recipient). --- src/tipping/ITipping.sol | 27 ++++--- src/tipping/Tipping.sol | 68 +++++++++++------ test/tipping/Tipping.t.sol | 145 +++++++++++++++++++++++++++++-------- 3 files changed, 178 insertions(+), 62 deletions(-) diff --git a/src/tipping/ITipping.sol b/src/tipping/ITipping.sol index 4f99faa4..5524fcc6 100644 --- a/src/tipping/ITipping.sol +++ b/src/tipping/ITipping.sol @@ -3,11 +3,12 @@ pragma solidity ^0.8.26; /** * @title ITipping - * @notice Agnostic tipping: any ERC-20, any NFT, any account. The recipient of a post tip is - * resolved on-chain from the NFT itself: the current owner for ERC-721, the ERC-2981 - * royalty receiver for ERC-1155 (editions have many holders; the royalty receiver is the - * creator's payout address). No backend involvement, no signature, no allowlist. - * The event surface is what the feed indexer consumes; keep it stable. + * @notice Agnostic tipping: any ERC-20, any NFT, any account. The caller names the recipient of + * a post tip (the feed knows it) and the contract verifies the claim against the NFT: + * ERC-721, the recipient must be `ownerOf(tokenId)`; ERC-1155, the recipient must hold the + * collection's `OWNER_ROLE` (Nodle collections), or be its Ownable `owner()`, or be its + * ERC-2981 royalty receiver for the id. Nothing is enumerated on-chain, only checked. + * No backend signature, no allowlist. The event surface is what the feed indexer consumes. */ interface ITipping { enum Standard { @@ -36,18 +37,22 @@ interface ITipping { error NotAContract(address collection); /// @notice The NFT does not exist for the given standard (ownerOf reverted, or an ERC-1155 id with zero supply). error InvalidToken(address collection, uint256 tokenId); - /// @notice The NFT exists but names nobody to pay (zero owner, or an ERC-1155 without a royalty receiver). - error NoRecipient(address collection, uint256 tokenId); + /// @notice The named recipient is not the NFT's owner (ERC-721) nor the collection's owner / royalty receiver (ERC-1155). + error NotRecipient(address collection, uint256 tokenId, address recipient); error FeeTooHigh(uint16 feeBps); error InvalidFeeRecipient(address recipient); - /// @notice Tip the NFT `tokenId` of `collection` with `amount` of `token`. The recipient is resolved on-chain. - function tip(address collection, Standard standard, uint256 tokenId, address token, uint256 amount) external; + /// @notice Tip the NFT `tokenId` of `collection`: `recipient` is verified against the NFT, then paid `amount` of `token`. + function tip(address collection, Standard standard, uint256 tokenId, address recipient, address token, uint256 amount) + external; /// @notice Tip an account the caller names. function tipAccount(address token, address to, uint256 amount) external; - /// @notice Who a tip of this NFT would pay right now; reverts the way `tip` would. - function recipientOf(address collection, Standard standard, uint256 tokenId) external view returns (address); + /// @notice Whether `tip` would accept `recipient` for this NFT; reverts for a non-contract or an invalid token, like `tip`. + function isRecipient(address collection, Standard standard, uint256 tokenId, address recipient) + external + view + returns (bool); function feeBps() external view returns (uint16); function feeRecipient() external view returns (address); } diff --git a/src/tipping/Tipping.sol b/src/tipping/Tipping.sol index 699e8aaf..7d9e91d5 100644 --- a/src/tipping/Tipping.sol +++ b/src/tipping/Tipping.sol @@ -10,11 +10,19 @@ import {IERC2981} from "@openzeppelin/contracts/interfaces/IERC2981.sol"; import {ITipping} from "./ITipping.sol"; -/// @dev ERC-1155 supply extension (OpenZeppelin ERC1155Supply); optional on the collection. +/// @dev Optional surfaces an ERC-1155 collection may expose; each is probed behind try/catch. interface IERC1155SupplyLike { function totalSupply(uint256 id) external view returns (uint256); } +interface IRoleLike { + function hasRole(bytes32 role, address account) external view returns (bool); +} + +interface IOwnableLike { + function owner() external view returns (address); +} + /** * @title Tipping * @notice Immutable, agnostic tipping (nft-feed-indexer design §6.2, v2 of 2026-10-28). No proxy, @@ -22,11 +30,13 @@ interface IERC1155SupplyLike { * can only ever be spent by the approver's own `tip`/`tipAccount` calls, because * `transferFrom` is only called with `from == msg.sender`. The contract holds no funds. * - * Post tips resolve the recipient from the NFT: `ownerOf(tokenId)` for ERC-721, the ERC-2981 - * royalty receiver for ERC-1155 (an edition has many holders; its royalty receiver is where the - * creator is paid). The caller states the standard; a wrong standard simply fails to resolve. - * The lookups are `view` calls (STATICCALL), so a hostile collection can only make the tip - * revert or burn the tipper's own gas. Account tips name their recipient directly. + * Post tips name their recipient (the feed knows who made or holds a post); the contract only + * verifies the claim against the NFT: ERC-721 → `ownerOf(tokenId) == recipient`; ERC-1155 → + * the recipient holds the collection's `OWNER_ROLE` (Nodle collections grant it to the creator), + * or is its Ownable `owner()`, or its ERC-2981 royalty receiver for the id. Nothing can be + * enumerated from an ERC-1155, but a claim can be checked. The lookups are `view` calls + * (STATICCALL) behind try/catch, so a hostile collection can only make the tip revert or burn + * the tipper's own gas. Account tips name their recipient with no check. * * Roles: DEFAULT_ADMIN_ROLE (fee ≤ 10 %, fee recipient). */ @@ -35,6 +45,8 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard { uint16 public constant MAX_FEE_BPS = 1000; uint256 public constant BPS = 10_000; + /// @dev Role Nodle user collections grant to their creator (keccak256("OWNER_ROLE")). + bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); uint16 public feeBps; address public feeRecipient; @@ -50,11 +62,11 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard { // ───────── Tipping ───────── /// @inheritdoc ITipping - function tip(address collection, Standard standard, uint256 tokenId, address token, uint256 amount) + function tip(address collection, Standard standard, uint256 tokenId, address recipient, address token, uint256 amount) external nonReentrant { - address recipient = _resolve(collection, standard, tokenId); + if (!_isRecipient(collection, standard, tokenId, recipient)) revert NotRecipient(collection, tokenId, recipient); uint256 fee = _pay(token, recipient, amount); emit Tipped(msg.sender, collection, tokenId, token, recipient, amount, fee); } @@ -66,18 +78,28 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard { } /// @inheritdoc ITipping - function recipientOf(address collection, Standard standard, uint256 tokenId) external view returns (address) { - return _resolve(collection, standard, tokenId); + function isRecipient(address collection, Standard standard, uint256 tokenId, address recipient) + external + view + returns (bool) + { + return _isRecipient(collection, standard, tokenId, recipient); } - /// @dev ERC-721: the current owner. ERC-1155: the ERC-2981 receiver for the id, after - /// rejecting ids whose tracked supply is zero (when the collection exposes totalSupply(id)). - function _resolve(address collection, Standard standard, uint256 tokenId) internal view returns (address) { + /// @dev ERC-721: `recipient` must be the current owner. ERC-1155: the id must exist (tracked + /// supply, when exposed, must be non-zero) and `recipient` must hold OWNER_ROLE, be the + /// Ownable owner, or be the ERC-2981 receiver for the id. Reverts for non-contracts and + /// invalid tokens; returns false for a wrong recipient. + function _isRecipient(address collection, Standard standard, uint256 tokenId, address recipient) + internal + view + returns (bool) + { if (collection.code.length == 0) revert NotAContract(collection); + if (recipient == address(0)) return false; if (standard == Standard.ERC721) { try IERC721(collection).ownerOf(tokenId) returns (address owner) { - if (owner == address(0)) revert NoRecipient(collection, tokenId); - return owner; + return owner == recipient; } catch { revert InvalidToken(collection, tokenId); } @@ -85,14 +107,18 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard { try IERC1155SupplyLike(collection).totalSupply(tokenId) returns (uint256 supply) { if (supply == 0) revert InvalidToken(collection, tokenId); } catch { - // No supply extension: the royalty lookup below is the only check available. + // No supply extension: nothing to check here. } + try IRoleLike(collection).hasRole(OWNER_ROLE, recipient) returns (bool held) { + if (held) return true; + } catch {} + try IOwnableLike(collection).owner() returns (address owner) { + if (owner == recipient) return true; + } catch {} try IERC2981(collection).royaltyInfo(tokenId, BPS) returns (address receiver, uint256) { - if (receiver == address(0)) revert NoRecipient(collection, tokenId); - return receiver; - } catch { - revert NoRecipient(collection, tokenId); - } + if (receiver == recipient) return true; + } catch {} + return false; } /// @dev Shared guards and transfers. Only ever pulls from msg.sender: the property the diff --git a/test/tipping/Tipping.t.sol b/test/tipping/Tipping.t.sol index ce66c0f6..e53ccb81 100644 --- a/test/tipping/Tipping.t.sol +++ b/test/tipping/Tipping.t.sol @@ -8,6 +8,8 @@ import {ERC1155} from "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import {ERC1155Supply} from "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol"; import {ERC2981} from "@openzeppelin/contracts/token/common/ERC2981.sol"; import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol"; +import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; +import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import {Tipping} from "../../src/tipping/Tipping.sol"; @@ -70,7 +72,33 @@ contract Edition1155 is ERC1155Supply, ERC2981 { } } -/// @dev An ERC-1155 that tracks no supply and pays no royalties (nothing to resolve). +/// @dev A Nodle-style edition: supply tracking, OWNER_ROLE held by the creator, no royalty. +contract NodleEdition1155 is ERC1155Supply, AccessControl { + bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); + + constructor(address owner_) ERC1155("ipfs://n") { + _grantRole(OWNER_ROLE, owner_); + } + + function mint(address to, uint256 id, uint256 amount) external { + _mint(to, id, amount, ""); + } + + function supportsInterface(bytes4 id) public view override(ERC1155, AccessControl) returns (bool) { + return super.supportsInterface(id); + } +} + +/// @dev A third-party Ownable edition: no roles, no royalty, no supply tracking. +contract Ownable1155 is ERC1155, Ownable { + constructor(address owner_) ERC1155("ipfs://o") Ownable(owner_) {} + + function mint(address to, uint256 id, uint256 amount) external { + _mint(to, id, amount, ""); + } +} + +/// @dev An ERC-1155 that tracks no supply, pays no royalties and has no owner (nothing to verify against). contract Bare1155 is ERC1155 { constructor() ERC1155("ipfs://y") {} @@ -100,6 +128,8 @@ contract TippingTest is Test { TokenMock internal usdc; Post721 internal post; Edition1155 internal edition; + NodleEdition1155 internal nodleEdition; + Ownable1155 internal ownable; Bare1155 internal bare; Tipping internal tipping; @@ -116,12 +146,16 @@ contract TippingTest is Test { post = new Post721(); edition = new Edition1155(); bare = new Bare1155(); + nodleEdition = new NodleEdition1155(CREATOR); + ownable = new Ownable1155(CREATOR); tipping = new Tipping(ADMIN); post.mint(BOB, POST_ID); edition.mint(ALICE, EDITION_ID, 100); edition.setRoyalty(CREATOR, 500); bare.mint(BOB, 1, 1); + nodleEdition.mint(ALICE, EDITION_ID, 10); + ownable.mint(ALICE, EDITION_ID, 10); nodl.mint(ALICE, 1_000e18); usdc.mint(ALICE, 1_000e6); @@ -132,8 +166,13 @@ contract TippingTest is Test { } function tipPost(address who, uint256 amount) internal { + address owner = post.ownerOf(POST_ID); // before the prank: an external call would consume it vm.prank(who); - tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, address(nodl), amount); + tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, owner, address(nodl), amount); + } + + function notRecipient(address collection, uint256 id, address who) internal pure returns (bytes memory) { + return abi.encodeWithSelector(ITipping.NotRecipient.selector, collection, id, who); } // ───────── Constructor ───────── @@ -171,21 +210,26 @@ contract TippingTest is Test { function test_tip721_followsTransfers() public { vm.prank(BOB); post.transferFrom(BOB, CREATOR, POST_ID); - assertEq(tipping.recipientOf(address(post), ITipping.Standard.ERC721, POST_ID), CREATOR); + assertTrue(tipping.isRecipient(address(post), ITipping.Standard.ERC721, POST_ID, CREATOR)); + assertFalse(tipping.isRecipient(address(post), ITipping.Standard.ERC721, POST_ID, BOB)); tipPost(ALICE, 1e18); assertEq(nodl.balanceOf(CREATOR), 1e18); assertEq(nodl.balanceOf(BOB), 0); + // The previous owner is no longer a valid recipient. + vm.prank(ALICE); + vm.expectRevert(notRecipient(address(post), POST_ID, BOB)); + tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, BOB, address(nodl), 1e18); } function test_tip721_neverMintedOrBurnedIsInvalid() public { vm.prank(ALICE); vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidToken.selector, address(post), 99)); - tipping.tip(address(post), ITipping.Standard.ERC721, 99, address(nodl), 1e18); + tipping.tip(address(post), ITipping.Standard.ERC721, 99, BOB, address(nodl), 1e18); post.burn(POST_ID); vm.prank(ALICE); vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidToken.selector, address(post), POST_ID)); - tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, address(nodl), 1e18); + tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, BOB, address(nodl), 1e18); } function test_tip721_ownerCannotTipOwnPost() public { @@ -194,12 +238,12 @@ contract TippingTest is Test { nodl.approve(address(tipping), 1e18); vm.prank(BOB); vm.expectRevert(ITipping.SelfTip.selector); - tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, address(nodl), 1e18); + tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, BOB, address(nodl), 1e18); } function test_tip_anyErc20() public { vm.prank(ALICE); - tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, address(usdc), 3e6); + tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, BOB, address(usdc), 3e6); assertEq(usdc.balanceOf(BOB), 3e6); } @@ -209,32 +253,73 @@ contract TippingTest is Test { vm.expectEmit(true, true, true, true); emit ITipping.Tipped(ALICE, address(edition), EDITION_ID, address(nodl), CREATOR, 2e18, 0); vm.prank(ALICE); - tipping.tip(address(edition), ITipping.Standard.ERC1155, EDITION_ID, address(nodl), 2e18); + tipping.tip(address(edition), ITipping.Standard.ERC1155, EDITION_ID, CREATOR, address(nodl), 2e18); assertEq(nodl.balanceOf(CREATOR), 2e18); - assertEq(tipping.recipientOf(address(edition), ITipping.Standard.ERC1155, EDITION_ID), CREATOR); + assertTrue(tipping.isRecipient(address(edition), ITipping.Standard.ERC1155, EDITION_ID, CREATOR)); + assertFalse(tipping.isRecipient(address(edition), ITipping.Standard.ERC1155, EDITION_ID, ALICE)); } function test_tip1155_zeroSupplyIsInvalid() public { vm.prank(ALICE); vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidToken.selector, address(edition), 42)); - tipping.tip(address(edition), ITipping.Standard.ERC1155, 42, address(nodl), 1e18); + tipping.tip(address(edition), ITipping.Standard.ERC1155, 42, CREATOR, address(nodl), 1e18); edition.burn(ALICE, EDITION_ID, 100); vm.prank(ALICE); vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidToken.selector, address(edition), EDITION_ID)); - tipping.tip(address(edition), ITipping.Standard.ERC1155, EDITION_ID, address(nodl), 1e18); + tipping.tip(address(edition), ITipping.Standard.ERC1155, EDITION_ID, CREATOR, address(nodl), 1e18); } - function test_tip1155_noRoyaltyReceiverHasNoRecipient() public { + function test_tip1155_royaltyReceiverIsTheOnlyProofOnThisEdition() public { + // Someone else than the royalty receiver is refused. + vm.prank(ALICE); + vm.expectRevert(notRecipient(address(edition), EDITION_ID, BOB)); + tipping.tip(address(edition), ITipping.Standard.ERC1155, EDITION_ID, BOB, address(nodl), 1e18); + // With the royalty removed nobody can be verified any more. edition.setRoyalty(address(0), 0); vm.prank(ALICE); - vm.expectRevert(abi.encodeWithSelector(ITipping.NoRecipient.selector, address(edition), EDITION_ID)); - tipping.tip(address(edition), ITipping.Standard.ERC1155, EDITION_ID, address(nodl), 1e18); + vm.expectRevert(notRecipient(address(edition), EDITION_ID, CREATOR)); + tipping.tip(address(edition), ITipping.Standard.ERC1155, EDITION_ID, CREATOR, address(nodl), 1e18); + // No supply extension, no roles, no owner, no ERC-2981: nothing to verify against. + vm.prank(ALICE); + vm.expectRevert(notRecipient(address(bare), 1, BOB)); + tipping.tip(address(bare), ITipping.Standard.ERC1155, 1, BOB, address(nodl), 1e18); + } + + function test_tip1155_nodleEditionPaysItsOwnerRoleHolder() public { + // Nodle collections: no royalty, but the creator holds OWNER_ROLE. + assertTrue(tipping.isRecipient(address(nodleEdition), ITipping.Standard.ERC1155, EDITION_ID, CREATOR)); + assertFalse(tipping.isRecipient(address(nodleEdition), ITipping.Standard.ERC1155, EDITION_ID, ALICE)); + vm.expectEmit(true, true, true, true); + emit ITipping.Tipped(ALICE, address(nodleEdition), EDITION_ID, address(nodl), CREATOR, 3e18, 0); + vm.prank(ALICE); + tipping.tip(address(nodleEdition), ITipping.Standard.ERC1155, EDITION_ID, CREATOR, address(nodl), 3e18); + assertEq(nodl.balanceOf(CREATOR), 3e18); + // A holder of the edition is not its owner. + vm.prank(ALICE); + vm.expectRevert(notRecipient(address(nodleEdition), EDITION_ID, ALICE)); + tipping.tip(address(nodleEdition), ITipping.Standard.ERC1155, EDITION_ID, ALICE, address(nodl), 1e18); + // An id never minted on a supply-tracking edition is invalid. + vm.prank(ALICE); + vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidToken.selector, address(nodleEdition), 5)); + tipping.tip(address(nodleEdition), ITipping.Standard.ERC1155, 5, CREATOR, address(nodl), 1e18); + } + + function test_tip1155_ownableEditionPaysItsOwner() public { + assertTrue(tipping.isRecipient(address(ownable), ITipping.Standard.ERC1155, EDITION_ID, CREATOR)); + vm.prank(ALICE); + tipping.tip(address(ownable), ITipping.Standard.ERC1155, EDITION_ID, CREATOR, address(nodl), 1e18); + assertEq(nodl.balanceOf(CREATOR), 1e18); + vm.prank(ALICE); + vm.expectRevert(notRecipient(address(ownable), EDITION_ID, BOB)); + tipping.tip(address(ownable), ITipping.Standard.ERC1155, EDITION_ID, BOB, address(nodl), 1e18); + } - // No supply extension and no ERC-2981 at all: nothing to resolve either. + function test_tip_zeroRecipientIsNotARecipient() public { vm.prank(ALICE); - vm.expectRevert(abi.encodeWithSelector(ITipping.NoRecipient.selector, address(bare), 1)); - tipping.tip(address(bare), ITipping.Standard.ERC1155, 1, address(nodl), 1e18); + vm.expectRevert(notRecipient(address(post), POST_ID, address(0))); + tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, address(0), address(nodl), 1e18); + assertFalse(tipping.isRecipient(address(nodleEdition), ITipping.Standard.ERC1155, EDITION_ID, address(0))); } function test_tip1155_royaltyReceiverCannotTipItself() public { @@ -242,7 +327,7 @@ contract TippingTest is Test { vm.startPrank(CREATOR); nodl.approve(address(tipping), 1e18); vm.expectRevert(ITipping.SelfTip.selector); - tipping.tip(address(edition), ITipping.Standard.ERC1155, EDITION_ID, address(nodl), 1e18); + tipping.tip(address(edition), ITipping.Standard.ERC1155, EDITION_ID, CREATOR, address(nodl), 1e18); vm.stopPrank(); } @@ -251,20 +336,20 @@ contract TippingTest is Test { function test_tip_wrongStandardFailsToResolve() public { // ERC-1155 path on a plain ERC-721: no totalSupply, no royaltyInfo. vm.prank(ALICE); - vm.expectRevert(abi.encodeWithSelector(ITipping.NoRecipient.selector, address(post), POST_ID)); - tipping.tip(address(post), ITipping.Standard.ERC1155, POST_ID, address(nodl), 1e18); + vm.expectRevert(notRecipient(address(post), POST_ID, BOB)); + tipping.tip(address(post), ITipping.Standard.ERC1155, POST_ID, BOB, address(nodl), 1e18); // ERC-721 path on an ERC-1155: no ownerOf. vm.prank(ALICE); vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidToken.selector, address(edition), EDITION_ID)); - tipping.tip(address(edition), ITipping.Standard.ERC721, EDITION_ID, address(nodl), 1e18); + tipping.tip(address(edition), ITipping.Standard.ERC721, EDITION_ID, CREATOR, address(nodl), 1e18); } function test_tip_collectionMustBeAContract() public { vm.prank(ALICE); vm.expectRevert(abi.encodeWithSelector(ITipping.NotAContract.selector, address(0xD00D))); - tipping.tip(address(0xD00D), ITipping.Standard.ERC721, 1, address(nodl), 1e18); + tipping.tip(address(0xD00D), ITipping.Standard.ERC721, 1, BOB, address(nodl), 1e18); vm.expectRevert(abi.encodeWithSelector(ITipping.NotAContract.selector, address(0))); - tipping.recipientOf(address(0), ITipping.Standard.ERC721, 1); + tipping.isRecipient(address(0), ITipping.Standard.ERC721, 1, BOB); } function test_tip_lookupIsStaticAndCannotReenter() public { @@ -273,16 +358,16 @@ contract TippingTest is Test { // tipAccount inside it reverts, the try/catch turns that into InvalidToken. vm.prank(ALICE); vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidToken.selector, address(evil), 1)); - tipping.tip(address(evil), ITipping.Standard.ERC721, 1, address(nodl), 1e18); + tipping.tip(address(evil), ITipping.Standard.ERC721, 1, address(evil), address(nodl), 1e18); assertEq(nodl.transfers(), 0); } function test_tip_guards() public { vm.startPrank(ALICE); vm.expectRevert(ITipping.ZeroAddress.selector); - tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, address(0), 1e18); + tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, BOB, address(0), 1e18); vm.expectRevert(ITipping.ZeroAmount.selector); - tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, address(nodl), 0); + tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, BOB, address(nodl), 0); vm.stopPrank(); } @@ -291,12 +376,12 @@ contract TippingTest is Test { nodl.approve(address(tipping), 1e18); vm.prank(ALICE); vm.expectRevert(); - tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, address(nodl), 2e18); + tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, BOB, address(nodl), 2e18); vm.prank(ALICE); nodl.approve(address(tipping), type(uint256).max); vm.prank(ALICE); vm.expectRevert(); - tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, address(nodl), 1_001e18); + tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, BOB, address(nodl), 1_001e18); } // ───────── Account tips ───────── @@ -396,8 +481,8 @@ contract TippingTest is Test { nodl.approve(address(tipping), amount); vm.prank(tipper); - if (path % 3 == 0) tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, address(nodl), amount); - else if (path % 3 == 1) tipping.tip(address(edition), ITipping.Standard.ERC1155, EDITION_ID, address(nodl), amount); + if (path % 3 == 0) tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, BOB, address(nodl), amount); + else if (path % 3 == 1) tipping.tip(address(edition), ITipping.Standard.ERC1155, EDITION_ID, CREATOR, address(nodl), amount); else tipping.tipAccount(address(nodl), BOB, amount); uint256 n = nodl.transfers(); From e56bee73a4e15e9860d62f017244b0bedbbda906 Mon Sep 17 00:00:00 2001 From: douglasacost Date: Wed, 28 Oct 2026 22:43:18 -0400 Subject: [PATCH 13/18] feat(tipping): fees accrue in the contract; withdrawFees(token) sends them to the fee recipient Review point 3 (2026-10-28). The fee share of a tip is pulled into this contract instead of the fee recipient; anyone may call withdrawFees(token), which sends the contract's whole balance of that token to feeRecipient (so fee-on-transfer rounding and stray tokens are handled too). The allowance invariant is unchanged: transferFrom only from msg.sender. --- src/tipping/ITipping.sol | 5 +++++ src/tipping/Tipping.sol | 22 +++++++++++++++++++--- test/tipping/Tipping.t.sol | 36 ++++++++++++++++++++++++++++++++---- 3 files changed, 56 insertions(+), 7 deletions(-) diff --git a/src/tipping/ITipping.sol b/src/tipping/ITipping.sol index 5524fcc6..51a39bbb 100644 --- a/src/tipping/ITipping.sol +++ b/src/tipping/ITipping.sol @@ -30,6 +30,8 @@ interface ITipping { event AccountTipped(address indexed tipper, address indexed to, address token, uint256 amount, uint256 fee); event FeeUpdated(uint16 feeBps); event FeeRecipientUpdated(address indexed feeRecipient); + /// @notice Accrued fees in `token` were sent to the fee recipient. + event FeesWithdrawn(address indexed token, address indexed to, uint256 amount); error ZeroAddress(); error ZeroAmount(); @@ -53,6 +55,9 @@ interface ITipping { external view returns (bool); + /// @notice Send everything this contract holds in `token` (accrued fees) to the fee recipient. Anyone may call. + function withdrawFees(address token) external; + function feeBps() external view returns (uint16); function feeRecipient() external view returns (address); } diff --git a/src/tipping/Tipping.sol b/src/tipping/Tipping.sol index 7d9e91d5..180446d6 100644 --- a/src/tipping/Tipping.sol +++ b/src/tipping/Tipping.sol @@ -28,7 +28,8 @@ interface IOwnableLike { * @notice Immutable, agnostic tipping (nft-feed-indexer design §6.2, v2 of 2026-10-28). No proxy, * no upgrade path, no pause, no backend signature: an allowance granted to this address * can only ever be spent by the approver's own `tip`/`tipAccount` calls, because - * `transferFrom` is only called with `from == msg.sender`. The contract holds no funds. + * `transferFrom` is only called with `from == msg.sender`. The only balance the contract + * ever holds is accrued fees, which `withdrawFees` sends to the fee recipient. * * Post tips name their recipient (the feed knows who made or holds a post); the contract only * verifies the claim against the NFT: ERC-721 → `ownerOf(tokenId) == recipient`; ERC-1155 → @@ -38,6 +39,11 @@ interface IOwnableLike { * (STATICCALL) behind try/catch, so a hostile collection can only make the tip revert or burn * the tipper's own gas. Account tips name their recipient with no check. * + * Fees (review decision 2026-10-28): the fee share of a tip stays in this contract and is moved to + * `feeRecipient` by `withdrawFees(token)`, which anyone may call; the tipper never pays for the + * fee recipient's transfer, and fee-on-transfer or stray tokens are handled by sending the + * actual balance. + * * Roles: DEFAULT_ADMIN_ROLE (fee ≤ 10 %, fee recipient). */ contract Tipping is ITipping, AccessControl, ReentrancyGuard { @@ -129,7 +135,17 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard { if (to == msg.sender) revert SelfTip(); fee = (amount * feeBps) / BPS; IERC20(token).safeTransferFrom(msg.sender, to, amount - fee); - if (fee > 0) IERC20(token).safeTransferFrom(msg.sender, feeRecipient, fee); + if (fee > 0) IERC20(token).safeTransferFrom(msg.sender, address(this), fee); + } + + /// @inheritdoc ITipping + function withdrawFees(address token) external nonReentrant { + if (token == address(0)) revert ZeroAddress(); + uint256 amount = IERC20(token).balanceOf(address(this)); + if (amount == 0) revert ZeroAmount(); + address to = feeRecipient; + IERC20(token).safeTransfer(to, amount); + emit FeesWithdrawn(token, to, amount); } // ───────── Admin ───────── @@ -142,7 +158,7 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard { function setFeeRecipient(address recipient) external onlyRole(DEFAULT_ADMIN_ROLE) { if (recipient == address(0)) revert ZeroAddress(); - // No rescue path exists in an immutable contract: fees sent to this address are lost. + // Withdrawing to itself would be a no-op: fees could never leave the contract. if (recipient == address(this)) revert InvalidFeeRecipient(recipient); feeRecipient = recipient; emit FeeRecipientUpdated(recipient); diff --git a/test/tipping/Tipping.t.sol b/test/tipping/Tipping.t.sol index e53ccb81..7558d938 100644 --- a/test/tipping/Tipping.t.sol +++ b/test/tipping/Tipping.t.sol @@ -414,14 +414,14 @@ contract TippingTest is Test { vm.expectEmit(true, true, true, true); emit ITipping.FeeUpdated(250); tipping.setFee(250); - vm.prank(ADMIN); - tipping.setFeeRecipient(CREATOR); vm.expectEmit(true, true, true, true); emit ITipping.Tipped(ALICE, address(post), POST_ID, address(nodl), BOB, 100e18, 2.5e18); tipPost(ALICE, 100e18); assertEq(nodl.balanceOf(BOB), 97.5e18); - assertEq(nodl.balanceOf(CREATOR), 2.5e18); + // The fee accrues in the contract; the fee recipient is paid on withdraw, not per tip. + assertEq(nodl.balanceOf(address(tipping)), 2.5e18); + assertEq(nodl.balanceOf(ADMIN), 0); assertEq(nodl.transfers(), 2); vm.prank(ADMIN); @@ -432,13 +432,41 @@ contract TippingTest is Test { assertEq(tipping.feeBps(), 1000); } + function test_withdrawFees_anyoneSendsAccruedToFeeRecipient() public { + vm.prank(ADMIN); + tipping.setFee(1000); + vm.prank(ADMIN); + tipping.setFeeRecipient(CREATOR); + tipPost(ALICE, 50e18); + vm.prank(ALICE); + tipping.tipAccount(address(nodl), BOB, 10e18); + assertEq(nodl.balanceOf(address(tipping)), 6e18); + + vm.expectEmit(true, true, true, true); + emit ITipping.FeesWithdrawn(address(nodl), CREATOR, 6e18); + vm.prank(BOB); // permissionless + tipping.withdrawFees(address(nodl)); + assertEq(nodl.balanceOf(CREATOR), 6e18); + assertEq(nodl.balanceOf(address(tipping)), 0); + + // Nothing accrued: revert rather than emit a zero withdrawal. + vm.expectRevert(ITipping.ZeroAmount.selector); + tipping.withdrawFees(address(nodl)); + vm.expectRevert(ITipping.ZeroAddress.selector); + tipping.withdrawFees(address(0)); + // Stray tokens sent directly are recoverable the same way. + usdc.mint(address(tipping), 7e6); + tipping.withdrawFees(address(usdc)); + assertEq(usdc.balanceOf(CREATOR), 7e6); + } + function test_feeRoundsDownInFavourOfRecipient() public { vm.prank(ADMIN); tipping.setFee(1); vm.prank(ALICE); tipping.tipAccount(address(nodl), BOB, 9_999); assertEq(nodl.balanceOf(BOB), 9_999); - assertEq(nodl.balanceOf(ADMIN), 0); + assertEq(nodl.balanceOf(address(tipping)), 0); assertEq(nodl.transfers(), 1); } From f3399d64f892bcfd2b9c488bca32a8aa48e63597 Mon Sep 17 00:00:00 2001 From: douglasacost Date: Wed, 28 Oct 2026 23:29:54 -0400 Subject: [PATCH 14/18] docs(tipping): contract title and description for v2 --- src/tipping/ITipping.sol | 11 +++++----- src/tipping/Tipping.sol | 45 ++++++++++++++++++++++++---------------- 2 files changed, 32 insertions(+), 24 deletions(-) diff --git a/src/tipping/ITipping.sol b/src/tipping/ITipping.sol index 51a39bbb..c3b5f815 100644 --- a/src/tipping/ITipping.sol +++ b/src/tipping/ITipping.sol @@ -3,12 +3,11 @@ pragma solidity ^0.8.26; /** * @title ITipping - * @notice Agnostic tipping: any ERC-20, any NFT, any account. The caller names the recipient of - * a post tip (the feed knows it) and the contract verifies the claim against the NFT: - * ERC-721, the recipient must be `ownerOf(tokenId)`; ERC-1155, the recipient must hold the - * collection's `OWNER_ROLE` (Nodle collections), or be its Ownable `owner()`, or be its - * ERC-2981 royalty receiver for the id. Nothing is enumerated on-chain, only checked. - * No backend signature, no allowlist. The event surface is what the feed indexer consumes. + * @notice Interface of Nodle Tipping v2: tip an NFT post or an account with any ERC-20. + * A post tip names its recipient and the contract verifies the claim against the NFT + * (ERC-721 owner; ERC-1155 collection owner role, Ownable owner or ERC-2981 receiver). + * No backend signature, no allowlist, no pause. Keep the event surface stable: the + * Nodle feed indexer consumes it. */ interface ITipping { enum Standard { diff --git a/src/tipping/Tipping.sol b/src/tipping/Tipping.sol index 180446d6..43bfec7e 100644 --- a/src/tipping/Tipping.sol +++ b/src/tipping/Tipping.sol @@ -24,27 +24,36 @@ interface IOwnableLike { } /** - * @title Tipping - * @notice Immutable, agnostic tipping (nft-feed-indexer design §6.2, v2 of 2026-10-28). No proxy, - * no upgrade path, no pause, no backend signature: an allowance granted to this address - * can only ever be spent by the approver's own `tip`/`tipAccount` calls, because - * `transferFrom` is only called with `from == msg.sender`. The only balance the contract - * ever holds is accrued fees, which `withdrawFees` sends to the fee recipient. + * @title Nodle Tipping v2 + * @author Nodle + * @notice Lets anyone tip an NFT post or an account with any ERC-20, on zkSync Era. * - * Post tips name their recipient (the feed knows who made or holds a post); the contract only - * verifies the claim against the NFT: ERC-721 → `ownerOf(tokenId) == recipient`; ERC-1155 → - * the recipient holds the collection's `OWNER_ROLE` (Nodle collections grant it to the creator), - * or is its Ownable `owner()`, or its ERC-2981 royalty receiver for the id. Nothing can be - * enumerated from an ERC-1155, but a claim can be checked. The lookups are `view` calls - * (STATICCALL) behind try/catch, so a hostile collection can only make the tip revert or burn - * the tipper's own gas. Account tips name their recipient with no check. + * @dev How a post tip works + * The caller passes the collection, its standard (ERC-721 or ERC-1155), the token id, the + * recipient, the ERC-20 and the amount. The contract does not decide who gets paid; it + * checks that the caller's recipient is legitimate for that NFT: + * - ERC-721: `recipient` must be `ownerOf(tokenId)`. + * - ERC-1155: the id must exist (non-zero tracked supply, when the collection exposes + * `totalSupply(id)`) and `recipient` must hold the collection's `OWNER_ROLE` (Nodle + * user collections grant it to their creator), or be its Ownable `owner()`, or be its + * ERC-2981 royalty receiver for the id. + * Nothing is enumerated from the NFT, only verified, so any collection works without a + * registry or a backend signature. The checks are `view` calls (STATICCALL) behind + * try/catch: a hostile collection can only make the tip revert or burn the caller's gas. + * Account tips (`tipAccount`) name their recipient with no check. * - * Fees (review decision 2026-10-28): the fee share of a tip stays in this contract and is moved to - * `feeRecipient` by `withdrawFees(token)`, which anyone may call; the tipper never pays for the - * fee recipient's transfer, and fee-on-transfer or stray tokens are handled by sending the - * actual balance. + * Money + * Tokens move with `transferFrom(msg.sender, …)` only: an allowance granted to this + * contract can be spent solely by the approver's own calls. The optional protocol fee + * (at most 10 %, 0 at launch) stays in the contract and `withdrawFees(token)`, callable by + * anyone, sends the contract's whole balance of that token to the fee recipient. Fees are + * the only balance the contract ever holds; a token sent here by mistake is recovered the + * same way. Self-tips and zero amounts revert. * - * Roles: DEFAULT_ADMIN_ROLE (fee ≤ 10 %, fee recipient). + * Governance + * Immutable: no proxy, no upgrade, no pause. `DEFAULT_ADMIN_ROLE` (a multisig) can only + * change the fee and the fee recipient. Events `Tipped`, `AccountTipped`, `FeeUpdated`, + * `FeeRecipientUpdated` and `FeesWithdrawn` are the surface the Nodle feed indexer reads. */ contract Tipping is ITipping, AccessControl, ReentrancyGuard { using SafeERC20 for IERC20; From 779c63a992da1fb29f32112dd0013f5944ce33a6 Mon Sep 17 00:00:00 2001 From: douglasacost Date: Thu, 29 Oct 2026 00:17:09 -0400 Subject: [PATCH 15/18] refactor(tipping): review renames: NFTStandard, isValidTipRecipient public (internal check folded in) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses aliXsed's review: enum Standard → NFTStandard; isRecipient → isValidTipRecipient, public, with the former internal _isRecipient body inlined. tipAccount stays for now (owner decision 2026-10-29). ABI change (view function name only; tip() unchanged): redeploy before the apps integrate v2. --- src/tipping/ITipping.sol | 14 +++++-- src/tipping/Tipping.sol | 30 +++++++------ test/tipping/Tipping.t.sol | 86 +++++++++++++++++++++----------------- 3 files changed, 71 insertions(+), 59 deletions(-) diff --git a/src/tipping/ITipping.sol b/src/tipping/ITipping.sol index c3b5f815..cd88ee01 100644 --- a/src/tipping/ITipping.sol +++ b/src/tipping/ITipping.sol @@ -10,7 +10,7 @@ pragma solidity ^0.8.26; * Nodle feed indexer consumes it. */ interface ITipping { - enum Standard { + enum NFTStandard { ERC721, ERC1155 } @@ -44,13 +44,19 @@ interface ITipping { error InvalidFeeRecipient(address recipient); /// @notice Tip the NFT `tokenId` of `collection`: `recipient` is verified against the NFT, then paid `amount` of `token`. - function tip(address collection, Standard standard, uint256 tokenId, address recipient, address token, uint256 amount) - external; + function tip( + address collection, + NFTStandard standard, + uint256 tokenId, + address recipient, + address token, + uint256 amount + ) external; /// @notice Tip an account the caller names. function tipAccount(address token, address to, uint256 amount) external; /// @notice Whether `tip` would accept `recipient` for this NFT; reverts for a non-contract or an invalid token, like `tip`. - function isRecipient(address collection, Standard standard, uint256 tokenId, address recipient) + function isValidTipRecipient(address collection, NFTStandard standard, uint256 tokenId, address recipient) external view returns (bool); diff --git a/src/tipping/Tipping.sol b/src/tipping/Tipping.sol index 43bfec7e..62c1f879 100644 --- a/src/tipping/Tipping.sol +++ b/src/tipping/Tipping.sol @@ -77,11 +77,17 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard { // ───────── Tipping ───────── /// @inheritdoc ITipping - function tip(address collection, Standard standard, uint256 tokenId, address recipient, address token, uint256 amount) - external - nonReentrant - { - if (!_isRecipient(collection, standard, tokenId, recipient)) revert NotRecipient(collection, tokenId, recipient); + function tip( + address collection, + NFTStandard standard, + uint256 tokenId, + address recipient, + address token, + uint256 amount + ) external nonReentrant { + if (!isValidTipRecipient(collection, standard, tokenId, recipient)) { + revert NotRecipient(collection, tokenId, recipient); + } uint256 fee = _pay(token, recipient, amount); emit Tipped(msg.sender, collection, tokenId, token, recipient, amount, fee); } @@ -93,26 +99,18 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard { } /// @inheritdoc ITipping - function isRecipient(address collection, Standard standard, uint256 tokenId, address recipient) - external - view - returns (bool) - { - return _isRecipient(collection, standard, tokenId, recipient); - } - /// @dev ERC-721: `recipient` must be the current owner. ERC-1155: the id must exist (tracked /// supply, when exposed, must be non-zero) and `recipient` must hold OWNER_ROLE, be the /// Ownable owner, or be the ERC-2981 receiver for the id. Reverts for non-contracts and /// invalid tokens; returns false for a wrong recipient. - function _isRecipient(address collection, Standard standard, uint256 tokenId, address recipient) - internal + function isValidTipRecipient(address collection, NFTStandard standard, uint256 tokenId, address recipient) + public view returns (bool) { if (collection.code.length == 0) revert NotAContract(collection); if (recipient == address(0)) return false; - if (standard == Standard.ERC721) { + if (standard == NFTStandard.ERC721) { try IERC721(collection).ownerOf(tokenId) returns (address owner) { return owner == recipient; } catch { diff --git a/test/tipping/Tipping.t.sol b/test/tipping/Tipping.t.sol index 7558d938..e5cfda98 100644 --- a/test/tipping/Tipping.t.sol +++ b/test/tipping/Tipping.t.sol @@ -168,7 +168,7 @@ contract TippingTest is Test { function tipPost(address who, uint256 amount) internal { address owner = post.ownerOf(POST_ID); // before the prank: an external call would consume it vm.prank(who); - tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, owner, address(nodl), amount); + tipping.tip(address(post), ITipping.NFTStandard.ERC721, POST_ID, owner, address(nodl), amount); } function notRecipient(address collection, uint256 id, address who) internal pure returns (bytes memory) { @@ -210,26 +210,26 @@ contract TippingTest is Test { function test_tip721_followsTransfers() public { vm.prank(BOB); post.transferFrom(BOB, CREATOR, POST_ID); - assertTrue(tipping.isRecipient(address(post), ITipping.Standard.ERC721, POST_ID, CREATOR)); - assertFalse(tipping.isRecipient(address(post), ITipping.Standard.ERC721, POST_ID, BOB)); + assertTrue(tipping.isValidTipRecipient(address(post), ITipping.NFTStandard.ERC721, POST_ID, CREATOR)); + assertFalse(tipping.isValidTipRecipient(address(post), ITipping.NFTStandard.ERC721, POST_ID, BOB)); tipPost(ALICE, 1e18); assertEq(nodl.balanceOf(CREATOR), 1e18); assertEq(nodl.balanceOf(BOB), 0); // The previous owner is no longer a valid recipient. vm.prank(ALICE); vm.expectRevert(notRecipient(address(post), POST_ID, BOB)); - tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, BOB, address(nodl), 1e18); + tipping.tip(address(post), ITipping.NFTStandard.ERC721, POST_ID, BOB, address(nodl), 1e18); } function test_tip721_neverMintedOrBurnedIsInvalid() public { vm.prank(ALICE); vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidToken.selector, address(post), 99)); - tipping.tip(address(post), ITipping.Standard.ERC721, 99, BOB, address(nodl), 1e18); + tipping.tip(address(post), ITipping.NFTStandard.ERC721, 99, BOB, address(nodl), 1e18); post.burn(POST_ID); vm.prank(ALICE); vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidToken.selector, address(post), POST_ID)); - tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, BOB, address(nodl), 1e18); + tipping.tip(address(post), ITipping.NFTStandard.ERC721, POST_ID, BOB, address(nodl), 1e18); } function test_tip721_ownerCannotTipOwnPost() public { @@ -238,12 +238,12 @@ contract TippingTest is Test { nodl.approve(address(tipping), 1e18); vm.prank(BOB); vm.expectRevert(ITipping.SelfTip.selector); - tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, BOB, address(nodl), 1e18); + tipping.tip(address(post), ITipping.NFTStandard.ERC721, POST_ID, BOB, address(nodl), 1e18); } function test_tip_anyErc20() public { vm.prank(ALICE); - tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, BOB, address(usdc), 3e6); + tipping.tip(address(post), ITipping.NFTStandard.ERC721, POST_ID, BOB, address(usdc), 3e6); assertEq(usdc.balanceOf(BOB), 3e6); } @@ -253,73 +253,77 @@ contract TippingTest is Test { vm.expectEmit(true, true, true, true); emit ITipping.Tipped(ALICE, address(edition), EDITION_ID, address(nodl), CREATOR, 2e18, 0); vm.prank(ALICE); - tipping.tip(address(edition), ITipping.Standard.ERC1155, EDITION_ID, CREATOR, address(nodl), 2e18); + tipping.tip(address(edition), ITipping.NFTStandard.ERC1155, EDITION_ID, CREATOR, address(nodl), 2e18); assertEq(nodl.balanceOf(CREATOR), 2e18); - assertTrue(tipping.isRecipient(address(edition), ITipping.Standard.ERC1155, EDITION_ID, CREATOR)); - assertFalse(tipping.isRecipient(address(edition), ITipping.Standard.ERC1155, EDITION_ID, ALICE)); + assertTrue(tipping.isValidTipRecipient(address(edition), ITipping.NFTStandard.ERC1155, EDITION_ID, CREATOR)); + assertFalse(tipping.isValidTipRecipient(address(edition), ITipping.NFTStandard.ERC1155, EDITION_ID, ALICE)); } function test_tip1155_zeroSupplyIsInvalid() public { vm.prank(ALICE); vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidToken.selector, address(edition), 42)); - tipping.tip(address(edition), ITipping.Standard.ERC1155, 42, CREATOR, address(nodl), 1e18); + tipping.tip(address(edition), ITipping.NFTStandard.ERC1155, 42, CREATOR, address(nodl), 1e18); edition.burn(ALICE, EDITION_ID, 100); vm.prank(ALICE); vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidToken.selector, address(edition), EDITION_ID)); - tipping.tip(address(edition), ITipping.Standard.ERC1155, EDITION_ID, CREATOR, address(nodl), 1e18); + tipping.tip(address(edition), ITipping.NFTStandard.ERC1155, EDITION_ID, CREATOR, address(nodl), 1e18); } function test_tip1155_royaltyReceiverIsTheOnlyProofOnThisEdition() public { // Someone else than the royalty receiver is refused. vm.prank(ALICE); vm.expectRevert(notRecipient(address(edition), EDITION_ID, BOB)); - tipping.tip(address(edition), ITipping.Standard.ERC1155, EDITION_ID, BOB, address(nodl), 1e18); + tipping.tip(address(edition), ITipping.NFTStandard.ERC1155, EDITION_ID, BOB, address(nodl), 1e18); // With the royalty removed nobody can be verified any more. edition.setRoyalty(address(0), 0); vm.prank(ALICE); vm.expectRevert(notRecipient(address(edition), EDITION_ID, CREATOR)); - tipping.tip(address(edition), ITipping.Standard.ERC1155, EDITION_ID, CREATOR, address(nodl), 1e18); + tipping.tip(address(edition), ITipping.NFTStandard.ERC1155, EDITION_ID, CREATOR, address(nodl), 1e18); // No supply extension, no roles, no owner, no ERC-2981: nothing to verify against. vm.prank(ALICE); vm.expectRevert(notRecipient(address(bare), 1, BOB)); - tipping.tip(address(bare), ITipping.Standard.ERC1155, 1, BOB, address(nodl), 1e18); + tipping.tip(address(bare), ITipping.NFTStandard.ERC1155, 1, BOB, address(nodl), 1e18); } function test_tip1155_nodleEditionPaysItsOwnerRoleHolder() public { // Nodle collections: no royalty, but the creator holds OWNER_ROLE. - assertTrue(tipping.isRecipient(address(nodleEdition), ITipping.Standard.ERC1155, EDITION_ID, CREATOR)); - assertFalse(tipping.isRecipient(address(nodleEdition), ITipping.Standard.ERC1155, EDITION_ID, ALICE)); + assertTrue( + tipping.isValidTipRecipient(address(nodleEdition), ITipping.NFTStandard.ERC1155, EDITION_ID, CREATOR) + ); + assertFalse(tipping.isValidTipRecipient(address(nodleEdition), ITipping.NFTStandard.ERC1155, EDITION_ID, ALICE)); vm.expectEmit(true, true, true, true); emit ITipping.Tipped(ALICE, address(nodleEdition), EDITION_ID, address(nodl), CREATOR, 3e18, 0); vm.prank(ALICE); - tipping.tip(address(nodleEdition), ITipping.Standard.ERC1155, EDITION_ID, CREATOR, address(nodl), 3e18); + tipping.tip(address(nodleEdition), ITipping.NFTStandard.ERC1155, EDITION_ID, CREATOR, address(nodl), 3e18); assertEq(nodl.balanceOf(CREATOR), 3e18); // A holder of the edition is not its owner. vm.prank(ALICE); vm.expectRevert(notRecipient(address(nodleEdition), EDITION_ID, ALICE)); - tipping.tip(address(nodleEdition), ITipping.Standard.ERC1155, EDITION_ID, ALICE, address(nodl), 1e18); + tipping.tip(address(nodleEdition), ITipping.NFTStandard.ERC1155, EDITION_ID, ALICE, address(nodl), 1e18); // An id never minted on a supply-tracking edition is invalid. vm.prank(ALICE); vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidToken.selector, address(nodleEdition), 5)); - tipping.tip(address(nodleEdition), ITipping.Standard.ERC1155, 5, CREATOR, address(nodl), 1e18); + tipping.tip(address(nodleEdition), ITipping.NFTStandard.ERC1155, 5, CREATOR, address(nodl), 1e18); } function test_tip1155_ownableEditionPaysItsOwner() public { - assertTrue(tipping.isRecipient(address(ownable), ITipping.Standard.ERC1155, EDITION_ID, CREATOR)); + assertTrue(tipping.isValidTipRecipient(address(ownable), ITipping.NFTStandard.ERC1155, EDITION_ID, CREATOR)); vm.prank(ALICE); - tipping.tip(address(ownable), ITipping.Standard.ERC1155, EDITION_ID, CREATOR, address(nodl), 1e18); + tipping.tip(address(ownable), ITipping.NFTStandard.ERC1155, EDITION_ID, CREATOR, address(nodl), 1e18); assertEq(nodl.balanceOf(CREATOR), 1e18); vm.prank(ALICE); vm.expectRevert(notRecipient(address(ownable), EDITION_ID, BOB)); - tipping.tip(address(ownable), ITipping.Standard.ERC1155, EDITION_ID, BOB, address(nodl), 1e18); + tipping.tip(address(ownable), ITipping.NFTStandard.ERC1155, EDITION_ID, BOB, address(nodl), 1e18); } function test_tip_zeroRecipientIsNotARecipient() public { vm.prank(ALICE); vm.expectRevert(notRecipient(address(post), POST_ID, address(0))); - tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, address(0), address(nodl), 1e18); - assertFalse(tipping.isRecipient(address(nodleEdition), ITipping.Standard.ERC1155, EDITION_ID, address(0))); + tipping.tip(address(post), ITipping.NFTStandard.ERC721, POST_ID, address(0), address(nodl), 1e18); + assertFalse( + tipping.isValidTipRecipient(address(nodleEdition), ITipping.NFTStandard.ERC1155, EDITION_ID, address(0)) + ); } function test_tip1155_royaltyReceiverCannotTipItself() public { @@ -327,7 +331,7 @@ contract TippingTest is Test { vm.startPrank(CREATOR); nodl.approve(address(tipping), 1e18); vm.expectRevert(ITipping.SelfTip.selector); - tipping.tip(address(edition), ITipping.Standard.ERC1155, EDITION_ID, CREATOR, address(nodl), 1e18); + tipping.tip(address(edition), ITipping.NFTStandard.ERC1155, EDITION_ID, CREATOR, address(nodl), 1e18); vm.stopPrank(); } @@ -337,19 +341,19 @@ contract TippingTest is Test { // ERC-1155 path on a plain ERC-721: no totalSupply, no royaltyInfo. vm.prank(ALICE); vm.expectRevert(notRecipient(address(post), POST_ID, BOB)); - tipping.tip(address(post), ITipping.Standard.ERC1155, POST_ID, BOB, address(nodl), 1e18); + tipping.tip(address(post), ITipping.NFTStandard.ERC1155, POST_ID, BOB, address(nodl), 1e18); // ERC-721 path on an ERC-1155: no ownerOf. vm.prank(ALICE); vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidToken.selector, address(edition), EDITION_ID)); - tipping.tip(address(edition), ITipping.Standard.ERC721, EDITION_ID, CREATOR, address(nodl), 1e18); + tipping.tip(address(edition), ITipping.NFTStandard.ERC721, EDITION_ID, CREATOR, address(nodl), 1e18); } function test_tip_collectionMustBeAContract() public { vm.prank(ALICE); vm.expectRevert(abi.encodeWithSelector(ITipping.NotAContract.selector, address(0xD00D))); - tipping.tip(address(0xD00D), ITipping.Standard.ERC721, 1, BOB, address(nodl), 1e18); + tipping.tip(address(0xD00D), ITipping.NFTStandard.ERC721, 1, BOB, address(nodl), 1e18); vm.expectRevert(abi.encodeWithSelector(ITipping.NotAContract.selector, address(0))); - tipping.isRecipient(address(0), ITipping.Standard.ERC721, 1, BOB); + tipping.isValidTipRecipient(address(0), ITipping.NFTStandard.ERC721, 1, BOB); } function test_tip_lookupIsStaticAndCannotReenter() public { @@ -358,16 +362,16 @@ contract TippingTest is Test { // tipAccount inside it reverts, the try/catch turns that into InvalidToken. vm.prank(ALICE); vm.expectRevert(abi.encodeWithSelector(ITipping.InvalidToken.selector, address(evil), 1)); - tipping.tip(address(evil), ITipping.Standard.ERC721, 1, address(evil), address(nodl), 1e18); + tipping.tip(address(evil), ITipping.NFTStandard.ERC721, 1, address(evil), address(nodl), 1e18); assertEq(nodl.transfers(), 0); } function test_tip_guards() public { vm.startPrank(ALICE); vm.expectRevert(ITipping.ZeroAddress.selector); - tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, BOB, address(0), 1e18); + tipping.tip(address(post), ITipping.NFTStandard.ERC721, POST_ID, BOB, address(0), 1e18); vm.expectRevert(ITipping.ZeroAmount.selector); - tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, BOB, address(nodl), 0); + tipping.tip(address(post), ITipping.NFTStandard.ERC721, POST_ID, BOB, address(nodl), 0); vm.stopPrank(); } @@ -376,12 +380,12 @@ contract TippingTest is Test { nodl.approve(address(tipping), 1e18); vm.prank(ALICE); vm.expectRevert(); - tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, BOB, address(nodl), 2e18); + tipping.tip(address(post), ITipping.NFTStandard.ERC721, POST_ID, BOB, address(nodl), 2e18); vm.prank(ALICE); nodl.approve(address(tipping), type(uint256).max); vm.prank(ALICE); vm.expectRevert(); - tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, BOB, address(nodl), 1_001e18); + tipping.tip(address(post), ITipping.NFTStandard.ERC721, POST_ID, BOB, address(nodl), 1_001e18); } // ───────── Account tips ───────── @@ -509,9 +513,13 @@ contract TippingTest is Test { nodl.approve(address(tipping), amount); vm.prank(tipper); - if (path % 3 == 0) tipping.tip(address(post), ITipping.Standard.ERC721, POST_ID, BOB, address(nodl), amount); - else if (path % 3 == 1) tipping.tip(address(edition), ITipping.Standard.ERC1155, EDITION_ID, CREATOR, address(nodl), amount); - else tipping.tipAccount(address(nodl), BOB, amount); + if (path % 3 == 0) { + tipping.tip(address(post), ITipping.NFTStandard.ERC721, POST_ID, BOB, address(nodl), amount); + } else if (path % 3 == 1) { + tipping.tip(address(edition), ITipping.NFTStandard.ERC1155, EDITION_ID, CREATOR, address(nodl), amount); + } else { + tipping.tipAccount(address(nodl), BOB, amount); + } uint256 n = nodl.transfers(); assertTrue(n == 1 || n == 2); From 73a6f937ecef02eefe7d959fbecc92b99f01d720 Mon Sep 17 00:00:00 2001 From: douglasacost Date: Thu, 29 Oct 2026 00:17:57 -0400 Subject: [PATCH 16/18] =?UTF-8?q?refactor(tipping):=20=5Fpay=20=E2=86=92?= =?UTF-8?q?=20=5FtransferTipWithFee;=20fuzz=20asserts=20the=20balance=20de?= =?UTF-8?q?lta?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review rename. The invariant fuzz asserted a zero balance after the tip, which fails when the fuzzed tipper is ALICE (funded in setUp); it now asserts before - amount. --- src/tipping/Tipping.sol | 6 +++--- test/tipping/Tipping.t.sol | 3 ++- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/tipping/Tipping.sol b/src/tipping/Tipping.sol index 62c1f879..c0858c87 100644 --- a/src/tipping/Tipping.sol +++ b/src/tipping/Tipping.sol @@ -88,13 +88,13 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard { if (!isValidTipRecipient(collection, standard, tokenId, recipient)) { revert NotRecipient(collection, tokenId, recipient); } - uint256 fee = _pay(token, recipient, amount); + uint256 fee = _transferTipWithFee(token, recipient, amount); emit Tipped(msg.sender, collection, tokenId, token, recipient, amount, fee); } /// @inheritdoc ITipping function tipAccount(address token, address to, uint256 amount) external nonReentrant { - uint256 fee = _pay(token, to, amount); + uint256 fee = _transferTipWithFee(token, to, amount); emit AccountTipped(msg.sender, to, token, amount, fee); } @@ -136,7 +136,7 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard { /// @dev Shared guards and transfers. Only ever pulls from msg.sender: the property the /// immutability argument rests on. Returns the fee taken. - function _pay(address token, address to, uint256 amount) internal returns (uint256 fee) { + function _transferTipWithFee(address token, address to, uint256 amount) internal returns (uint256 fee) { if (token == address(0) || to == address(0)) revert ZeroAddress(); if (amount == 0) revert ZeroAmount(); if (to == msg.sender) revert SelfTip(); diff --git a/test/tipping/Tipping.t.sol b/test/tipping/Tipping.t.sol index e5cfda98..e72534cd 100644 --- a/test/tipping/Tipping.t.sol +++ b/test/tipping/Tipping.t.sol @@ -509,6 +509,7 @@ contract TippingTest is Test { vm.prank(ADMIN); tipping.setFee(bps); nodl.mint(tipper, amount); + uint256 before = nodl.balanceOf(tipper); // ALICE already holds a balance from setUp vm.prank(tipper); nodl.approve(address(tipping), amount); @@ -529,6 +530,6 @@ contract TippingTest is Test { total += nodl.amounts(i); } assertEq(total, amount); - assertEq(nodl.balanceOf(tipper), 0); + assertEq(nodl.balanceOf(tipper), before - amount); } } From 4eabf23c833ee23bf42114c6748dea2e2ff0ed0d Mon Sep 17 00:00:00 2001 From: douglasacost Date: Thu, 29 Oct 2026 00:42:55 -0400 Subject: [PATCH 17/18] fix(tipping): review fixes from Copilot - isValidTipRecipient: the ERC-1155 proofs apply only to collections that declare ERC-1155 support (ERC-165); a role-bearing ERC-721 passed as ERC-1155 no longer skips ownerOf (regression test with a Nodle-style ERC-721). - ops/deploy_tipping_zksync.sh: the second argument must be exactly --broadcast or omitted, so the mainnet confirmation guard and the broadcast flag cannot disagree. - ops/verify_zksync_contracts.py: Tipping in CONTRACT_SOURCE_MAP and DeployTippingZkSync in BROADCAST_CONTRACT_SEQUENCE; remappings are rewritten per import statement, including statements that span lines (UserCollection*.sol). --- ops/deploy_tipping_zksync.sh | 4 ++++ ops/verify_zksync_contracts.py | 34 ++++++++++++++++++---------------- src/tipping/Tipping.sol | 15 +++++++++++++-- test/tipping/Tipping.t.sol | 32 ++++++++++++++++++++++++++++++++ 4 files changed, 67 insertions(+), 18 deletions(-) diff --git a/ops/deploy_tipping_zksync.sh b/ops/deploy_tipping_zksync.sh index ca8bae62..a7810007 100755 --- a/ops/deploy_tipping_zksync.sh +++ b/ops/deploy_tipping_zksync.sh @@ -15,6 +15,10 @@ set -euo pipefail cd "$(dirname "$0")/.." NETWORK="${1:-}"; BROADCAST="${2:-}" +case "$BROADCAST" in + ""|--broadcast) ;; + *) echo "usage: $0 [--broadcast] (second argument must be exactly --broadcast or omitted)"; exit 1 ;; +esac case "$NETWORK" in testnet) RPC_URL="${L2_RPC:-https://sepolia.era.zksync.dev}" ;; mainnet) RPC_URL="${L2_RPC:-https://mainnet.era.zksync.io}" ;; diff --git a/ops/verify_zksync_contracts.py b/ops/verify_zksync_contracts.py index 43204640..ec07e1a7 100755 --- a/ops/verify_zksync_contracts.py +++ b/ops/verify_zksync_contracts.py @@ -85,6 +85,7 @@ "FleetIdentityUpgradeable": "src/swarms/FleetIdentityUpgradeable.sol:FleetIdentityUpgradeable", "SwarmRegistryUniversalUpgradeable": "src/swarms/SwarmRegistryUniversalUpgradeable.sol:SwarmRegistryUniversalUpgradeable", "ERC1967Proxy": "lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Proxy.sol:ERC1967Proxy", + "Tipping": "src/tipping/Tipping.sol:Tipping", "BondTreasuryPaymaster": "src/paymasters/BondTreasuryPaymaster.sol:BondTreasuryPaymaster", "CollectionFactory": "src/collections/CollectionFactory.sol:CollectionFactory", "UserCollection721": "src/collections/UserCollection721.sol:UserCollection721", @@ -97,6 +98,7 @@ # with unnamed `additionalContracts`. For those scripts, recover the deployed # contract type by the deterministic deployment order inside the script. BROADCAST_CONTRACT_SEQUENCE = { + "DeployTippingZkSync.s.sol": ["Tipping"], "DeployEnvelopeZkSync.s.sol": [ "EnvelopeLinks", "EnvelopePaymaster", @@ -183,24 +185,24 @@ def apply_remappings(std_json: dict) -> int: pairs.append((prefix, target)) pairs.sort(key=lambda x: -len(x[0])) source_keys = set(std_json["sources"].keys()) - pattern = re.compile(r'(import\s+.*?["\'])([^"\'.][^"\']*)(["\'].*)') + # Whole-statement match: imports may span lines (`import {A, B} from\n "@openzeppelin/..."`). + pattern = re.compile(r'(\bimport\b[^;]*?["\'])([^"\'.][^"\']*)(["\'])', re.S) changed = 0 + + def rewrite(m: "re.Match[str]") -> str: + nonlocal changed + prefix, path, quote = m.groups() + for rp, target in pairs: + if path.startswith(rp): + new_path = target + path[len(rp):] + if new_path in source_keys: + changed += 1 + return prefix + new_path + quote + break + return m.group(0) + for src_key in list(std_json["sources"].keys()): - lines = std_json["sources"][src_key]["content"].split("\n") - out = [] - for line in lines: - m = pattern.match(line) - if m: - prefix, path, suffix = m.groups() - for rp, target in pairs: - if path.startswith(rp): - new_path = target + path[len(rp):] - if new_path in source_keys: - line = prefix + new_path + suffix - changed += 1 - break - out.append(line) - std_json["sources"][src_key]["content"] = "\n".join(out) + std_json["sources"][src_key]["content"] = pattern.sub(rewrite, std_json["sources"][src_key]["content"]) return changed diff --git a/src/tipping/Tipping.sol b/src/tipping/Tipping.sol index c0858c87..86b3ac44 100644 --- a/src/tipping/Tipping.sol +++ b/src/tipping/Tipping.sol @@ -7,6 +7,8 @@ import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import {IERC2981} from "@openzeppelin/contracts/interfaces/IERC2981.sol"; +import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; +import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import {ITipping} from "./ITipping.sol"; @@ -101,8 +103,9 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard { /// @inheritdoc ITipping /// @dev ERC-721: `recipient` must be the current owner. ERC-1155: the id must exist (tracked /// supply, when exposed, must be non-zero) and `recipient` must hold OWNER_ROLE, be the - /// Ownable owner, or be the ERC-2981 receiver for the id. Reverts for non-contracts and - /// invalid tokens; returns false for a wrong recipient. + /// Ownable owner, or be the ERC-2981 receiver for the id; the collection must declare + /// ERC-1155 support (ERC-165). Reverts for non-contracts and invalid tokens; returns false + /// for a wrong recipient or a wrong standard. function isValidTipRecipient(address collection, NFTStandard standard, uint256 tokenId, address recipient) public view @@ -117,6 +120,14 @@ contract Tipping is ITipping, AccessControl, ReentrancyGuard { revert InvalidToken(collection, tokenId); } } + // The ERC-1155 proofs (role, owner, royalty) say nothing about a token id, so they only + // apply to a collection that declares itself ERC-1155. Otherwise an ERC-721 with an + // OWNER_ROLE passed as "ERC-1155" would skip ownerOf and pay the creator for any id. + try IERC165(collection).supportsInterface(type(IERC1155).interfaceId) returns (bool is1155) { + if (!is1155) return false; + } catch { + return false; + } try IERC1155SupplyLike(collection).totalSupply(tokenId) returns (uint256 supply) { if (supply == 0) revert InvalidToken(collection, tokenId); } catch { diff --git a/test/tipping/Tipping.t.sol b/test/tipping/Tipping.t.sol index e72534cd..3c1089df 100644 --- a/test/tipping/Tipping.t.sol +++ b/test/tipping/Tipping.t.sol @@ -89,6 +89,23 @@ contract NodleEdition1155 is ERC1155Supply, AccessControl { } } +/// @dev A Nodle-style ERC-721 collection: OWNER_ROLE held by the creator (like UserCollection721). +contract NodleCollection721 is ERC721, AccessControl { + bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); + + constructor(address owner_) ERC721("Nodle721", "N721") { + _grantRole(OWNER_ROLE, owner_); + } + + function mint(address to, uint256 id) external { + _mint(to, id); + } + + function supportsInterface(bytes4 id) public view override(ERC721, AccessControl) returns (bool) { + return super.supportsInterface(id); + } +} + /// @dev A third-party Ownable edition: no roles, no royalty, no supply tracking. contract Ownable1155 is ERC1155, Ownable { constructor(address owner_) ERC1155("ipfs://o") Ownable(owner_) {} @@ -337,6 +354,21 @@ contract TippingTest is Test { // ───────── Resolution guards ───────── + function test_tip_erc721WithOwnerRolePassedAs1155IsRefused() public { + // Regression (Copilot review): a role-bearing ERC-721 declared as ERC-1155 must not skip + // ownerOf and pay the creator for a transferred, burned or never-minted id. + NodleCollection721 col = new NodleCollection721(CREATOR); + col.mint(BOB, 1); + assertFalse(tipping.isValidTipRecipient(address(col), ITipping.NFTStandard.ERC1155, 1, CREATOR)); + assertFalse(tipping.isValidTipRecipient(address(col), ITipping.NFTStandard.ERC1155, 99, CREATOR)); + vm.prank(ALICE); + vm.expectRevert(notRecipient(address(col), 99, CREATOR)); + tipping.tip(address(col), ITipping.NFTStandard.ERC1155, 99, CREATOR, address(nodl), 1e18); + // Declared correctly it pays the owner and refuses the creator. + assertTrue(tipping.isValidTipRecipient(address(col), ITipping.NFTStandard.ERC721, 1, BOB)); + assertFalse(tipping.isValidTipRecipient(address(col), ITipping.NFTStandard.ERC721, 1, CREATOR)); + } + function test_tip_wrongStandardFailsToResolve() public { // ERC-1155 path on a plain ERC-721: no totalSupply, no royaltyInfo. vm.prank(ALICE); From 0a7868364a5f8cb1d510c78c7e28f0cb42fa3b29 Mon Sep 17 00:00:00 2001 From: douglasacost Date: Thu, 29 Oct 2026 01:16:06 -0400 Subject: [PATCH 18/18] test(tipping): cover the ERC-165 refusal and the no-proof fallthrough (coverage gate) --- test/tipping/Tipping.t.sol | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/test/tipping/Tipping.t.sol b/test/tipping/Tipping.t.sol index 3c1089df..39d2fdc2 100644 --- a/test/tipping/Tipping.t.sol +++ b/test/tipping/Tipping.t.sol @@ -369,6 +369,22 @@ contract TippingTest is Test { assertFalse(tipping.isValidTipRecipient(address(col), ITipping.NFTStandard.ERC721, 1, CREATOR)); } + function test_tip1155_requiresErc165() public { + // A contract with no supportsInterface at all (here: an ERC-20) declared as ERC-1155 is refused + // before any proof is consulted (the ERC-165 probe reverts → false). + assertFalse(tipping.isValidTipRecipient(address(usdc), ITipping.NFTStandard.ERC1155, 1, BOB)); + vm.prank(ALICE); + vm.expectRevert(notRecipient(address(usdc), 1, BOB)); + tipping.tip(address(usdc), ITipping.NFTStandard.ERC1155, 1, BOB, address(nodl), 1e18); + } + + function test_tip1155_noProofMatchesIsFalse() public { + // Genuine ERC-1155, every proof consulted, none names BOB: role (none), owner (CREATOR), royalty (none). + assertFalse(tipping.isValidTipRecipient(address(ownable), ITipping.NFTStandard.ERC1155, EDITION_ID, BOB)); + // Genuine ERC-1155 with a royalty receiver that is not BOB. + assertFalse(tipping.isValidTipRecipient(address(edition), ITipping.NFTStandard.ERC1155, EDITION_ID, BOB)); + } + function test_tip_wrongStandardFailsToResolve() public { // ERC-1155 path on a plain ERC-721: no totalSupply, no royaltyInfo. vm.prank(ALICE);