From 9b12737d431e3b3423c58e2dbb87a3c9d3042a02 Mon Sep 17 00:00:00 2001 From: Ryan Ghods Date: Tue, 17 Nov 2026 10:58:13 -0800 Subject: [PATCH 1/8] Add an agent NFT extension with ERC-8048 onchain metadata (#212) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds `ERC721SeaDropAgents`, an extension for collections whose tokens are AI agents, modeled on what MUSEGOD's [Muses contract](https://robin.etherscan.io/address/0x13ea3072b7215d4c9c2ec4f498a08c5825129836#code) added to `ERC721SeaDrop` on Robinhood Chain. The ERC-8048 code is a separate module in `src/lib`, so other token contracts can reuse it. ## Agent registration `registerAgents(firstTokenId, lastTokenId, prefix, suffix)` registers an [ERC-8004](https://eips.ethereum.org/EIPS/eip-8004) agent for each token through an [ERC-8217](https://eips.ethereum.org/EIPS/eip-8217) adapter, with agent URI `prefix` + id + `suffix`. Whoever holds the token controls the agent. The adapter is a constructor argument, since it is only deployed on some networks. - Owner only, and only for tokens not minted yet (up to the max supply). The adapter lets a token contract register only tokens without an owner. MUSEGOD's version allowed it only before the first mint; this allows registering in ranges as a drop goes. - The adapter doesn't stop a token from being registered twice, so the contract records each agent id and skips tokens already registered. `agentOf(tokenId)` returns it. ## ERC-8048 onchain metadata `ERC8048OnchainMetadata` stores string keys with bytes values per token and implements ERC-8048's optional Metadata Authority extension in its collection-wide form ([ethereum/ERCs#2174](https://github.com/ethereum/ERCs/pull/2174)). The authority and three settings pack into one storage slot. - `tokenMetadataAuthority()` returns the one address that can write every token, including before mint, or zero when none is set. While it is set it is the only writer, as the ERC requires: the owner and holders write only through it. `supportsInterface(0x04f90b41)` returns true, and every change of the address emits `TokenMetadataAuthoritySet(address indexed authority)`. - While the authority is blank, the settings decide. The owner (`owner()`, so it follows ownership) writes any token unless `ownerCannotWrite` is on. `holderCanWrite` lets a token's current holder (`ownerOf` at write time) write that token. Transfers need no claim: the buyer writes right away and the seller can't. ERC-721 operators can't write for the holder. - `authorityLocked` stops the owner from calling `setCollectionAuthority`, including while the owner writes as the blank authority. A set authority can still call it, so a locked policy can hand itself on. A blank authority can be locked, which fixes the settings for good and blocks adding a policy later. - `setCollectionAuthority(authority, holderCanWrite, ownerCannotWrite, authorityLocked)` sets everything and emits `CollectionAuthoritySettingsUpdated(holderCanWrite, ownerCannotWrite, authorityLocked)`, so indexers see flag changes too. `collectionAuthoritySettings()` returns the flags. They default to false, so a new collection starts owner-only. - There are no key locks. Prem's follow-up pointed out that a key lock also freezes the key for tokens not minted yet: an artist who signs the first tokens and locks `artist.signature` leaves every later token unsigned. Freezing is left to a policy set as the authority, which can freeze per token. A collection that wants every record frozen locks a blank authority with `ownerCannotWrite` on and `holderCanWrite` off (`testFreezeEverything`). - Every write emits `MetadataSet`. A write to a minted token also emits ERC-4906 `MetadataUpdate`, since OpenSea refreshes on ERC-4906 events. The library calls a `_emitMetadataUpdate` hook and the token declares the event, so the library also works next to OpenZeppelin's `IERC4906`. Writes before mint skip it. A batch emits one `MetadataUpdate` per run of entries for the same token, and reverts if the caller can't write any entry. The settings cover these states, each with a test: | State | Authority, settings | Test | | --- | --- | --- | | Owner only. The owner writes and can change the settings | blank, all off | `testOwnerOnlyByDefault` | | Owner and holders. The owner can change the settings | blank, `holderCanWrite` | `testHoldersWrite` | | Locked blank, owner and holders for good | blank, `holderCanWrite`, `authorityLocked` | `testLockedBlankOwnerAndHolders` | | Locked blank, holders only for good | blank, `holderCanWrite`, `ownerCannotWrite`, `authorityLocked` | `testLockedBlankHoldersOnly` | | Locked blank, nobody writes | blank, `ownerCannotWrite`, `authorityLocked` | `testFreezeEverything` | | A policy. Only the policy writes, the owner can replace it | policy | `testPolicyAuthority`, `testAuthorityIsOnlyWriter` | | A locked policy. Only the policy writes and hands it on | policy, `authorityLocked` | `testLockedPolicy` | This replaces the earlier per-token Metadata Authority design. `lockMetadataKey`, `metadataKeyLocked`, `MetadataKeyLocked`, `MetadataKeyIsLocked`, `setMetadataAuthority`, the per-token authority mapping, metadata writers (`setMetadataWriter`), the clear-on-transfer hook, and ERC-165 support for the per-token Metadata Authority draft (`0xf9cb127d`) are gone. The token reports ERC-8048 (`0xdf670be1`), its collection-wide Metadata Authority extension (`0x04f90b41`), and ERC-4906 (`0x49064906`). Transfers no longer touch metadata storage. ### Reference policy `src/lib/MetadataWriterPolicy.sol` is a small example to set as the collection authority, so nothing the per-token design offered is lost. The token doesn't depend on it. - Its admin (`TwoStepOwnable` owner) allows several writer addresses with `setWriter`, replacing `setMetadataWriter`. - A token's current holder delegates their token's writes to one address with `setDelegate`, such as their agent's wallet. The delegation records the holder who set it and counts only while that address is still `ownerOf`, so it lapses on transfer (and counts again if the token returns to that holder). - Write-once keys, from Prem's follow-up. The admin marks a key with `setWriteOnceKey(key, bool)`, and a write to that key reverts with `WriteOnceValueSet(tokenId, key)` when the token already has a non-empty value, read through the token's `metadata(tokenId, key)`. `setMetadataBatch` applies the same rule and also counts earlier entries in the batch, so a batch can't set a value and overwrite it. Tokens minted later can still be written once (`testPolicyWriteOnceKey`, `testPolicyWriteOnceKeyBatch`). The admin can unmark a key, so a lasting freeze locks the authority to the policy and renounces the policy. While the policy is the authority, holders can't write past it whatever `holderCanWrite` says. - `setMetadata` and `setMetadataBatch` check the caller and forward to the token. The batch checks array lengths first (`BatchLengthMismatch`), since it now reads each entry. `setCollectionAuthority` is an admin passthrough, so a policy can hand the authority on. `renounceOwnership` also cancels a pending ownership transfer, as the token does, so a renounced policy stays renounced. The module reserves no keys. ERC-8048 is a draft and its agent profile (ERC-721T) may still change, so the keys are only listed in the doc. Token id 0 is not special. ## Docs [docs/AgentNFTs.md](https://github.com/ProjectOpenSea/seadrop/blob/ryan/agent-nft-extension/docs/AgentNFTs.md) covers deployment, the adapter addresses on Ethereum, Base, Robinhood Chain and Sepolia (each confirmed to have code), registration, the metadata authority and its common setups, the reference policy, and how OpenSea shows agent NFTs. The README and the bring-your-own-token doc link to it. ## Size and gas - `ERC721SeaDropAgents` runtime code is 23,472 bytes, 1,104 bytes under EIP-170. - Registration costs about 200,000 gas per token, or about 240,000 once the agent URI is longer than 31 bytes. Ethereum and Base cap a transaction at 16,777,216 gas (EIP-7825), so the docs say to register about 60 tokens per transaction. ## Tests - `test/foundry/ERC721SeaDropAgents.t.sol`: 32 tests (31 run, 1 fork test skipped in CI) covering the states above, settings permissions, when `TokenMetadataAuthoritySet` fires, a set authority as the only writer, `ownerCannotWrite` while unlocked, a locked authority clearing itself to a locked blank state, writes before mint, holder writes across transfer, safe transfer and burn, batches, the reference policy's writers, holder delegation and write-once keys (single and batch) through the token, registration ranges and skips (including a collection whose ids start past 1), interface ids, and the library next to OpenZeppelin's `ERC721URIStorage`. `forge coverage --ir-minimum` reports 100% line and branch coverage of `ERC8048OnchainMetadata` and `ERC721SeaDropAgents`, and 100% branch coverage of `MetadataWriterPolicy` (its two-line `renounceOwnership` shows as unhit lines under `--ir-minimum`, though `testPolicyRenounceCancelsPendingOwner` calls it). - `src/test/MockAgentAdapter.sol` applies the real adapter's registration rule. - `testRegisterAgentsWithDeployedAdapter` forks the chain `AGENT_ADAPTER_FORK_URL` names and registers through that chain's deployed adapter. It is skipped in CI. It passes locally on Ethereum, Base, Robinhood Chain and Sepolia against public RPCs. ## Audit An independent review of the earlier version found no critical, high or medium issues. Its changes that still apply: the library doesn't declare `MetadataUpdate` (so it compiles next to OpenZeppelin's `IERC4906`), and the docs cover the 16,777,216-gas transaction cap, that nobody can change an agent URI before mint, that agent URIs are public once registered, that the agent's URI and wallet carry over a sale, and that the adapters are upgradeable proxies a 3-of-4 Safe controls on Ethereum and Base. Its findings about clearing per-token authorities on transfer, batches failing on tokens with an authority, and writers surviving an ownership transfer no longer apply: there is no per-token authority, the collection authority can write every batch entry, key locks are gone, and writers now live in a policy contract with its own admin. ## Not in this PR - Upgradeable and clone versions. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- README.md | 9 + docs/AgentNFTs.md | 121 ++ docs/BringYourOwnTokenContract.md | 2 +- src/extensions/ERC721SeaDropAgents.sol | 205 +++ src/interfaces/IAgentAdapter.sol | 35 + src/interfaces/IERC8048Metadata.sol | 25 + .../IERC8048TokenMetadataAuthority.sol | 20 + src/lib/ERC8048OnchainMetadata.sol | 318 ++++ src/lib/MetadataWriterPolicy.sol | 305 ++++ src/test/MockAgentAdapter.sol | 68 + test/foundry/ERC721SeaDropAgents.t.sol | 1327 +++++++++++++++++ 11 files changed, 2434 insertions(+), 1 deletion(-) create mode 100644 docs/AgentNFTs.md create mode 100644 src/extensions/ERC721SeaDropAgents.sol create mode 100644 src/interfaces/IAgentAdapter.sol create mode 100644 src/interfaces/IERC8048Metadata.sol create mode 100644 src/interfaces/IERC8048TokenMetadataAuthority.sol create mode 100644 src/lib/ERC8048OnchainMetadata.sol create mode 100644 src/lib/MetadataWriterPolicy.sol create mode 100644 src/test/MockAgentAdapter.sol create mode 100644 test/foundry/ERC721SeaDropAgents.t.sol diff --git a/README.md b/README.md index 29fea821..da68d508 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,14 @@ SeaDrop is a contract for primary NFT drops on EVM chains. +## Versions + +- [v1 (`main`)](https://github.com/ProjectOpenSea/seadrop/tree/main) powers ERC-721 drops. +- [v2](https://github.com/ProjectOpenSea/seadrop/tree/v2) powers ERC-1155 self-minting for editions (open collections). It also supports existing staged drops and receives security fixes. +- [v3](https://github.com/ProjectOpenSea/seadrop/tree/v3) is in development. It upgrades v1's drop architecture and lets existing v1 collections opt into the new minter. It adds ERC-20 mint payments, delegate-wallet and linked-wallet support, signed mint intents, clone factories, existing-contract adapters and agent NFT extensions. Self-service ERC-1155 edition drops are planned for a later rollout. + +See the [v3 tracker](https://github.com/ProjectOpenSea/seadrop/issues/235) for scope and remaining work. v3 requires Security review and an external audit before deployment. + ## Background SeaDrop runs primary NFT drops: public drops, allow lists, server-side signed mints and token-gated mints. A token contract configures its drop through `SeaDrop`, and minters mint through `SeaDrop`. @@ -42,6 +50,7 @@ The creator configures a drop by calling the token, for example `updatePublicDro - [SeaDrop Deployment](docs/SeaDropDeployment.md) - [SeaDrop Token Deployment](docs/SeaDropTokenDeployment.md) - [Bring Your Own Token Contract](docs/BringYourOwnTokenContract.md) +- [Agent NFTs](docs/AgentNFTs.md) - [Drops for an existing contract](docs/ExistingContractAdapters.md) - [Provenance Hash](docs/ProvenanceHash.md) - [Upgradeable Contracts](docs/UpgradeableContracts.md) diff --git a/docs/AgentNFTs.md b/docs/AgentNFTs.md new file mode 100644 index 00000000..47435f28 --- /dev/null +++ b/docs/AgentNFTs.md @@ -0,0 +1,121 @@ +# Agent NFTs + +`ERC721SeaDropAgents` (in `src/extensions`) is `ERC721SeaDrop` for collections whose tokens are AI agents. It adds two things: + +- Agent registration. The owner registers an [ERC-8004](https://eips.ethereum.org/EIPS/eip-8004) agent for each token before it mints, through an [ERC-8217](https://eips.ethereum.org/EIPS/eip-8217) adapter. Whoever holds the token controls its agent. +- Onchain metadata under [ERC-8048](https://eips.ethereum.org/EIPS/eip-8048): string keys with bytes values, stored per token, with ERC-8048's Metadata Authority extension deciding who can write them. The ERC-8048 code lives in `src/lib/ERC8048OnchainMetadata.sol`, so other token contracts can reuse it, including ones that already implement ERC-4906. + +Minting, drop configuration and `tokenURI` work as in `ERC721SeaDrop`. + +## Deploy + +The constructor takes the usual name, symbol and allowed SeaDrop addresses, plus the adapter to register agents through: + +| Network | ERC-8217 adapter | +| --------------- | -------------------------------------------- | +| Ethereum | `0xde152afb7db5373f34876e1499fbd893a82dd336` | +| Base | `0x270d25d2c59a8bca1b0f40ad95ff7806c0025c27` | +| Robinhood Chain | `0x000000009d62675362a58911e3f32fecf46f5e18` | +| Sepolia | `0x7621630cb63a73a194f45a3e6801b8c6a7ec2f92` | + +On a network without an adapter, pass the zero address. Registration then reverts with `AgentAdapterNotSet`, and onchain metadata still works. + +The adapters are upgradeable proxies. On Ethereum and Base a 3-of-4 Safe controls their upgrades, so the bindings between tokens and agents rely on that Safe. + +The contract's runtime code is about 23.4 KB, about 1.2 KB under the EIP-170 limit, so a contract that inherits it has little room to add code. + +## Register agents + +```solidity +function registerAgents( + uint256 firstTokenId, + uint256 lastTokenId, + string calldata prefix, + string calldata suffix +) external; +``` + +`registerAgents` registers one agent per token id from `firstTokenId` to `lastTokenId`. Each agent's URI is `prefix`, then the token id, then `suffix`, for example `https://example.com/agents/` and `.json`. `agentOf(tokenId)` returns the agent id. + +- Only the owner can call it. +- It only works for tokens that are not minted yet. The adapter lets a token contract register a token only while the token has no owner. Set the max supply first, since the range can't go past the last token id that can mint. +- Tokens already registered are skipped, so overlapping ranges, or a range sent again after earlier transactions registered part of it, don't register a token twice. The adapter itself doesn't stop a token from being registered twice. +- Each registration mints an identity in the ERC-8004 registry. That costs about 200,000 gas per token, or about 240,000 once the agent URI is longer than 31 bytes. Ethereum and Base cap a transaction at 16,777,216 gas (EIP-7825), so register about 60 tokens per transaction, fewer with long URIs. +- Nobody can change an agent URI before its token mints, the owner included, and sending the range again skips it. Check the prefix and suffix before you register, and use URIs whose content you control. +- Agent URIs are public once registered. For a delayed reveal, keep anything that gives the reveal away out of the registration files until then. + +After a token mints, its holder controls the agent in the adapter. They can change the agent URI or set the agent's wallet there. A holder can also register a token the owner didn't register by calling the adapter directly. `agentOf` only tracks agents registered through `registerAgents`. Once a token is burned, nobody controls its agent. + +The agent's URI and wallet stay as they are when the token is sold. A buyer should set both again through the adapter after buying, or payments sent to the agent's wallet keep reaching the seller. + +The agent URI should point to an ERC-8004 registration file, the JSON whose `type` is `https://eips.ethereum.org/EIPS/eip-8004#registration-v1`. Keep that `type` out of the token's own `tokenURI` JSON. OpenSea reads the agent card from the registration file only. + +## Onchain metadata + +Anyone can read a token's records with `metadata(tokenId, key)`. + +### Who can write + +The contract implements [ERC-8048](https://github.com/ethereum/ERCs/blob/master/ERCS/erc-8048.md)'s optional Metadata Authority extension (interface id `0x04f90b41`). `tokenMetadataAuthority()` returns the one address that can write every token's records, or the zero address when none is set. + +- While the authority is set, it is the only writer, for every token, including before a token mints. It can be an account or a policy contract that applies its own rules. The owner and holders write only through it. +- While the authority is blank, three settings decide who writes. `collectionAuthoritySettings()` returns them. + - The owner writes any token's records, unless `ownerCannotWrite` is on. + - With `holderCanWrite`, a token's current holder also writes that token's records. The contract checks `ownerOf` at write time, so after a transfer the new holder can write right away and the old holder can't. ERC-721 operators can't write for the holder. + - With `authorityLocked`, nobody can change the settings or set an authority again, the owner included. +- A set authority can also be locked. Then the owner can't replace it, and only the authority can hand itself on, including to a locked blank state. + +`setCollectionAuthority(authority, holderCanWrite, ownerCannotWrite, authorityLocked)` sets the authority and all three settings. The owner can call it until the settings are locked, and a set authority can always call it. It emits `TokenMetadataAuthoritySet(authority)` when the authority changes and `CollectionAuthoritySettingsUpdated` every time. The settings all start false, so a new collection starts with the owner as the only writer. A blank authority follows ownership, so a new owner takes over writing when the contract changes owners. + +### Common setups + +- Owner only. Leave the authority blank and the settings false, the default. The owner writes and can change the settings. +- Owner and holders. Leave the authority blank and set `holderCanWrite`. The owner writes any token, each holder writes their own, and the owner can change the settings. +- Locked blank. Leave the authority blank and set `authorityLocked`. The other two settings decide who writes for good: the owner and holders, the owner only, holders only (with `ownerCannotWrite`), or nobody (with `ownerCannotWrite` and without `holderCanWrite`), which freezes every record, including for tokens that mint later. Nobody can change the settings or add a policy. +- A policy. Set a policy contract as the authority. Only the policy writes, and the owner can replace it. +- A locked policy. Do the same and set `authorityLocked`. Only the policy writes, the owner can't replace it, and only the policy can hand the authority on. + +When holders can write, a seller can change their token's records up to the moment of sale, so a buyer should check them after buying. In the other setups holders write only through a policy's rules, if at all. + +### Reference policy + +`src/lib/MetadataWriterPolicy.sol` is a small policy contract to set as the metadata authority. The contract doesn't need it, and it shows what a policy can do. Its owner (the admin) can allow several writer addresses with `setWriter`, such as a hot wallet that runs a metadata job. A writer can write records and nothing else. A token's current holder can delegate their token's writes to one address with `setDelegate`, such as their agent's wallet. A delegation counts only while the holder who set it still holds the token, so it lapses on transfer. It counts again if the token comes back to that holder. + +Writers and delegates call the policy's `setMetadata` and `setMetadataBatch`, which check the caller and forward the write to the token. The admin can also call `setCollectionAuthority` through the policy, for example to hand the authority to a new policy. + +### Freezing records + +The contract has no key locks. A lock on a key would also freeze it for tokens that haven't minted yet, so an artist who signed the first tokens and then locked `artist.signature` would leave every later token without a signature. Freezing is up to a policy set as the authority instead, which can freeze per token. + +The reference policy shows one way. Its admin can mark a key write-once with `setWriteOnceKey(key, true)`. A write to a write-once key through the policy reverts with `WriteOnceValueSet` once that token has a non-empty value for the key, in `setMetadata` and `setMetadataBatch` alike, counting earlier entries in the same batch. An artist can sign tokens 1 and 2, and token 3 can still be signed once after it mints, but nobody can overwrite the signatures on tokens 1 and 2. + +The admin can unmark a key, and the owner can replace an unlocked policy. For a freeze that holds, set the policy as the authority with `authorityLocked`, then renounce the policy's ownership. While the policy has an admin, that admin can still unmark keys. To freeze every record instead, lock a blank authority with `ownerCannotWrite` on and `holderCanWrite` off, as described above. + +### Batches + +`setMetadataBatch` writes many records in one transaction. If the caller can't write any one entry, the whole batch reverts. A set authority, or the owner while the authority is blank, can write every entry. + +### Events and keys + +Every write emits ERC-8048's `MetadataSet`. A write to a minted token also emits ERC-4906's `MetadataUpdate`. Writes before mint don't, since marketplaces read a token's metadata when it mints. + +The contract doesn't fix any keys. ERC-8048's agent profile (nicknamed ERC-721T) reserves these: + +| Key | Value | +| ------------------------------ | -------------------------------------------------------------- | +| `context` | The agent's context as UTF-8 text, Markdown suggested | +| `endpoint[]` | A URI, for types such as `mcp`, `a2a`, `ens`, `web` and `x402` | +| `address[]` | The agent's account on a chain, as raw address bytes | +| `account[][]` | An additional account on a chain | + +`` is an ERC-7930 chain identifier, such as `0x00010000010100` for Ethereum. ERC-8048 is a draft and its agent profile may still change, so check the current text before you pick keys. Keys are case sensitive. + +Token id 0 is not special. Put collection-level data in the contract URI. + +## How OpenSea shows agent NFTs + +- The NFT's page shows that the token is bound to an agent, from the adapter's `AgentBound` event. +- The agent card shows on the agent's identity item in the ERC-8004 registry, read from the agent URI. +- OpenSea doesn't read ERC-8048 records. Anything OpenSea should show, such as the name, image and traits, goes in the `tokenURI` JSON. Don't copy agent keys such as `context` or `endpoint[mcp]` into that JSON: ERC-8495, the draft standard for `tokenURI` JSON, asks for field names of lowercase letters, digits and underscores that won't collide with future extensions. +- OpenSea refreshes a token's metadata when it sees an ERC-4906 event, and every record write to a minted token emits one. +- Agents created with the adapter's `counterfactualRegister` are not indexed. diff --git a/docs/BringYourOwnTokenContract.md b/docs/BringYourOwnTokenContract.md index 66f72d66..fcbf28e4 100644 --- a/docs/BringYourOwnTokenContract.md +++ b/docs/BringYourOwnTokenContract.md @@ -1,6 +1,6 @@ # Bring Your Own Token Contract -Token creators who would like to use their own token contract functionality can inherit `ERC721SeaDrop`. There are also several extensions in `src/extensions` such as RandomOffset and Lockable, which can pause trading or make tokens non-transferable ([ERC-6982](https://eips.ethereum.org/EIPS/eip-6982) and [ERC-8451](https://github.com/ethereum/ERCs/pull/2084)). +Token creators who would like to use their own token contract functionality can inherit `ERC721SeaDrop`. There are also several extensions in `src/extensions`: RandomOffset, Lockable, which can pause trading or make tokens non-transferable ([ERC-6982](https://eips.ethereum.org/EIPS/eip-6982) and [ERC-8451](https://github.com/ethereum/ERCs/pull/2084)), and Agents, for tokens that are AI agents ([Agent NFTs](./AgentNFTs.md)). SeaDrop tokens use ERC721A for efficient multiple-quantity mint, along with additional tracking metadata like number of tokens minted by address used for enforcing wallet limits. Please do not override or modify any SeaDrop-related functionality on the token like `getMintStats()` to remain compatible and secure with SeaDrop. diff --git a/src/extensions/ERC721SeaDropAgents.sol b/src/extensions/ERC721SeaDropAgents.sol new file mode 100644 index 00000000..edc0aef6 --- /dev/null +++ b/src/extensions/ERC721SeaDropAgents.sol @@ -0,0 +1,205 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.38; + +import { ERC721SeaDrop } from "../ERC721SeaDrop.sol"; + +import { ERC8048OnchainMetadata } from "../lib/ERC8048OnchainMetadata.sol"; + +import { IAgentAdapter } from "../interfaces/IAgentAdapter.sol"; + +import { IERC8048Metadata } from "../interfaces/IERC8048Metadata.sol"; + +import { + IERC8048TokenMetadataAuthority +} from "../interfaces/IERC8048TokenMetadataAuthority.sol"; + +/** + * @title ERC721SeaDropAgents + * @author Ryan Ghods (ralxz.eth) + * @notice ERC721SeaDrop for tokens that are AI agents. It adds: + * + * - Agent registration. The owner registers an ERC-8004 agent for + * each token before it is minted, through an ERC-8217 adapter, so + * every token is minted with its agent. Whoever holds the token + * controls the agent. + * - ERC-8048 onchain metadata, for agent records such as the + * ERC-721T profile's `context` and `endpoint[mcp]` keys, with + * ERC-8048's Metadata Authority extension. See + * ERC8048OnchainMetadata for who can write them. + * + * tokenURI works as in ERC721SeaDrop, and marketplaces read the + * token's JSON from it as usual. + */ +contract ERC721SeaDropAgents is ERC721SeaDrop, ERC8048OnchainMetadata { + /// @dev The ERC-8217 adapter agents are registered through, or the + /// zero address on a chain without one. + address internal immutable _AGENT_ADAPTER; + + /// @dev The agent id registered for each token, plus one, so zero means + /// none. + mapping(uint256 => uint256) private _agentIdsPlusOne; + + /// @notice Emitted when a token's metadata changes (ERC-4906). + event MetadataUpdate(uint256 _tokenId); + + /// @notice Revert when registering agents without an adapter. + error AgentAdapterNotSet(); + + /// @notice Revert when the token id range to register is empty, starts + /// at a token that was already minted, or ends past the max + /// supply. + error InvalidAgentTokenIdRange(uint256 firstTokenId, uint256 lastTokenId); + + /** + * @notice Deploy the token contract with its name, symbol, allowed + * SeaDrop addresses, and agent adapter. + * + * @param name The name of the token. + * @param symbol The symbol of the token. + * @param allowedSeaDrop The allowed SeaDrop addresses. + * @param adapter The ERC-8217 adapter to register agents + * through, or the zero address on a chain without + * one. Registration reverts without an adapter. + */ + constructor( + string memory name, + string memory symbol, + address[] memory allowedSeaDrop, + address adapter + ) ERC721SeaDrop(name, symbol, allowedSeaDrop) { + _AGENT_ADAPTER = adapter; + } + + /** + * @notice Returns the ERC-8217 adapter agents are registered through. + */ + function agentAdapter() external view returns (address) { + return _AGENT_ADAPTER; + } + + /** + * @notice Returns the agent the owner registered for `tokenId`, if any. + * An agent the holder registers through the adapter directly + * after mint is not tracked here. + * + * @param tokenId The token id. + * + * @return registered Whether an agent is registered for the token. + * @return agentId The agent's id in the ERC-8004 registry. + */ + function agentOf(uint256 tokenId) + external + view + returns (bool registered, uint256 agentId) + { + uint256 agentIdPlusOne = _agentIdsPlusOne[tokenId]; + if (agentIdPlusOne != 0) { + registered = true; + unchecked { + agentId = agentIdPlusOne - 1; + } + } + } + + /** + * @notice Register an ERC-8004 agent for each token id from + * `firstTokenId` to `lastTokenId`, with the agent URI + * `prefix` + token id + `suffix`. Only the owner can call this, + * and only for tokens not minted yet, since the adapter lets a + * token contract register only tokens without an owner. Tokens + * already registered here are skipped, so a failed batch can be + * sent again. + * + * Each registration mints an identity in the ERC-8004 registry, + * so large ranges need several transactions. + * + * @param firstTokenId The first token id to register. + * @param lastTokenId The last token id to register. + * @param prefix The agent URI before the token id. + * @param suffix The agent URI after the token id. + */ + function registerAgents( + uint256 firstTokenId, + uint256 lastTokenId, + string calldata prefix, + string calldata suffix + ) external onlyOwner { + address adapter = _AGENT_ADAPTER; + if (adapter == address(0)) revert AgentAdapterNotSet(); + + // The max supply caps how many tokens mint, so the last token that + // can mint is the start id plus the max supply, less one. + if ( + firstTokenId < _nextTokenId() || lastTokenId < firstTokenId + || lastTokenId - _startTokenId() >= maxSupply() + ) { + revert InvalidAgentTokenIdRange(firstTokenId, lastTokenId); + } + + for (uint256 tokenId = firstTokenId; tokenId <= lastTokenId; ++tokenId) { + if (_agentIdsPlusOne[tokenId] != 0) continue; + + uint256 agentId = IAgentAdapter(adapter) + .register( + 0, // ERC-721 + address(this), + tokenId, + string.concat(prefix, _toString(tokenId), suffix) + ); + _agentIdsPlusOne[tokenId] = agentId + 1; + } + } + + /** + * @notice Returns whether the interface is supported. + * + * @param interfaceId The interface id to check against. + */ + function supportsInterface(bytes4 interfaceId) + public + view + virtual + override + returns (bool) + { + return interfaceId == type(IERC8048Metadata).interfaceId + || interfaceId == type(IERC8048TokenMetadataAuthority).interfaceId + || super.supportsInterface(interfaceId); + } + + /** + * @dev The owner is the metadata admin. + */ + function _isMetadataAdmin(address account) + internal + view + virtual + override + returns (bool) + { + return account == owner(); + } + + /** + * @dev Emit ERC-4906 `MetadataUpdate` for a token that exists, from mint + * until burn. + */ + function _emitMetadataUpdate(uint256 tokenId) internal virtual override { + if (_exists(tokenId)) { + emit MetadataUpdate(tokenId); + } + } + + /** + * @dev A token's holder is its owner, from mint until burn. + */ + function _metadataHolderOf(uint256 tokenId) + internal + view + virtual + override + returns (address) + { + return _exists(tokenId) ? ownerOf(tokenId) : address(0); + } +} diff --git a/src/interfaces/IAgentAdapter.sol b/src/interfaces/IAgentAdapter.sol new file mode 100644 index 00000000..72cb2c62 --- /dev/null +++ b/src/interfaces/IAgentAdapter.sol @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.7; + +/** + * @title IAgentAdapter + * @notice The registration call of an ERC-8217 adapter for ERC-8004 agent + * identities. The adapter mints an identity in the ERC-8004 + * registry and binds it to a token for good. Whoever holds the + * token then controls the agent. + * + * A token contract can register one of its own ERC-721 tokens + * while `ownerOf` reverts or returns the zero address for it. After + * the token is minted, only its holder or the holder's delegate + * can register it. The adapter does not stop a token from being + * registered twice. + */ +interface IAgentAdapter { + /** + * @notice Registers a new ERC-8004 agent bound to `tokenId` of + * `boundAddress`. + * + * @param standard The bound token's standard. 0 is ERC-721. + * @param boundAddress The token contract. + * @param tokenId The token id. + * @param agentURI The agent's registration file URI. + * + * @return agentId The new agent's id in the ERC-8004 registry. + */ + function register( + uint8 standard, + address boundAddress, + uint256 tokenId, + string calldata agentURI + ) external returns (uint256 agentId); +} diff --git a/src/interfaces/IERC8048Metadata.sol b/src/interfaces/IERC8048Metadata.sol new file mode 100644 index 00000000..a3d1dae9 --- /dev/null +++ b/src/interfaces/IERC8048Metadata.sol @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.7; + +/** + * @title IERC8048Metadata + * @notice ERC-8048: Onchain Metadata for Token Registries (draft). String + * keys with bytes values, stored per token. + * The ERC-165 identifier for this interface is 0xdf670be1. + */ +interface IERC8048Metadata { + /// @notice Emitted when a token's value for `key` is set. + event MetadataSet( + uint256 indexed tokenId, + string indexed indexedKey, + string key, + bytes value + ); + + /// @notice Returns the value of `key` for `tokenId`, or empty bytes + /// when none is set. + function metadata(uint256 tokenId, string calldata key) + external + view + returns (bytes memory); +} diff --git a/src/interfaces/IERC8048TokenMetadataAuthority.sol b/src/interfaces/IERC8048TokenMetadataAuthority.sol new file mode 100644 index 00000000..5ac3c315 --- /dev/null +++ b/src/interfaces/IERC8048TokenMetadataAuthority.sol @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.7; + +/** + * @title IERC8048TokenMetadataAuthority + * @notice ERC-8048's optional Metadata Authority extension (draft). One + * metadata authority for every token in the collection. While it + * is set, it is the only address that can write metadata. While + * it is the zero address, the contract's own write policy applies. + * The ERC-165 identifier for this interface is 0x04f90b41. + */ +interface IERC8048TokenMetadataAuthority { + /// @notice Emitted when the metadata authority is set, changed, or + /// cleared. `authority` is the zero address when cleared. + event TokenMetadataAuthoritySet(address indexed authority); + + /// @notice Returns the metadata authority for every token, or the + /// zero address when none is set. + function tokenMetadataAuthority() external view returns (address); +} diff --git a/src/lib/ERC8048OnchainMetadata.sol b/src/lib/ERC8048OnchainMetadata.sol new file mode 100644 index 00000000..ffde164a --- /dev/null +++ b/src/lib/ERC8048OnchainMetadata.sol @@ -0,0 +1,318 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.38; + +import { IERC8048Metadata } from "../interfaces/IERC8048Metadata.sol"; + +import { + IERC8048TokenMetadataAuthority +} from "../interfaces/IERC8048TokenMetadataAuthority.sol"; + +/** + * @title ERC8048OnchainMetadata + * @author Ryan Ghods (ralxz.eth) + * @notice Onchain metadata for ERC-721 tokens under ERC-8048: string keys + * with bytes values, stored per token, with ERC-8048's optional + * Metadata Authority extension. + * + * The token metadata authority and three settings decide who + * writes: + * - While `tokenMetadataAuthority()` is set, it is the only address + * that can write, for every token, as ERC-8048 requires. It can + * be an account or a policy contract that applies its own rules, + * such as MetadataWriterPolicy. The settings below don't apply. + * - While the authority is blank (the zero address), the metadata + * admin (the owner) can write any token's metadata, unless + * `ownerCannotWrite` is on. + * - While the authority is blank and `holderCanWrite` is on, a + * token's current holder can also write that token's metadata. + * The check reads the holder at write time, so a new holder can + * write right after a transfer and the old holder can't. + * - With `authorityLocked`, the admin can no longer change the + * authority or the settings. A nonzero authority still can, so a + * locked policy contract can hand itself on. A locked blank + * authority fixes the settings for good: nobody can change them + * or set a policy later. + * + * The settings all start false, so a new collection starts with + * the admin as the only writer. Tokens don't have to exist yet, so + * the admin or the authority can write metadata before a mint. + * + * The module has no key locks. A policy contract can freeze + * records per token, for example with a write-once rule. To freeze + * every record, lock a blank authority with `ownerCannotWrite` on + * and `holderCanWrite` off. + * + * Each write emits `MetadataSet` and calls `_emitMetadataUpdate` + * once per token, where the token contract emits ERC-4906 + * `MetadataUpdate` for a token that exists, since marketplaces + * refresh tokens on ERC-4906 events. Records written before a mint + * are picked up when the token mints. The event is left to the + * token contract so this can sit next to an ERC-4906 + * implementation that already declares it. + * + * The token contract that inherits this must decide who the admin + * is in `_isMetadataAdmin`, name a token's holder in + * `_metadataHolderOf`, emit ERC-4906 in `_emitMetadataUpdate`, and + * return true from `supportsInterface` for IERC8048Metadata and + * IERC8048TokenMetadataAuthority. + */ +abstract contract ERC8048OnchainMetadata is + IERC8048Metadata, + IERC8048TokenMetadataAuthority +{ + /// @dev The authority and its three settings, in one slot. + struct CollectionAuthority { + address authority; + bool holderCanWrite; + bool ownerCannotWrite; + bool authorityLocked; + } + + /// @dev Each token's values, by key. + mapping(uint256 => mapping(string => bytes)) private _metadata; + + /// @dev The authority and its settings. + CollectionAuthority private _collectionAuthority; + + /// @notice Emitted when the settings are set, with the values they + /// now hold. + event CollectionAuthoritySettingsUpdated( + bool holderCanWrite, + bool ownerCannotWrite, + bool authorityLocked + ); + + /// @notice Revert when the caller can't write `tokenId`'s metadata. + error MetadataWriteUnauthorized(uint256 tokenId); + + /// @notice Revert when the caller is neither the admin nor a nonzero + /// authority. + error CollectionAuthorityUnauthorized(); + + /// @notice Revert when the admin changes the settings after they were + /// locked. + error CollectionAuthorityIsLocked(); + + /// @notice Revert when a batch's arrays differ in length. + error MetadataBatchLengthMismatch(); + + /** + * @notice Returns the value of `key` for `tokenId`, or empty bytes when + * none is set. + */ + function metadata(uint256 tokenId, string calldata key) + external + view + returns (bytes memory) + { + return _metadata[tokenId][key]; + } + + /** + * @notice Returns the metadata authority for every token, or the zero + * address when none is set and the settings decide who writes. + */ + function tokenMetadataAuthority() external view returns (address) { + return _collectionAuthority.authority; + } + + /** + * @notice Returns the settings that apply while the authority is + * blank, and whether they are locked. + * + * @return holderCanWrite Whether a token's holder can write its + * metadata. + * @return ownerCannotWrite Whether the admin is shut out of writing. + * @return authorityLocked Whether only a nonzero authority can change + * the authority or the settings. + */ + function collectionAuthoritySettings() + external + view + returns ( + bool holderCanWrite, + bool ownerCannotWrite, + bool authorityLocked + ) + { + CollectionAuthority memory settings = _collectionAuthority; + return ( + settings.holderCanWrite, + settings.ownerCannotWrite, + settings.authorityLocked + ); + } + + /** + * @notice Set `tokenId`'s value for `key`. An empty value clears it. + * + * @param tokenId The token id. + * @param key The key. + * @param value The value. + */ + function setMetadata( + uint256 tokenId, + string calldata key, + bytes calldata value + ) external { + _setMetadata(tokenId, key, value); + _emitMetadataUpdate(tokenId); + } + + /** + * @notice Set `values[i]` for `keys[i]` on `tokenIds[i]`, each as + * `setMetadata` would. Any entry that fails reverts the batch. + * Consecutive entries for the same token emit one + * `MetadataUpdate`. + * + * @param tokenIds The token ids. + * @param keys The keys. + * @param values The values. + */ + function setMetadataBatch( + uint256[] calldata tokenIds, + string[] calldata keys, + bytes[] calldata values + ) external { + uint256 length = tokenIds.length; + if (keys.length != length || values.length != length) { + revert MetadataBatchLengthMismatch(); + } + + for (uint256 i = 0; i < length;) { + uint256 tokenId = tokenIds[i]; + _setMetadata(tokenId, keys[i], values[i]); + + unchecked { + ++i; + } + + if (i == length || tokenIds[i] != tokenId) { + _emitMetadataUpdate(tokenId); + } + } + } + + /** + * @notice Set the authority and its settings. A nonzero authority can + * always call this. The admin can call it until the settings + * are locked, including while it writes as the blank + * authority. Emits `TokenMetadataAuthoritySet` when the + * authority changes. + * + * @param authority The new authority, or the zero address to + * let the settings decide who writes. + * @param holderCanWrite Whether a token's holder can write its + * metadata while the authority is blank. + * @param ownerCannotWrite Whether to shut the admin out of writing + * while the authority is blank. + * @param authorityLocked Whether to stop the admin from changing + * these again. With a blank authority, nobody + * can change them again. + */ + function setCollectionAuthority( + address authority, + bool holderCanWrite, + bool ownerCannotWrite, + bool authorityLocked + ) external { + CollectionAuthority memory current = _collectionAuthority; + if (current.authority == address(0) || msg.sender != current.authority) + { + if (!_isMetadataAdmin(msg.sender)) { + revert CollectionAuthorityUnauthorized(); + } + if (current.authorityLocked) { + revert CollectionAuthorityIsLocked(); + } + } + + _collectionAuthority = CollectionAuthority( + authority, holderCanWrite, ownerCannotWrite, authorityLocked + ); + if (authority != current.authority) { + emit TokenMetadataAuthoritySet(authority); + } + emit CollectionAuthoritySettingsUpdated( + holderCanWrite, + ownerCannotWrite, + authorityLocked + ); + } + + /** + * @dev Returns whether `account` can write any token: the authority + * while one is set, otherwise the admin unless `ownerCannotWrite` + * is on. + */ + function _isCollectionWriter(address account) internal view returns (bool) { + CollectionAuthority memory settings = _collectionAuthority; + if (settings.authority != address(0)) { + return account == settings.authority; + } + return !settings.ownerCannotWrite && _isMetadataAdmin(account); + } + + /** + * @dev Store `value` for `key` on `tokenId` after checking the caller + * and emit `MetadataSet`. + */ + function _setMetadata( + uint256 tokenId, + string calldata key, + bytes calldata value + ) internal { + if (!_isCollectionWriter(msg.sender)) { + if (!_isHolderWriter(tokenId, msg.sender)) { + revert MetadataWriteUnauthorized(tokenId); + } + } + + _metadata[tokenId][key] = value; + emit MetadataSet(tokenId, key, key, value); + } + + /** + * @dev Returns whether the authority is blank, holders can write, and + * `account` holds `tokenId` now. A token that doesn't exist has no + * holder. + */ + function _isHolderWriter(uint256 tokenId, address account) + internal + view + returns (bool) + { + CollectionAuthority memory settings = _collectionAuthority; + if (settings.authority != address(0) || !settings.holderCanWrite) { + return false; + } + + address holder = _metadataHolderOf(tokenId); + return holder != address(0) && account == holder; + } + + /** + * @dev Returns whether `account` is the metadata admin. + */ + function _isMetadataAdmin(address account) + internal + view + virtual + returns (bool); + + /** + * @dev Called after `tokenId`'s metadata changes. Emit ERC-4906 + * `MetadataUpdate` here if the token exists. + */ + function _emitMetadataUpdate(uint256 tokenId) internal virtual; + + /** + * @dev Returns `tokenId`'s holder, or the zero address when the token + * does not exist. + */ + function _metadataHolderOf(uint256 tokenId) + internal + view + virtual + returns (address); +} diff --git a/src/lib/MetadataWriterPolicy.sol b/src/lib/MetadataWriterPolicy.sol new file mode 100644 index 00000000..94737ac1 --- /dev/null +++ b/src/lib/MetadataWriterPolicy.sol @@ -0,0 +1,305 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.38; + +import { TwoStepOwnable } from "utility-contracts/TwoStepOwnable.sol"; + +/// @dev The parts of an ERC8048OnchainMetadata token the policy calls. +interface IERC8048OnchainMetadataToken { + function setMetadata( + uint256 tokenId, + string calldata key, + bytes calldata value + ) external; + + function setMetadataBatch( + uint256[] calldata tokenIds, + string[] calldata keys, + bytes[] calldata values + ) external; + + function metadata(uint256 tokenId, string calldata key) + external + view + returns (bytes memory); + + function setCollectionAuthority( + address authority, + bool holderCanWrite, + bool ownerCannotWrite, + bool authorityLocked + ) external; + + function ownerOf(uint256 tokenId) external view returns (address); +} + +/** + * @title MetadataWriterPolicy + * @author Ryan Ghods (ralxz.eth) + * @notice A reference policy to set as an ERC8048OnchainMetadata token's + * metadata authority. It is an example; the token doesn't need + * it. Writes go through this contract, which forwards them to the + * token when: + * + * - The caller is a writer its owner (the admin) allows, such as a + * hot wallet that runs a metadata job. + * - The caller is the address a token's current holder delegated + * that token's writes to, such as their agent's wallet. A + * delegation records the holder who set it and counts only while + * that address still holds the token, so it lapses on transfer. + * It counts again if the token comes back to that holder. + * + * The admin can mark a key write-once. A write to a write-once key + * reverts when the token already has a non-empty value for it, so + * each token's value can be set once and never changed, while + * tokens minted later can still be written. The admin can unmark + * the key, so for a lasting freeze, lock the token's authority to + * this policy and renounce or hand off its ownership. While this + * policy is the authority, it is the token's only writer, so + * nobody writes past these rules. + * + * The admin can also change the token's authority through this + * contract. + */ +contract MetadataWriterPolicy is TwoStepOwnable { + /// @dev A token's delegate and the holder who set it. + struct Delegation { + address holder; + address delegate; + } + + /// @notice The token this policy writes to. + IERC8048OnchainMetadataToken public immutable token; + + /// @dev The accounts the admin allows to write any token. + mapping(address => bool) private _writers; + + /// @dev Each token's delegation. + mapping(uint256 => Delegation) private _delegations; + + /// @dev The write-once keys, by the hash of the key. + mapping(bytes32 => bool) private _writeOnceKeys; + + /// @notice Emitted when the admin allows or removes a writer. + event WriterUpdated(address indexed writer, bool allowed); + + /// @notice Emitted when `holder` delegates `tokenId`'s writes to + /// `delegate`, or clears it with the zero address. + event DelegateSet( + uint256 indexed tokenId, + address indexed holder, + address indexed delegate + ); + + /// @notice Emitted when the admin marks or unmarks `key` write-once. + event WriteOnceKeyUpdated( + string indexed indexedKey, + string key, + bool writeOnce + ); + + /// @notice Revert when the caller can't write `tokenId`. + error WriteUnauthorized(uint256 tokenId); + + /// @notice Revert when the caller doesn't hold `tokenId`. + error NotTokenHolder(uint256 tokenId); + + /// @notice Revert when writing a write-once `key` that `tokenId` + /// already has a value for. + error WriteOnceValueSet(uint256 tokenId, string key); + + /// @notice Revert when a batch's arrays differ in length. + error BatchLengthMismatch(); + + /** + * @param token_ The token this policy writes to. + */ + constructor(address token_) { + token = IERC8048OnchainMetadataToken(token_); + } + + /** + * @notice Returns whether the admin allows `account` to write any + * token. + */ + function isWriter(address account) external view returns (bool) { + return _writers[account]; + } + + /** + * @notice Returns whether `key` is write-once. + */ + function isWriteOnceKey(string calldata key) external view returns (bool) { + return _writeOnceKeys[keccak256(bytes(key))]; + } + + /** + * @notice Returns the address `tokenId`'s current holder delegated its + * writes to, or the zero address when there is none or the + * holder who set it no longer holds the token. + */ + function delegateOf(uint256 tokenId) public view returns (address) { + Delegation memory delegation = _delegations[tokenId]; + if (delegation.holder != _holderOf(tokenId)) return address(0); + return delegation.delegate; + } + + /** + * @notice Allow or remove a writer. Only the admin can call this. + * + * @param writer The account. + * @param allowed Whether the account can write any token. + */ + function setWriter(address writer, bool allowed) external onlyOwner { + _writers[writer] = allowed; + emit WriterUpdated(writer, allowed); + } + + /** + * @notice Mark or unmark `key` write-once. Only the admin can call + * this. + * + * @param key The key. + * @param writeOnce Whether a token's non-empty value for the key can't + * be overwritten. + */ + function setWriteOnceKey(string calldata key, bool writeOnce) + external + onlyOwner + { + _writeOnceKeys[keccak256(bytes(key))] = writeOnce; + emit WriteOnceKeyUpdated(key, key, writeOnce); + } + + /** + * @notice Delegate `tokenId`'s writes to `delegate`, or clear it with + * the zero address. Only the token's current holder can call + * this. + * + * @param tokenId The token id. + * @param delegate The address that can write the token. + */ + function setDelegate(uint256 tokenId, address delegate) external { + if (msg.sender != _holderOf(tokenId)) revert NotTokenHolder(tokenId); + + _delegations[tokenId] = Delegation(msg.sender, delegate); + emit DelegateSet(tokenId, msg.sender, delegate); + } + + /** + * @notice Write `tokenId`'s value for `key` on the token. + */ + function setMetadata( + uint256 tokenId, + string calldata key, + bytes calldata value + ) external { + if (!_writers[msg.sender]) _checkDelegate(tokenId); + _checkWriteOnce(tokenId, key); + token.setMetadata(tokenId, key, value); + } + + /** + * @notice Write a batch on the token. The caller must be able to write + * every token in it, and each entry follows the write-once + * rule, counting earlier entries in the batch. + */ + function setMetadataBatch( + uint256[] calldata tokenIds, + string[] calldata keys, + bytes[] calldata values + ) external { + uint256 length = tokenIds.length; + if (keys.length != length || values.length != length) { + revert BatchLengthMismatch(); + } + + bool writer = _writers[msg.sender]; + for (uint256 i = 0; i < length; ++i) { + uint256 tokenId = tokenIds[i]; + if (!writer) _checkDelegate(tokenId); + + bytes32 keyHash = keccak256(bytes(keys[i])); + if (!_writeOnceKeys[keyHash]) continue; + + // The value on the token, or one an earlier entry in this batch + // sets, makes the entry an overwrite. + if (token.metadata(tokenId, keys[i]).length != 0) { + revert WriteOnceValueSet(tokenId, keys[i]); + } + for (uint256 j = 0; j < i; ++j) { + if ( + tokenIds[j] == tokenId && values[j].length != 0 + && keccak256(bytes(keys[j])) == keyHash + ) { + revert WriteOnceValueSet(tokenId, keys[i]); + } + } + } + + token.setMetadataBatch(tokenIds, keys, values); + } + + /** + * @notice Set the token's authority and its settings, for example to + * hand the authority to a new policy. Only the admin can call + * this. + */ + function setCollectionAuthority( + address authority, + bool holderCanWrite, + bool ownerCannotWrite, + bool authorityLocked + ) external onlyOwner { + token.setCollectionAuthority( + authority, holderCanWrite, ownerCannotWrite, authorityLocked + ); + } + + /** + * @notice Renounce ownership. This also cancels a pending ownership + * transfer, so the pending owner can't accept it and take back + * a policy that was renounced. + */ + function renounceOwnership() public virtual override { + cancelOwnershipTransfer(); + super.renounceOwnership(); + } + + /** + * @dev Revert when `key` is write-once and `tokenId` already has a + * non-empty value for it on the token. + */ + function _checkWriteOnce(uint256 tokenId, string calldata key) + internal + view + { + if ( + _writeOnceKeys[keccak256(bytes(key))] + && token.metadata(tokenId, key).length != 0 + ) { + revert WriteOnceValueSet(tokenId, key); + } + } + + /** + * @dev Revert unless the caller is `tokenId`'s delegate. + */ + function _checkDelegate(uint256 tokenId) internal view { + address delegate = delegateOf(tokenId); + if (delegate == address(0) || msg.sender != delegate) { + revert WriteUnauthorized(tokenId); + } + } + + /** + * @dev Returns `tokenId`'s holder, or the zero address when `ownerOf` + * reverts, as it does for a token that doesn't exist. + */ + function _holderOf(uint256 tokenId) internal view returns (address) { + try token.ownerOf(tokenId) returns (address holder) { + return holder; + } catch { + return address(0); + } + } +} diff --git a/src/test/MockAgentAdapter.sol b/src/test/MockAgentAdapter.sol new file mode 100644 index 00000000..41f71b60 --- /dev/null +++ b/src/test/MockAgentAdapter.sol @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.38; + +import { IAgentAdapter } from "../interfaces/IAgentAdapter.sol"; + +interface IOwnerOf { + function ownerOf(uint256 tokenId) external view returns (address); +} + +/** + * @dev An ERC-8217 adapter stand-in with the real adapter's registration + * rule for ERC-721 tokens: the token contract itself can register a + * token while `ownerOf` reverts or returns the zero address, and + * otherwise only the token's holder can. Like the real adapter, it + * does not stop a token from being registered twice. + */ +contract MockAgentAdapter is IAgentAdapter { + struct Binding { + address boundAddress; + uint256 tokenId; + string agentURI; + } + + error UnsupportedStandard(uint8 standard); + error NotController(address account); + + uint256 public nextAgentId = 1; + + uint256 public registrations; + + mapping(uint256 => Binding) public bindings; + + function register( + uint8 standard, + address boundAddress, + uint256 tokenId, + string calldata agentURI + ) external returns (uint256 agentId) { + if (standard != 0) { + revert UnsupportedStandard(standard); + } + + (bool success, bytes memory result) = boundAddress.staticcall( + abi.encodeCall(IOwnerOf.ownerOf, (tokenId)) + ); + address owner = success ? abi.decode(result, (address)) : address(0); + + bool contractPath = msg.sender == boundAddress && owner == address(0); + if (!contractPath && (owner == address(0) || msg.sender != owner)) { + revert NotController(msg.sender); + } + + agentId = nextAgentId++; + ++registrations; + bindings[agentId] = Binding(boundAddress, tokenId, agentURI); + } + + /// @dev Whether `account` controls `agentId`: the bound token's holder. + function isController(uint256 agentId, address account) + external + view + returns (bool) + { + Binding storage binding = bindings[agentId]; + return + IOwnerOf(binding.boundAddress).ownerOf(binding.tokenId) == account; + } +} diff --git a/test/foundry/ERC721SeaDropAgents.t.sol b/test/foundry/ERC721SeaDropAgents.t.sol new file mode 100644 index 00000000..244d2858 --- /dev/null +++ b/test/foundry/ERC721SeaDropAgents.t.sol @@ -0,0 +1,1327 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.38; + +import { TestHelper } from "test/foundry/utils/TestHelper.sol"; + +import { Vm } from "forge-std/Vm.sol"; + +import { + ERC721SeaDropAgents +} from "seadrop/extensions/ERC721SeaDropAgents.sol"; + +import { ERC8048OnchainMetadata } from "seadrop/lib/ERC8048OnchainMetadata.sol"; + +import { IERC8048Metadata } from "seadrop/interfaces/IERC8048Metadata.sol"; + +import { + IERC8048TokenMetadataAuthority +} from "seadrop/interfaces/IERC8048TokenMetadataAuthority.sol"; + +import { MetadataWriterPolicy } from "seadrop/lib/MetadataWriterPolicy.sol"; + +import { MockAgentAdapter } from "seadrop/test/MockAgentAdapter.sol"; + +import { TwoStepOwnable } from "utility-contracts/TwoStepOwnable.sol"; + +import { ERC721 } from "openzeppelin-contracts/token/ERC721/ERC721.sol"; + +import { + ERC721URIStorage +} from "openzeppelin-contracts/token/ERC721/extensions/ERC721URIStorage.sol"; + +contract ERC721SeaDropAgentsWithMint is ERC721SeaDropAgents { + constructor(address[] memory allowedSeaDrop, address adapter) + ERC721SeaDropAgents("Agents", "AGENT", allowedSeaDrop, adapter) + { } + + function mint(address to, uint256 quantity) public onlyOwner { + _mint(to, quantity); + } +} + +/// @dev Token ids start at 10 instead of 1. +contract ERC721SeaDropAgentsStartAtTen is ERC721SeaDropAgentsWithMint { + constructor(address[] memory allowedSeaDrop, address adapter) + ERC721SeaDropAgentsWithMint(allowedSeaDrop, adapter) + { } + + function _startTokenId() internal pure override returns (uint256) { + return 10; + } +} + +/// @dev The parts of the deployed ERC-8217 adapter the fork test reads. +interface IAgentAdapterView { + struct Binding { + uint8 standard; + address boundAddress; + uint256 tokenId; + } + + function bindingOf(uint256 agentId) external view returns (Binding memory); + + function isController(uint256 agentId, address account) + external + view + returns (bool); + + function tokenURI(uint256 agentId) external view returns (string memory); +} + +/// @dev ERC8048OnchainMetadata next to OpenZeppelin's ERC721URIStorage, +/// which declares ERC-4906's events itself. +contract URIStorageWithOnchainMetadata is + ERC721URIStorage, + ERC8048OnchainMetadata +{ + address internal immutable _ADMIN = msg.sender; + + constructor() ERC721("Reuse", "REUSE") { } + + function mint(address to, uint256 tokenId) external { + _mint(to, tokenId); + } + + function supportsInterface(bytes4 interfaceId) + public + view + override + returns (bool) + { + return interfaceId == type(IERC8048Metadata).interfaceId + || super.supportsInterface(interfaceId); + } + + function _isMetadataAdmin(address account) + internal + view + override + returns (bool) + { + return account == _ADMIN; + } + + function _metadataHolderOf(uint256 tokenId) + internal + view + override + returns (address) + { + return _ownerOf(tokenId); + } + + function _emitMetadataUpdate(uint256 tokenId) internal override { + if (_exists(tokenId)) { + emit MetadataUpdate(tokenId); + } + } +} + +contract ERC721SeaDropAgentsTest is TestHelper { + bytes32 constant METADATA_SET = + keccak256("MetadataSet(uint256,string,string,bytes)"); + bytes32 constant METADATA_UPDATE = keccak256("MetadataUpdate(uint256)"); + bytes32 constant AUTHORITY_SET = + keccak256("TokenMetadataAuthoritySet(address)"); + bytes32 constant SETTINGS_UPDATED = + keccak256("CollectionAuthoritySettingsUpdated(bool,bool,bool)"); + + MockAgentAdapter adapter; + ERC721SeaDropAgentsWithMint agents; + + address holder = makeAddr("holder"); + address otherHolder = makeAddr("otherHolder"); + address writer = makeAddr("writer"); + address agentWallet = makeAddr("agentWallet"); + address stranger = makeAddr("stranger"); + address policyAdmin = makeAddr("policyAdmin"); + + function setUp() public { + adapter = new MockAgentAdapter(); + agents = _deploy(address(adapter)); + agents.setMaxSupply(100); + } + + function _deploy(address adapter_) + internal + returns (ERC721SeaDropAgentsWithMint) + { + address[] memory allowedSeaDrop = new address[](1); + allowedSeaDrop[0] = address(seadrop); + return new ERC721SeaDropAgentsWithMint(allowedSeaDrop, adapter_); + } + + /// @dev Deploys a MetadataWriterPolicy for `agents` that `policyAdmin` + /// runs. + function _deployPolicy() internal returns (MetadataWriterPolicy policy) { + vm.prank(policyAdmin); + policy = new MetadataWriterPolicy(address(agents)); + } + + function _writeUnauthorized(uint256 tokenId) + internal + pure + returns (bytes memory) + { + return abi.encodeWithSelector( + ERC8048OnchainMetadata.MetadataWriteUnauthorized.selector, tokenId + ); + } + + function _policyWriteUnauthorized(uint256 tokenId) + internal + pure + returns (bytes memory) + { + return abi.encodeWithSelector( + MetadataWriterPolicy.WriteUnauthorized.selector, tokenId + ); + } + + function _writeOnceValueSet(uint256 tokenId, string memory key) + internal + pure + returns (bytes memory) + { + return abi.encodeWithSelector( + MetadataWriterPolicy.WriteOnceValueSet.selector, tokenId, key + ); + } + + function _assertCollectionAuthority( + address authority, + bool holderCanWrite, + bool ownerCannotWrite, + bool authorityLocked + ) internal view { + assertEq(agents.tokenMetadataAuthority(), authority); + (bool canWrite, bool ownerOut, bool locked) = + agents.collectionAuthoritySettings(); + assertEq(canWrite, holderCanWrite); + assertEq(ownerOut, ownerCannotWrite); + assertEq(locked, authorityLocked); + } + + /// @dev Counts the logs with `topic` emitted by the token contract. + function _count(Vm.Log[] memory logs, bytes32 topic) + internal + view + returns (uint256 count) + { + for (uint256 i = 0; i < logs.length; ++i) { + if ( + logs[i].emitter == address(agents) && logs[i].topics[0] == topic + ) { + ++count; + } + } + } + + function testSupportsInterface() public view { + assertTrue(agents.supportsInterface(0xdf670be1)); + assertEq(type(IERC8048Metadata).interfaceId, bytes4(0xdf670be1)); + // ERC-8048's Metadata Authority extension, collection-wide. + assertTrue(agents.supportsInterface(0x04f90b41)); + assertEq( + type(IERC8048TokenMetadataAuthority).interfaceId, bytes4(0x04f90b41) + ); + // Not the earlier per-token authority draft. + assertFalse(agents.supportsInterface(0xf9cb127d)); + // ERC-4906, ERC-721 and ERC-165 still answer. + assertTrue(agents.supportsInterface(0x49064906)); + assertTrue(agents.supportsInterface(0x80ac58cd)); + assertTrue(agents.supportsInterface(0x01ffc9a7)); + assertFalse(agents.supportsInterface(0xffffffff)); + } + + function testOwnerSetsMetadataBeforeAndAfterMint() public { + // Before the token exists: MetadataSet, but no ERC-4906 refresh + // for a token that isn't there yet. + vm.recordLogs(); + vm.expectEmit(true, true, false, true, address(agents)); + emit IERC8048Metadata.MetadataSet(1, "context", "context", "lore"); + agents.setMetadata(1, "context", "lore"); + assertEq(_count(vm.getRecordedLogs(), METADATA_UPDATE), 0); + assertEq(agents.metadata(1, "context"), bytes("lore")); + + // After mint, every write refreshes the token too. + agents.mint(holder, 1); + vm.expectEmit(true, true, false, true, address(agents)); + emit IERC8048Metadata.MetadataSet( + 1, + "endpoint[web]", + "endpoint[web]", + "https://agent.example" + ); + vm.expectEmit(false, false, false, true, address(agents)); + emit ERC721SeaDropAgents.MetadataUpdate(1); + agents.setMetadata(1, "endpoint[web]", "https://agent.example"); + assertEq( + agents.metadata(1, "endpoint[web]"), bytes("https://agent.example") + ); + + // Keys are exact bytes. + assertEq(agents.metadata(1, "endpoint[WEB]").length, 0); + + // An empty value clears the key. + agents.setMetadata(1, "context", ""); + assertEq(agents.metadata(1, "context").length, 0); + } + + /// @dev State 1: a blank authority with the settings false. Only the + /// owner writes. + function testOwnerOnlyByDefault() public { + _assertCollectionAuthority(address(0), false, false, false); + agents.mint(holder, 1); + + vm.prank(stranger); + vm.expectRevert(_writeUnauthorized(1)); + agents.setMetadata(1, "context", "x"); + + vm.prank(holder); + vm.expectRevert(_writeUnauthorized(1)); + agents.setMetadata(1, "context", "x"); + + agents.setMetadata(1, "context", "owner"); + assertEq(agents.metadata(1, "context"), bytes("owner")); + + // A new owner takes over a blank authority. + agents.transferOwnership(otherHolder); + vm.prank(otherHolder); + agents.acceptOwnership(); + vm.expectRevert(_writeUnauthorized(1)); + agents.setMetadata(1, "context", "old owner"); + vm.prank(otherHolder); + agents.setMetadata(1, "context", "new owner"); + } + + function testOnlyOwnerOrAuthoritySetsCollectionAuthority() public { + agents.mint(holder, 1); + + // Not a stranger, a holder, or an approved operator. + vm.prank(stranger); + vm.expectRevert( + ERC8048OnchainMetadata.CollectionAuthorityUnauthorized.selector + ); + agents.setCollectionAuthority(stranger, true, false, false); + + vm.prank(holder); + vm.expectRevert( + ERC8048OnchainMetadata.CollectionAuthorityUnauthorized.selector + ); + agents.setCollectionAuthority(address(0), true, false, false); + + vm.prank(holder); + agents.setApprovalForAll(stranger, true); + vm.prank(stranger); + vm.expectRevert( + ERC8048OnchainMetadata.CollectionAuthorityUnauthorized.selector + ); + agents.setCollectionAuthority(address(0), true, false, false); + + // The owner sets the authority and settings at once, with events. + vm.expectEmit(true, false, false, true, address(agents)); + emit IERC8048TokenMetadataAuthority.TokenMetadataAuthoritySet(writer); + vm.expectEmit(false, false, false, true, address(agents)); + emit ERC8048OnchainMetadata.CollectionAuthoritySettingsUpdated( + true, + false, + false + ); + agents.setCollectionAuthority(writer, true, false, false); + _assertCollectionAuthority(writer, true, false, false); + + // The authority can change them too. + vm.prank(writer); + agents.setCollectionAuthority(agentWallet, false, false, false); + _assertCollectionAuthority(agentWallet, false, false, false); + + // A former authority can't. + vm.prank(writer); + vm.expectRevert( + ERC8048OnchainMetadata.CollectionAuthorityUnauthorized.selector + ); + agents.setCollectionAuthority(writer, false, false, false); + + // The owner can return it to blank. + agents.setCollectionAuthority(address(0), false, false, false); + _assertCollectionAuthority(address(0), false, false, false); + } + + function testAuthoritySetEmitsOnlyOnChange() public { + // Settings alone leave the authority blank, so no authority event. + vm.recordLogs(); + agents.setCollectionAuthority(address(0), true, false, false); + Vm.Log[] memory logs = vm.getRecordedLogs(); + assertEq(_count(logs, AUTHORITY_SET), 0); + assertEq(_count(logs, SETTINGS_UPDATED), 1); + + // Setting, keeping, and clearing an authority. + vm.recordLogs(); + agents.setCollectionAuthority(writer, false, false, false); + assertEq(_count(vm.getRecordedLogs(), AUTHORITY_SET), 1); + vm.recordLogs(); + agents.setCollectionAuthority(writer, true, false, false); + assertEq(_count(vm.getRecordedLogs(), AUTHORITY_SET), 0); + vm.expectEmit(true, false, false, true, address(agents)); + emit IERC8048TokenMetadataAuthority.TokenMetadataAuthoritySet(address( + 0 + )); + agents.setCollectionAuthority(address(0), false, false, false); + } + + /// @dev State 3: a locked blank authority with holders on. The owner + /// and holders write for good, and nobody adds a policy. + function testLockedBlankOwnerAndHolders() public { + agents.mint(holder, 1); + vm.expectEmit(false, false, false, true, address(agents)); + emit ERC8048OnchainMetadata.CollectionAuthoritySettingsUpdated( + true, + false, + true + ); + agents.setCollectionAuthority(address(0), true, false, true); + _assertCollectionAuthority(address(0), true, false, true); + + agents.setMetadata(1, "context", "owner"); + vm.prank(holder); + agents.setMetadata(1, "context", "holder"); + + // The owner writes as the blank authority but can't change locked + // settings or set a policy. + vm.expectRevert( + ERC8048OnchainMetadata.CollectionAuthorityIsLocked.selector + ); + agents.setCollectionAuthority(address(0), false, false, false); + MetadataWriterPolicy policy = _deployPolicy(); + vm.expectRevert( + ERC8048OnchainMetadata.CollectionAuthorityIsLocked.selector + ); + agents.setCollectionAuthority(address(policy), false, false, true); + vm.prank(holder); + vm.expectRevert( + ERC8048OnchainMetadata.CollectionAuthorityUnauthorized.selector + ); + agents.setCollectionAuthority(holder, false, false, false); + } + + /// @dev State 3: a locked blank authority with the owner shut out and + /// holders on. Holders control their records for good. + function testLockedBlankHoldersOnly() public { + agents.mint(holder, 1); + agents.setMetadata(1, "context", "owner lore"); + agents.setCollectionAuthority(address(0), true, true, true); + _assertCollectionAuthority(address(0), true, true, true); + + // Nobody changes the settings again. + vm.expectRevert( + ERC8048OnchainMetadata.CollectionAuthorityIsLocked.selector + ); + agents.setCollectionAuthority(address(0), false, false, false); + vm.prank(holder); + vm.expectRevert( + ERC8048OnchainMetadata.CollectionAuthorityUnauthorized.selector + ); + agents.setCollectionAuthority(holder, true, true, true); + + // The owner can't write. + vm.expectRevert(_writeUnauthorized(1)); + agents.setMetadata(1, "context", "owner again"); + + // The holder writes, and after a sale the buyer does. + vm.prank(holder); + agents.setMetadata(1, "context", "holder lore"); + vm.prank(holder); + agents.transferFrom(holder, otherHolder, 1); + vm.prank(otherHolder); + agents.setMetadata(1, "context", "buyer lore"); + assertEq(agents.metadata(1, "context"), bytes("buyer lore")); + vm.prank(holder); + vm.expectRevert(_writeUnauthorized(1)); + agents.setMetadata(1, "context", "seller lore"); + + // A new owner can't take it back either. + agents.transferOwnership(stranger); + vm.prank(stranger); + agents.acceptOwnership(); + vm.prank(stranger); + vm.expectRevert(_writeUnauthorized(1)); + agents.setMetadata(1, "context", "new owner"); + vm.prank(stranger); + vm.expectRevert( + ERC8048OnchainMetadata.CollectionAuthorityIsLocked.selector + ); + agents.setCollectionAuthority(address(0), false, false, false); + } + + function testOwnerCannotWriteUnlocked() public { + agents.mint(holder, 1); + agents.setCollectionAuthority(address(0), false, true, false); + + // Shut out of writing, nobody else writes either. + vm.expectRevert(_writeUnauthorized(1)); + agents.setMetadata(1, "context", "x"); + vm.prank(holder); + vm.expectRevert(_writeUnauthorized(1)); + agents.setMetadata(1, "context", "x"); + + // The owner still changes the settings while they aren't locked. + agents.setCollectionAuthority(address(0), false, false, false); + agents.setMetadata(1, "context", "back"); + assertEq(agents.metadata(1, "context"), bytes("back")); + } + + function testLockedAuthorityCanClearToLockedBlank() public { + agents.setCollectionAuthority(writer, false, false, true); + + // The authority hands the collection to a locked blank state that + // holders write. + agents.mint(holder, 1); + vm.prank(writer); + agents.setCollectionAuthority(address(0), true, true, true); + _assertCollectionAuthority(address(0), true, true, true); + + // The former authority and the owner are both out for good. + vm.prank(writer); + vm.expectRevert( + ERC8048OnchainMetadata.CollectionAuthorityUnauthorized.selector + ); + agents.setCollectionAuthority(writer, false, false, false); + vm.expectRevert( + ERC8048OnchainMetadata.CollectionAuthorityIsLocked.selector + ); + agents.setCollectionAuthority(writer, false, false, false); + vm.prank(holder); + agents.setMetadata(1, "context", "holder"); + } + + function testWritesBeforeMint() public { + agents.setCollectionAuthority(address(0), true, false, false); + + // The authority writes a token that isn't minted. + agents.setMetadata(5, "context", "lore"); + assertEq(agents.metadata(5, "context"), bytes("lore")); + + // Nobody is its holder yet. + vm.prank(holder); + vm.expectRevert(_writeUnauthorized(5)); + agents.setMetadata(5, "context", "x"); + vm.prank(address(0)); + vm.expectRevert(_writeUnauthorized(5)); + agents.setMetadata(5, "context", "x"); + + // A policy authority writes before mint too. + MetadataWriterPolicy policy = _deployPolicy(); + agents.setCollectionAuthority(address(policy), false, false, false); + vm.prank(policyAdmin); + policy.setWriter(writer, true); + vm.prank(writer); + policy.setMetadata(6, "context", "policy lore"); + assertEq(agents.metadata(6, "context"), bytes("policy lore")); + + // Nobody can delegate a token that isn't minted. + vm.prank(holder); + vm.expectRevert( + abi.encodeWithSelector( + MetadataWriterPolicy.NotTokenHolder.selector, 6 + ) + ); + policy.setDelegate(6, agentWallet); + assertEq(policy.delegateOf(6), address(0)); + } + + /// @dev State 4: a city and its homeowners. A policy contract is the + /// authority, holders write only under its rules, and the owner + /// can replace it. + function testPolicyAuthority() public { + agents.mint(holder, 1); + MetadataWriterPolicy city = _deployPolicy(); + agents.setCollectionAuthority(address(city), false, false, false); + + // Neither the holder nor the owner writes past the policy. + _assertCollectionAuthority(address(city), false, false, false); + vm.prank(holder); + vm.expectRevert(_writeUnauthorized(1)); + agents.setMetadata(1, "context", "x"); + vm.expectRevert(_writeUnauthorized(1)); + agents.setMetadata(1, "context", "x"); + + // The holder writes through the policy, under its rules. + vm.prank(holder); + city.setDelegate(1, holder); + vm.prank(holder); + city.setMetadata(1, "context", "homeowner"); + assertEq(agents.metadata(1, "context"), bytes("homeowner")); + + // The owner replaces the policy, and the old one can't write. + MetadataWriterPolicy newCity = _deployPolicy(); + agents.setCollectionAuthority(address(newCity), false, false, false); + _assertCollectionAuthority(address(newCity), false, false, false); + vm.prank(holder); + vm.expectRevert(_writeUnauthorized(1)); + city.setMetadata(1, "context", "old city"); + } + + /// @dev While an authority is set, it is the only writer, whatever + /// the settings say. + function testAuthorityIsOnlyWriter() public { + agents.mint(holder, 1); + agents.setCollectionAuthority(writer, true, false, false); + + vm.prank(holder); + vm.expectRevert(_writeUnauthorized(1)); + agents.setMetadata(1, "context", "holder"); + vm.expectRevert(_writeUnauthorized(1)); + agents.setMetadata(1, "context", "owner"); + vm.prank(writer); + agents.setMetadata(1, "context", "authority"); + + // Cleared, the same settings let the holder and owner write again. + agents.setCollectionAuthority(address(0), true, false, false); + vm.prank(holder); + agents.setMetadata(1, "context", "holder"); + agents.setMetadata(1, "context", "owner"); + vm.prank(writer); + vm.expectRevert(_writeUnauthorized(1)); + agents.setMetadata(1, "context", "former authority"); + } + + /// @dev State 2: holders write their own tokens, and the owner can + /// change the rules. Transfers need no claim. + function testHoldersWrite() public { + agents.mint(holder, 1); + agents.mint(otherHolder, 1); + agents.setCollectionAuthority(address(0), true, false, false); + + vm.prank(holder); + agents.setMetadata(1, "endpoint[mcp]", "mcp://seller"); + assertEq(agents.metadata(1, "endpoint[mcp]"), bytes("mcp://seller")); + + // Not another holder's token, nor through an operator approval. + vm.prank(holder); + vm.expectRevert(_writeUnauthorized(2)); + agents.setMetadata(2, "context", "x"); + vm.prank(holder); + agents.setApprovalForAll(stranger, true); + vm.prank(stranger); + vm.expectRevert(_writeUnauthorized(1)); + agents.setMetadata(1, "context", "x"); + + // The owner still writes every token. + agents.setMetadata(2, "context", "owner"); + + // A transfer changes nothing in the settings and emits no + // authority event. + vm.recordLogs(); + vm.prank(holder); + agents.transferFrom(holder, otherHolder, 1); + Vm.Log[] memory logs = vm.getRecordedLogs(); + assertEq(_count(logs, AUTHORITY_SET), 0); + assertEq(_count(logs, SETTINGS_UPDATED), 0); + _assertCollectionAuthority(address(0), true, false, false); + + // The records stay with the token. + assertEq(agents.metadata(1, "endpoint[mcp]"), bytes("mcp://seller")); + + // The new holder writes right away, and the old holder can't. + vm.prank(otherHolder); + agents.setMetadata(1, "endpoint[mcp]", "mcp://buyer"); + vm.prank(holder); + vm.expectRevert(_writeUnauthorized(1)); + agents.setMetadata(1, "endpoint[mcp]", "mcp://seller"); + + // The owner changes the rules back. + agents.setCollectionAuthority(address(0), false, false, false); + vm.prank(otherHolder); + vm.expectRevert(_writeUnauthorized(1)); + agents.setMetadata(1, "endpoint[mcp]", "mcp://buyer"); + } + + function testHolderWriteFollowsOnlyTheMovedToken() public { + // One batch mint of two tokens. + agents.mint(holder, 2); + agents.setCollectionAuthority(address(0), true, false, false); + + vm.prank(holder); + agents.safeTransferFrom(holder, otherHolder, 2); + + vm.startPrank(holder); + agents.setMetadata(1, "context", "still mine"); + vm.expectRevert(_writeUnauthorized(2)); + agents.setMetadata(2, "context", "x"); + vm.stopPrank(); + + vm.prank(otherHolder); + agents.setMetadata(2, "context", "mine now"); + } + + function testBurnedTokenHasNoHolder() public { + agents.mint(holder, 1); + agents.setCollectionAuthority(address(0), true, false, false); + + vm.prank(holder); + agents.burn(1); + + vm.prank(holder); + vm.expectRevert(_writeUnauthorized(1)); + agents.setMetadata(1, "context", "x"); + + // The records stay, and the owner can still write them, without + // refreshing a token that no longer exists. + vm.recordLogs(); + agents.setMetadata(1, "context", "retired"); + assertEq(_count(vm.getRecordedLogs(), METADATA_UPDATE), 0); + assertEq(agents.metadata(1, "context"), bytes("retired")); + } + + /// @dev State 5: a locked policy. The owner can't replace it, and only + /// the policy can hand the authority on. + function testLockedPolicy() public { + agents.mint(holder, 1); + MetadataWriterPolicy policy = _deployPolicy(); + agents.setCollectionAuthority(address(policy), false, false, true); + + vm.expectRevert( + ERC8048OnchainMetadata.CollectionAuthorityIsLocked.selector + ); + agents.setCollectionAuthority(address(0), false, false, false); + vm.expectRevert(_writeUnauthorized(1)); + agents.setMetadata(1, "context", "x"); + + // The policy's admin, not the token owner, hands it on. + MetadataWriterPolicy next = _deployPolicy(); + vm.expectRevert(TwoStepOwnable.OnlyOwner.selector); + policy.setCollectionAuthority(address(next), false, false, true); + + vm.expectEmit(true, false, false, true, address(agents)); + emit IERC8048TokenMetadataAuthority.TokenMetadataAuthoritySet(address( + next + )); + vm.prank(policyAdmin); + policy.setCollectionAuthority(address(next), false, false, true); + _assertCollectionAuthority(address(next), false, false, true); + + // The old policy is out, and the owner is still locked out. + vm.prank(policyAdmin); + vm.expectRevert( + ERC8048OnchainMetadata.CollectionAuthorityUnauthorized.selector + ); + policy.setCollectionAuthority(address(policy), false, false, true); + vm.expectRevert( + ERC8048OnchainMetadata.CollectionAuthorityIsLocked.selector + ); + agents.setCollectionAuthority(address(policy), false, false, false); + } + + function testOwnerAsLockedAuthority() public { + // An owner named as the locked authority is the authority, so it + // still changes the settings, until ownership moves. + agents.setCollectionAuthority(address(this), false, false, true); + agents.setCollectionAuthority(address(this), true, false, true); + agents.setMetadata(1, "context", "x"); + + agents.transferOwnership(otherHolder); + vm.prank(otherHolder); + agents.acceptOwnership(); + vm.prank(otherHolder); + vm.expectRevert( + ERC8048OnchainMetadata.CollectionAuthorityIsLocked.selector + ); + agents.setCollectionAuthority(otherHolder, true, false, true); + agents.setMetadata(1, "context", "former owner, still authority"); + } + + function testSetMetadataBatch() public { + uint256[] memory tokenIds = new uint256[](4); + string[] memory keys = new string[](4); + bytes[] memory values = new bytes[](4); + (tokenIds[0], keys[0], values[0]) = (1, "context", "one"); + (tokenIds[1], keys[1], values[1]) = (1, "endpoint[mcp]", "mcp://one"); + (tokenIds[2], keys[2], values[2]) = (2, "context", "two"); + (tokenIds[3], keys[3], values[3]) = (1, "endpoint[a2a]", "a2a://one"); + + // Before mint, the batch emits no ERC-4906 refreshes. + vm.recordLogs(); + agents.setMetadataBatch(tokenIds, keys, values); + Vm.Log[] memory logs = vm.getRecordedLogs(); + assertEq(_count(logs, METADATA_SET), 4); + assertEq(_count(logs, METADATA_UPDATE), 0); + + agents.mint(holder, 2); + vm.recordLogs(); + agents.setMetadataBatch(tokenIds, keys, values); + logs = vm.getRecordedLogs(); + + assertEq(agents.metadata(1, "context"), bytes("one")); + assertEq(agents.metadata(1, "endpoint[mcp]"), bytes("mcp://one")); + assertEq(agents.metadata(2, "context"), bytes("two")); + assertEq(agents.metadata(1, "endpoint[a2a]"), bytes("a2a://one")); + + // One MetadataSet per entry, one MetadataUpdate per run of entries + // for the same token: [1, 1], [2], [1]. + assertEq(_count(logs, METADATA_SET), 4); + assertEq(_count(logs, METADATA_UPDATE), 3); + + string[] memory shortKeys = new string[](3); + vm.expectRevert( + ERC8048OnchainMetadata.MetadataBatchLengthMismatch.selector + ); + agents.setMetadataBatch(tokenIds, shortKeys, values); + + bytes[] memory shortValues = new bytes[](3); + vm.expectRevert( + ERC8048OnchainMetadata.MetadataBatchLengthMismatch.selector + ); + agents.setMetadataBatch(tokenIds, keys, shortValues); + + // A holder batches their own tokens. + agents.setCollectionAuthority(address(0), true, false, false); + values[0] = "holder"; + vm.prank(holder); + agents.setMetadataBatch(tokenIds, keys, values); + assertEq(agents.metadata(1, "context"), bytes("holder")); + + // One bad entry reverts the whole batch. + vm.prank(holder); + agents.transferFrom(holder, otherHolder, 2); + values[0] = "changed"; + vm.prank(holder); + vm.expectRevert(_writeUnauthorized(2)); + agents.setMetadataBatch(tokenIds, keys, values); + assertEq(agents.metadata(1, "context"), bytes("holder")); + } + + /// @dev State 3 with nobody writing: a locked blank authority with + /// the owner shut out and holders off freezes every record. + function testFreezeEverything() public { + agents.mint(holder, 1); + agents.setMetadata(1, "context", "final"); + agents.setMetadata(2, "context", "final before mint"); + agents.setCollectionAuthority(address(0), false, true, true); + + // Nobody writes any token, minted or not. + vm.expectRevert(_writeUnauthorized(1)); + agents.setMetadata(1, "context", "x"); + vm.prank(holder); + vm.expectRevert(_writeUnauthorized(1)); + agents.setMetadata(1, "context", "x"); + vm.expectRevert(_writeUnauthorized(2)); + agents.setMetadata(2, "context", "x"); + + // Nobody changes the settings back. + vm.expectRevert( + ERC8048OnchainMetadata.CollectionAuthorityIsLocked.selector + ); + agents.setCollectionAuthority(address(0), false, false, false); + vm.prank(holder); + vm.expectRevert( + ERC8048OnchainMetadata.CollectionAuthorityUnauthorized.selector + ); + agents.setCollectionAuthority(address(0), false, false, false); + + assertEq(agents.metadata(1, "context"), bytes("final")); + assertEq(agents.metadata(2, "context"), bytes("final before mint")); + } + + /// @dev Prem's case: an artist signs the first tokens, and tokens + /// minted later can still be signed once. + function testPolicyWriteOnceKey() public { + MetadataWriterPolicy policy = _deployPolicy(); + agents.setCollectionAuthority(address(policy), false, false, false); + address artist = makeAddr("artist"); + + vm.prank(stranger); + vm.expectRevert(TwoStepOwnable.OnlyOwner.selector); + policy.setWriteOnceKey("artist.signature", true); + + vm.startPrank(policyAdmin); + policy.setWriter(artist, true); + vm.expectEmit(true, false, false, true, address(policy)); + emit MetadataWriterPolicy.WriteOnceKeyUpdated( + "artist.signature", + "artist.signature", + true + ); + policy.setWriteOnceKey("artist.signature", true); + vm.stopPrank(); + assertTrue(policy.isWriteOnceKey("artist.signature")); + assertFalse(policy.isWriteOnceKey("context")); + + // The artist signs tokens 1 and 2. + agents.mint(holder, 2); + vm.startPrank(artist); + policy.setMetadata(1, "artist.signature", "sig1"); + policy.setMetadata(2, "artist.signature", "sig2"); + + // Nobody overwrites them, the artist included. + vm.expectRevert(_writeOnceValueSet(1, "artist.signature")); + policy.setMetadata(1, "artist.signature", "forged"); + vm.expectRevert(_writeOnceValueSet(2, "artist.signature")); + policy.setMetadata(2, "artist.signature", ""); + + // Other keys stay writable. + policy.setMetadata(1, "context", "one"); + policy.setMetadata(1, "context", "one, again"); + vm.stopPrank(); + + // Not the holder's delegate, and not the owner past the policy. + vm.prank(holder); + policy.setDelegate(1, agentWallet); + vm.prank(agentWallet); + vm.expectRevert(_writeOnceValueSet(1, "artist.signature")); + policy.setMetadata(1, "artist.signature", "forged"); + vm.expectRevert(_writeUnauthorized(1)); + agents.setMetadata(1, "artist.signature", "forged"); + + // Token 3 mints later and can still be signed, once. An empty + // write leaves it unsigned. + agents.mint(otherHolder, 1); + vm.startPrank(artist); + policy.setMetadata(3, "artist.signature", ""); + policy.setMetadata(3, "artist.signature", "sig3"); + vm.expectRevert(_writeOnceValueSet(3, "artist.signature")); + policy.setMetadata(3, "artist.signature", "sig3, again"); + vm.stopPrank(); + + assertEq(agents.metadata(1, "artist.signature"), bytes("sig1")); + assertEq(agents.metadata(2, "artist.signature"), bytes("sig2")); + assertEq(agents.metadata(3, "artist.signature"), bytes("sig3")); + + // The admin can unmark the key, so a lasting freeze locks the + // authority to the policy and renounces the policy. + agents.setCollectionAuthority(address(policy), false, false, true); + vm.prank(policyAdmin); + policy.renounceOwnership(); + vm.prank(policyAdmin); + vm.expectRevert(TwoStepOwnable.OnlyOwner.selector); + policy.setWriteOnceKey("artist.signature", false); + vm.expectRevert( + ERC8048OnchainMetadata.CollectionAuthorityIsLocked.selector + ); + agents.setCollectionAuthority(address(0), false, false, false); + vm.prank(artist); + vm.expectRevert(_writeOnceValueSet(1, "artist.signature")); + policy.setMetadata(1, "artist.signature", "forged"); + } + + function testPolicyWriteOnceKeyUnmarked() public { + MetadataWriterPolicy policy = _deployPolicy(); + agents.setCollectionAuthority(address(policy), false, false, false); + vm.startPrank(policyAdmin); + policy.setWriter(writer, true); + policy.setWriteOnceKey("artist.signature", true); + vm.stopPrank(); + + vm.prank(writer); + policy.setMetadata(1, "artist.signature", "sig1"); + + // While the admin can act, it can unmark the key. + vm.prank(policyAdmin); + policy.setWriteOnceKey("artist.signature", false); + assertFalse(policy.isWriteOnceKey("artist.signature")); + vm.prank(writer); + policy.setMetadata(1, "artist.signature", "sig1, fixed"); + assertEq(agents.metadata(1, "artist.signature"), bytes("sig1, fixed")); + } + + function testPolicyWriteOnceKeyBatch() public { + MetadataWriterPolicy policy = _deployPolicy(); + agents.setCollectionAuthority(address(policy), false, false, false); + vm.startPrank(policyAdmin); + policy.setWriter(writer, true); + policy.setWriteOnceKey("artist.signature", true); + vm.stopPrank(); + agents.mint(holder, 2); + + uint256[] memory tokenIds = new uint256[](2); + string[] memory keys = new string[](2); + bytes[] memory values = new bytes[](2); + (tokenIds[0], keys[0], values[0]) = (1, "artist.signature", "sig1"); + (tokenIds[1], keys[1], values[1]) = (2, "artist.signature", "sig2"); + + vm.startPrank(writer); + policy.setMetadataBatch(tokenIds, keys, values); + assertEq(agents.metadata(1, "artist.signature"), bytes("sig1")); + assertEq(agents.metadata(2, "artist.signature"), bytes("sig2")); + + // A batch can't overwrite a signature on the token. + (tokenIds[0], keys[0], values[0]) = (1, "context", "one"); + (tokenIds[1], keys[1], values[1]) = (1, "artist.signature", "forged"); + vm.expectRevert(_writeOnceValueSet(1, "artist.signature")); + policy.setMetadataBatch(tokenIds, keys, values); + + // Nor sign a token twice within the batch. + (tokenIds[0], keys[0], values[0]) = (3, "artist.signature", "sig3"); + (tokenIds[1], keys[1], values[1]) = (3, "artist.signature", "forged"); + vm.expectRevert(_writeOnceValueSet(3, "artist.signature")); + policy.setMetadataBatch(tokenIds, keys, values); + assertEq(agents.metadata(3, "artist.signature").length, 0); + + // Earlier entries count only for the same token and key, with a + // value. + uint256[] memory ids = new uint256[](4); + string[] memory ks = new string[](4); + bytes[] memory vs = new bytes[](4); + (ids[0], ks[0], vs[0]) = (3, "artist.signature", ""); + (ids[1], ks[1], vs[1]) = (4, "artist.signature", "sig4"); + (ids[2], ks[2], vs[2]) = (3, "context", "three"); + (ids[3], ks[3], vs[3]) = (3, "artist.signature", "sig3"); + policy.setMetadataBatch(ids, ks, vs); + assertEq(agents.metadata(3, "artist.signature"), bytes("sig3")); + assertEq(agents.metadata(4, "artist.signature"), bytes("sig4")); + + // The policy checks lengths before it reads entries. + string[] memory shortKeys = new string[](1); + vm.expectRevert(MetadataWriterPolicy.BatchLengthMismatch.selector); + policy.setMetadataBatch(tokenIds, shortKeys, values); + bytes[] memory shortValues = new bytes[](1); + vm.expectRevert(MetadataWriterPolicy.BatchLengthMismatch.selector); + policy.setMetadataBatch(tokenIds, keys, shortValues); + vm.stopPrank(); + } + + function testPolicyWriters() public { + MetadataWriterPolicy policy = _deployPolicy(); + assertEq(address(policy.token()), address(agents)); + agents.setCollectionAuthority(address(policy), false, false, false); + + vm.prank(stranger); + vm.expectRevert(TwoStepOwnable.OnlyOwner.selector); + policy.setWriter(writer, true); + + vm.expectEmit(true, false, false, true, address(policy)); + emit MetadataWriterPolicy.WriterUpdated(writer, true); + vm.prank(policyAdmin); + policy.setWriter(writer, true); + assertTrue(policy.isWriter(writer)); + assertFalse(policy.isWriter(stranger)); + + // A writer writes any token, minted or not, one at a time or in a + // batch. + agents.mint(holder, 1); + vm.startPrank(writer); + policy.setMetadata(7, "context", "written"); + policy.setMetadata(1, "context", "written"); + uint256[] memory tokenIds = new uint256[](2); + string[] memory keys = new string[](2); + bytes[] memory values = new bytes[](2); + (tokenIds[0], keys[0], values[0]) = (1, "endpoint[mcp]", "mcp://1"); + (tokenIds[1], keys[1], values[1]) = (7, "endpoint[mcp]", "mcp://7"); + policy.setMetadataBatch(tokenIds, keys, values); + vm.stopPrank(); + assertEq(agents.metadata(7, "context"), bytes("written")); + assertEq(agents.metadata(1, "endpoint[mcp]"), bytes("mcp://1")); + assertEq(agents.metadata(7, "endpoint[mcp]"), bytes("mcp://7")); + + // A writer can't do anything else the admins can. + vm.startPrank(writer); + vm.expectRevert(TwoStepOwnable.OnlyOwner.selector); + agents.setBaseURI("ipfs://other/"); + vm.expectRevert( + ERC8048OnchainMetadata.CollectionAuthorityUnauthorized.selector + ); + agents.setCollectionAuthority(writer, false, false, false); + vm.expectRevert(TwoStepOwnable.OnlyOwner.selector); + policy.setWriteOnceKey("context", true); + vm.expectRevert(TwoStepOwnable.OnlyOwner.selector); + policy.setWriter(stranger, true); + vm.stopPrank(); + + // Strangers can't write through the policy. + vm.prank(stranger); + vm.expectRevert(_policyWriteUnauthorized(7)); + policy.setMetadata(7, "context", "x"); + + vm.prank(policyAdmin); + policy.setWriter(writer, false); + assertFalse(policy.isWriter(writer)); + vm.prank(writer); + vm.expectRevert(_policyWriteUnauthorized(7)); + policy.setMetadata(7, "endpoint[mcp]", "again"); + } + + function testPolicyHolderDelegate() public { + MetadataWriterPolicy policy = _deployPolicy(); + agents.setCollectionAuthority(address(policy), false, false, false); + agents.mint(holder, 2); + + // Only the token's holder delegates, not an operator or the + // policy's admin. + vm.prank(holder); + agents.setApprovalForAll(stranger, true); + bytes memory notHolder = abi.encodeWithSelector( + MetadataWriterPolicy.NotTokenHolder.selector, 1 + ); + vm.prank(stranger); + vm.expectRevert(notHolder); + policy.setDelegate(1, stranger); + vm.prank(policyAdmin); + vm.expectRevert(notHolder); + policy.setDelegate(1, policyAdmin); + + vm.expectEmit(true, true, true, true, address(policy)); + emit MetadataWriterPolicy.DelegateSet(1, holder, agentWallet); + vm.prank(holder); + policy.setDelegate(1, agentWallet); + assertEq(policy.delegateOf(1), agentWallet); + assertEq(policy.delegateOf(2), address(0)); + + // The agent's wallet writes its token, and not the holder's other + // token. + vm.startPrank(agentWallet); + policy.setMetadata(1, "endpoint[mcp]", "mcp://agent"); + vm.expectRevert(_policyWriteUnauthorized(2)); + policy.setMetadata(2, "endpoint[mcp]", "mcp://agent"); + + uint256[] memory tokenIds = new uint256[](2); + string[] memory keys = new string[](2); + bytes[] memory values = new bytes[](2); + (tokenIds[0], keys[0], values[0]) = (1, "context", "agent lore"); + (tokenIds[1], keys[1], values[1]) = (1, "endpoint[a2a]", "a2a://1"); + policy.setMetadataBatch(tokenIds, keys, values); + tokenIds[1] = 2; + vm.expectRevert(_policyWriteUnauthorized(2)); + policy.setMetadataBatch(tokenIds, keys, values); + vm.stopPrank(); + assertEq(agents.metadata(1, "endpoint[mcp]"), bytes("mcp://agent")); + assertEq(agents.metadata(1, "endpoint[a2a]"), bytes("a2a://1")); + + // The agent's wallet can't write the token directly. + vm.prank(agentWallet); + vm.expectRevert(_writeUnauthorized(1)); + agents.setMetadata(1, "context", "x"); + + // The delegation lapses when the token is sold. + vm.prank(holder); + agents.transferFrom(holder, otherHolder, 1); + assertEq(policy.delegateOf(1), address(0)); + vm.prank(agentWallet); + vm.expectRevert(_policyWriteUnauthorized(1)); + policy.setMetadata(1, "endpoint[mcp]", "mcp://seller"); + + // The old holder can't delegate it again, and the buyer can. + vm.prank(holder); + vm.expectRevert(notHolder); + policy.setDelegate(1, agentWallet); + vm.prank(otherHolder); + policy.setDelegate(1, writer); + vm.prank(writer); + policy.setMetadata(1, "endpoint[mcp]", "mcp://buyer"); + + // Clearing it with the zero address. + vm.prank(otherHolder); + policy.setDelegate(1, address(0)); + assertEq(policy.delegateOf(1), address(0)); + vm.prank(writer); + vm.expectRevert(_policyWriteUnauthorized(1)); + policy.setMetadata(1, "endpoint[mcp]", "x"); + + // A burned token has no holder, so no delegate. + vm.prank(holder); + policy.setDelegate(2, agentWallet); + vm.prank(holder); + agents.burn(2); + assertEq(policy.delegateOf(2), address(0)); + vm.prank(agentWallet); + vm.expectRevert(_policyWriteUnauthorized(2)); + policy.setMetadata(2, "context", "x"); + } + + function testPolicyRenounceCancelsPendingOwner() public { + MetadataWriterPolicy policy = _deployPolicy(); + agents.setCollectionAuthority(address(policy), false, false, true); + + vm.startPrank(policyAdmin); + policy.transferOwnership(stranger); + policy.renounceOwnership(); + vm.stopPrank(); + assertEq(policy.owner(), address(0)); + + // The pending owner can't take back the renounced policy. + vm.prank(stranger); + vm.expectRevert(TwoStepOwnable.NotNextOwner.selector); + policy.acceptOwnership(); + vm.prank(stranger); + vm.expectRevert(TwoStepOwnable.OnlyOwner.selector); + policy.setWriter(stranger, true); + vm.prank(stranger); + vm.expectRevert(TwoStepOwnable.OnlyOwner.selector); + policy.setCollectionAuthority(stranger, false, false, false); + } + + function testReusableNextToOpenZeppelinERC4906() public { + URIStorageWithOnchainMetadata reuse = + new URIStorageWithOnchainMetadata(); + reuse.mint(holder, 7); + + vm.expectEmit(true, true, true, true, address(reuse)); + emit ERC721SeaDropAgents.MetadataUpdate(7); + reuse.setMetadata(7, "context", "hello"); + assertEq(reuse.metadata(7, "context"), bytes("hello")); + + vm.prank(holder); + vm.expectRevert(_writeUnauthorized(7)); + reuse.setMetadata(7, "context", "bye"); + + reuse.setCollectionAuthority(address(0), true, false, false); + vm.prank(holder); + reuse.setMetadata(7, "context", "bye"); + assertEq(reuse.metadata(7, "context"), bytes("bye")); + } + + function testRegisterAgents() public { + agents.registerAgents(1, 3, "https://agents.example/", ".json"); + + assertEq(adapter.registrations(), 3); + for (uint256 tokenId = 1; tokenId <= 3; ++tokenId) { + (bool registered, uint256 agentId) = agents.agentOf(tokenId); + assertTrue(registered); + assertEq(agentId, tokenId); + (address bound, uint256 boundTokenId, string memory agentURI) = + adapter.bindings(agentId); + assertEq(bound, address(agents)); + assertEq(boundTokenId, tokenId); + assertEq( + agentURI, + string.concat( + "https://agents.example/", vm.toString(tokenId), ".json" + ) + ); + } + (bool none,) = agents.agentOf(4); + assertFalse(none); + + // A repeated or overlapping range skips registered tokens. + agents.registerAgents(2, 5, "https://agents.example/", ".json"); + assertEq(adapter.registrations(), 5); + (, uint256 agentFive) = agents.agentOf(5); + assertEq(agentFive, 5); + + // The holder controls the agent after mint. + agents.mint(holder, 1); + (, uint256 agentOne) = agents.agentOf(1); + assertTrue(adapter.isController(agentOne, holder)); + assertFalse(adapter.isController(agentOne, address(agents))); + } + + function testRegisterAgentsRanges() public { + agents.mint(holder, 2); + + // Minted tokens can't be registered by the contract. + vm.expectRevert( + abi.encodeWithSelector( + ERC721SeaDropAgents.InvalidAgentTokenIdRange.selector, 2, 4 + ) + ); + agents.registerAgents(2, 4, "", ""); + + // Empty range. + vm.expectRevert( + abi.encodeWithSelector( + ERC721SeaDropAgents.InvalidAgentTokenIdRange.selector, 5, 4 + ) + ); + agents.registerAgents(5, 4, "", ""); + + // Past the max supply. + vm.expectRevert( + abi.encodeWithSelector( + ERC721SeaDropAgents.InvalidAgentTokenIdRange.selector, 99, 101 + ) + ); + agents.registerAgents(99, 101, "", ""); + + // The next token to mint, up to the max supply, is fine. + agents.registerAgents(3, 3, "", ""); + agents.registerAgents(100, 100, "", ""); + assertEq(adapter.registrations(), 2); + } + + function testRegisterAgentsRangeFollowsStartTokenId() public { + address[] memory allowedSeaDrop = new address[](1); + allowedSeaDrop[0] = address(seadrop); + ERC721SeaDropAgentsStartAtTen tens = + new ERC721SeaDropAgentsStartAtTen(allowedSeaDrop, address(adapter)); + tens.setMaxSupply(100); + + // Ids 10 through 109 can mint, so 109 registers and 110 doesn't. + tens.registerAgents(10, 10, "", ""); + tens.registerAgents(109, 109, "", ""); + vm.expectRevert( + abi.encodeWithSelector( + ERC721SeaDropAgents.InvalidAgentTokenIdRange.selector, 109, 110 + ) + ); + tens.registerAgents(109, 110, "", ""); + + // Minting the full supply reaches 109. + tens.mint(holder, 100); + assertEq(tens.ownerOf(109), holder); + (bool registered,) = tens.agentOf(109); + assertTrue(registered); + } + + function testRegisterAgentsOnlyOwner() public { + vm.prank(stranger); + vm.expectRevert(TwoStepOwnable.OnlyOwner.selector); + agents.registerAgents(1, 1, "", ""); + } + + function testRegisterAgentsWithoutAdapter() public { + ERC721SeaDropAgentsWithMint noAdapter = _deploy(address(0)); + noAdapter.setMaxSupply(10); + assertEq(noAdapter.agentAdapter(), address(0)); + + vm.expectRevert(ERC721SeaDropAgents.AgentAdapterNotSet.selector); + noAdapter.registerAgents(1, 1, "", ""); + + // Metadata works without an adapter. + noAdapter.setMetadata(1, "context", "lore"); + assertEq(noAdapter.metadata(1, "context"), bytes("lore")); + } + + /// @dev The ERC-8217 adapter docs/AgentNFTs.md lists for `chainId`. + function _deployedAdapter(uint256 chainId) internal pure returns (address) { + if (chainId == 1) return 0xde152AfB7db5373F34876E1499fbD893A82dD336; + if (chainId == 8453) return 0x270d25D2c59A8bcA1B0f40ad95fF7806c0025c27; + if (chainId == 4663) return 0x000000009d62675362a58911e3f32FEcf46F5E18; + if (chainId == 11_155_111) { + return 0x7621630cB63a73a194f45A3E6801B8C6A7eC2f92; + } + revert("no adapter listed for this chain"); + } + + /// @dev Registers through the ERC-8217 adapter deployed on the chain + /// AGENT_ADAPTER_FORK_URL names: Ethereum, Base, Robinhood Chain or + /// Sepolia. Skipped when it isn't set. + function testRegisterAgentsWithDeployedAdapter() public { + string memory forkUrl = vm.envOr("AGENT_ADAPTER_FORK_URL", string("")); + if (bytes(forkUrl).length == 0) { + vm.skip(true); + return; + } + + vm.createSelectFork(forkUrl); + address deployedAdapter = _deployedAdapter(block.chainid); + + ERC721SeaDropAgentsWithMint forked = _deploy(deployedAdapter); + forked.setMaxSupply(10); + forked.registerAgents(1, 2, "https://agents.example/", ".json"); + + IAgentAdapterView view_ = IAgentAdapterView(deployedAdapter); + (bool registered, uint256 agentId) = forked.agentOf(1); + assertTrue(registered); + IAgentAdapterView.Binding memory binding = view_.bindingOf(agentId); + assertEq(binding.standard, 0); + assertEq(binding.boundAddress, address(forked)); + assertEq(binding.tokenId, 1); + assertEq(view_.tokenURI(agentId), "https://agents.example/1.json"); + + // The holder controls the agent after mint, and the contract + // can't register the minted token again. + forked.mint(holder, 1); + assertTrue(view_.isController(agentId, holder)); + assertFalse(view_.isController(agentId, address(forked))); + assertFalse(view_.isController(agentId, address(this))); + } +} From 7b3c98ba1f02f929622afb52e20a41d1cb4365f2 Mon Sep 17 00:00:00 2001 From: Ryan Ghods Date: Tue, 17 Nov 2026 11:24:37 -0800 Subject: [PATCH 2/8] Add stateful v3 accounting invariants and push CI --- .github/workflows/test.yml | 2 +- docs/v3/AuditScope.md | 2 +- foundry.toml | 5 + test/v3/SeaDropMinterInvariant.t.sol | 468 +++++++++++++++++++++++++++ 4 files changed, 475 insertions(+), 2 deletions(-) create mode 100644 test/v3/SeaDropMinterInvariant.t.sol diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b2147f4b..af6bb42d 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -2,7 +2,7 @@ name: Test CI on: push: - branches: [main] + branches: [main, v3] tags: ["*"] pull_request: types: [opened, reopened, synchronize] diff --git a/docs/v3/AuditScope.md b/docs/v3/AuditScope.md index 63f7bb30..1845ba6a 100644 --- a/docs/v3/AuditScope.md +++ b/docs/v3/AuditScope.md @@ -233,7 +233,7 @@ Token events: a clone's initialization emits `OwnershipTransferred(address(0), o - Foundry, with solc 0.8.38 targeting Cancun and 1,000,000 optimizer runs, without via-IR. Every network we deploy to supports Cancun's opcodes. - Build with `forge build`, and run the v3 tests with `forge test --match-path 'test/v3/*'`. -- CI runs both v1 and v3 tests, including agent metadata, registration and storage-slot coverage and distinct payer/wallet/recipient event assertions. The migration's validated commit has 605 passing tests and two skipped fork tests across 43 suites. Refresh these counts at code freeze. There are no invariant tests yet; add payment-accounting, wallet-limit and stage-cap invariants before freeze. +- CI runs both v1 and v3 tests, including agent metadata, registration and storage-slot coverage and distinct payer/wallet/recipient event assertions. The migration's validated commit has 605 passing tests and two skipped fork tests across 43 suites. Refresh these counts at code freeze. The stateful suite in `test/v3/SeaDropMinterInvariant.t.sol` checks native/ERC-20 conservation, exact payout liabilities, failed withdrawals, unsolicited surplus, cross-stage wallet and supply accounting, and rejected payment and authorization paths. It seeds successful mints and withdrawals, then fuzzes action sequences with unexpected reverts treated as failures. - A public mint through a clone costs 144k to 169k gas, against 129k for v1 and 202k for v2. About 2.85k of that is the clone's `DELEGATECALL` (see "Token deployment"). Every paid mint writes the wallet's count, even in a stage with no wallet limit. That costs about 23k on a wallet's first mint of a token and id, and about 5k on later ones. Skipping it in unlimited stages would save the write, but a later limited stage couldn't see those mints. A stage cap adds about 1.1k to every mint in the stage, for the view call that reads the token's total. It writes nothing, so the first mint costs the same as later ones. The minter's runtime bytecode is 22,242 bytes, 2,334 under the EIP-170 limit. The ERC-721 implementation is 11,065 bytes and the ERC-1155 11,258. The factory's runtime is 2,287 bytes, and its init code, which carries both implementations, is 26,159 bytes, 22,993 under EIP-3860's limit. The mint adapter's runtime is 5,099 bytes and the transfer adapter's 7,201. ## Deployment diff --git a/foundry.toml b/foundry.toml index 673a5a1f..39e84a1f 100644 --- a/foundry.toml +++ b/foundry.toml @@ -42,6 +42,11 @@ ignored_warnings_from = ['script'] additional_compiler_profiles = [] compilation_restrictions = [] +[profile.default.invariant] +runs = 128 +depth = 64 +fail_on_revert = true + [profile.ir_inspect] test = 'src' diff --git a/test/v3/SeaDropMinterInvariant.t.sol b/test/v3/SeaDropMinterInvariant.t.sol new file mode 100644 index 00000000..8b04d1e1 --- /dev/null +++ b/test/v3/SeaDropMinterInvariant.t.sol @@ -0,0 +1,468 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.38; + +import { StdInvariant } from "forge-std/StdInvariant.sol"; +import { Test } from "forge-std/Test.sol"; +import { SeaDropV3TestHelper } from "./utils/SeaDropV3TestHelper.sol"; +import { RevertingRecipient, TestERC20 } from "./utils/Mocks.sol"; +import { ISeaDropMinter } from "seadrop/v3/interfaces/ISeaDropMinter.sol"; + +/** + * @dev Only the selected actions are fuzzed. Successful calls are not caught: + * fail_on_revert makes unexpected failures fail the campaign. The model + * derives charges from requested quantities, not minter accounting. + */ +contract SeaDropInvariantHandler is SeaDropV3TestHelper { + uint256 internal constant ACTORS = 16; + uint256 internal constant WALLET_LIMIT = 12; + uint256 internal constant SUPPLY = 128; + uint256 internal constant TOKEN_PRICE = 1_000_003; + + TestERC20 internal currency; + RevertingRecipient internal rejectingCreator; + address internal withdrawalSink = makeAddr("withdrawalSink"); + address[16] internal actors; + uint256[2] internal sold; + uint256[2] internal ownerMinted; + uint256[2] internal stageCaps; + uint256[2] internal collected; + uint256[2] internal donated; + mapping(uint256 => mapping(address => uint256)) internal spent; + uint256[2] internal expectedCreatorCredit; + uint256[2] internal expectedFeeCredit; + uint256[2] internal withdrawn; + mapping(uint256 => mapping(address => uint256)) internal walletMints; + mapping(uint256 => mapping(address => uint256)) internal delivered; + mapping(address => uint256) internal nextNonce; + ISeaDropMinter.MintIntent internal lastIntent; + bytes internal lastIntentSignature; + ISeaDropMinter.Authorization internal lastAuthorization; + bool internal hasIntent; + uint256 public successfulMints; + uint256 public successfulWithdrawals; + uint256 public rejectedCalls; + + function setUp() public override { + super.setUp(); + currency = new TestERC20(); + rejectingCreator = new RevertingRecipient(); + minter.setCurrency( + address(currency), + ISeaDropMinter.CurrencyConfig(true, uint16(FEE_BPS), feeRecipient) + ); + token721.setMaxSupply(SUPPLY); + token1155.setMaxSupply(ID_1155, uint128(SUPPLY)); + _setSinglePayout(address(token721), address(rejectingCreator)); + _setSinglePayout(address(token1155), address(rejectingCreator)); + for (uint256 i; i < ACTORS; ++i) { + actors[i] = vm.addr(i + 100); + vm.deal(actors[i], 1000 ether); + currency.mint(actors[i], 1_000_000_000); + vm.prank(actors[i]); + currency.approve(address(minter), type(uint256).max); + } + setCap(0, 63); + setCap(1, 63); + } + + function _token(uint256 kind) internal view returns (address) { + return kind == 0 ? address(token721) : address(token1155); + } + + function _id(uint256 kind) internal pure returns (uint256) { + return kind == 0 ? 0 : ID_1155; + } + + function _currency(uint256 kind) internal view returns (address) { + return kind == 0 ? address(0) : address(currency); + } + + function _price(uint256 kind) internal pure returns (uint256) { + return kind == 0 ? PRICE : TOKEN_PRICE; + } + + /// @dev Change both stage caps without erasing the cumulative counts. + function setCap(uint256 kindSeed, uint256 capSeed) public { + uint256 kind = kindSeed % 2; + uint256 total = sold[kind] + ownerMinted[kind]; + uint256 cap = bound(capSeed, total == 0 ? 1 : total, SUPPLY); + stageCaps[kind] = cap; + ISeaDropMinter.Stage memory stage = _publicStage(); + stage.currency = _currency(kind); + stage.price = uint96(_price(kind)); + stage.maxPerWallet = uint32(WALLET_LIMIT); + stage.maxTokenSupplyForStage = uint32(cap); + minter.setStage(_token(kind), _id(kind), 0, stage); + stage.signer = signer; + minter.setStage(_token(kind), _id(kind), 1, stage); + } + + function mint( + uint256 kindSeed, + uint256 actorSeed, + uint256 quantitySeed, + bool signedStage, + bool useIntent, + bool blockCreator, + bool blockFee + ) public { + uint256 kind = kindSeed % 2; + uint256 actorIndex = actorSeed % ACTORS; + address wallet = actors[actorIndex]; + uint256 room = stageCaps[kind] - sold[kind] - ownerMinted[kind]; + uint256 walletRoom = WALLET_LIMIT - walletMints[kind][wallet]; + if (room > walletRoom) room = walletRoom; + if (room == 0) return; + uint256 quantity = bound(quantitySeed, 1, room > 3 ? 3 : room); + address payer = actors[(actorIndex + 1) % ACTORS]; + address recipient = + useIntent ? actors[(actorIndex + 2) % ACTORS] : wallet; + ISeaDropMinter.MintParams memory params = + _params(_token(kind), _id(kind), wallet, recipient, quantity); + params.currency = _currency(kind); + params.maxTotalPrice = _price(kind) * quantity; + params.stageIndex = signedStage ? 1 : 0; + ISeaDropMinter.Authorization memory auth = _noAuth(); + if (signedStage) { + auth = _authorize(params, signer, signerKey, 0, false, 0); + } + currency.setBlocked(address(rejectingCreator), blockCreator); + currency.setBlocked(feeRecipient, blockFee); + uint256 value = kind == 0 ? params.maxTotalPrice : 0; + if (useIntent) { + ISeaDropMinter.MintIntent memory intent = ISeaDropMinter.MintIntent( + params, nextNonce[wallet]++, vm.getBlockTimestamp() + 100 + ); + bytes memory signature = + _sign(actorIndex + 100, _intentDigest(intent)); + vm.prank(payer); + minter.mintWithIntent{ value: value }(intent, signature, auth); + assertTrue(minter.intentNonceUsed(wallet, intent.nonce)); + lastIntent = intent; + lastIntentSignature = signature; + lastAuthorization = auth; + hasIntent = true; + } else { + vm.prank(payer); + minter.mint{ value: value }(params, auth); + } + _recordMint(kind, params, payer, blockCreator, blockFee); + } + + function _recordMint( + uint256 kind, + ISeaDropMinter.MintParams memory params, + address payer, + bool blockCreator, + bool blockFee + ) internal { + uint256 fee = params.maxTotalPrice * FEE_BPS / 10_000; + if (kind == 0 || blockCreator) { + expectedCreatorCredit[kind] += params.maxTotalPrice - fee; + } + if (kind == 1 && blockFee) expectedFeeCredit[kind] += fee; + collected[kind] += params.maxTotalPrice; + spent[kind][payer] += params.maxTotalPrice; + sold[kind] += params.quantity; + walletMints[kind][params.wallet] += params.quantity; + delivered[kind][params.recipient] += params.quantity; + ++successfulMints; + } + + /// @dev Owner mints consume supply and future stage headroom, not wallet limits. + function ownerMint(uint256 kindSeed, uint256 actorSeed) public { + uint256 kind = kindSeed % 2; + if (sold[kind] + ownerMinted[kind] == stageCaps[kind]) return; + address recipient = actors[actorSeed % ACTORS]; + minter.ownerMint(_token(kind), _id(kind), recipient, 1); + ++ownerMinted[kind]; + ++delivered[kind][recipient]; + } + + function withdraw(uint256 kindSeed, bool fee, bool fail) public { + uint256 kind = kindSeed % 2; + uint256 amount = + fee ? expectedFeeCredit[kind] : expectedCreatorCredit[kind]; + if (amount == 0) return; + address account = fee ? feeRecipient : address(rejectingCreator); + address to = fail ? address(rejectingCreator) : withdrawalSink; + currency.setBlocked(to, fail); + vm.prank(account); + if (fail) { + if (kind == 0) { + vm.expectRevert(ISeaDropMinter.WithdrawalFailed.selector); + } else { + vm.expectRevert(bytes("blocked")); + } + minter.withdraw(_currency(kind), to); + ++rejectedCalls; + } else { + minter.withdraw(_currency(kind), to); + if (fee) expectedFeeCredit[kind] = 0; + else expectedCreatorCredit[kind] = 0; + withdrawn[kind] += amount; + ++successfulWithdrawals; + } + } + + /// @dev Rejected calls must leave all modeled balances and counts unchanged. + function rejectUnauthorized(uint256 kindSeed, uint256 attackSeed) public { + uint256 kind = kindSeed % 2; + address token = _token(kind); + address wallet = actors[0]; + address attacker = actors[1]; + ISeaDropMinter.MintParams memory params = + _params(token, _id(kind), wallet, actors[2], 1); + params.currency = _currency(kind); + params.maxTotalPrice = _price(kind); + uint256 value = kind == 0 ? params.maxTotalPrice : 0; + uint256 attack = attackSeed % 3; + if (attack == 0) { + vm.prank(attacker); + vm.expectRevert( + abi.encodeWithSelector( + ISeaDropMinter.RecipientNotApproved.selector, + wallet, + actors[2] + ) + ); + minter.mint{ value: value }(params, _noAuth()); + } else if (attack == 1) { + params.recipient = wallet; + params.stageIndex = 1; + ISeaDropMinter.Authorization memory auth = + _authorize(params, signer, 101, 0, false, 0); + vm.prank(attacker); + vm.expectRevert(ISeaDropMinter.InvalidSignature.selector); + minter.mint{ value: value }(params, auth); + } else { + vm.prank(attacker); + vm.expectRevert( + abi.encodeWithSelector( + ISeaDropMinter.OnlyTokenOwner.selector, token, attacker + ) + ); + minter.ownerMint(token, _id(kind), attacker, 1); + } + ++rejectedCalls; + } + + function rejectReplay() public { + if (!hasIntent) return; + ISeaDropMinter.MintIntent memory intent = lastIntent; + uint256 value = intent.params.currency == address(0) + ? intent.params.maxTotalPrice + : 0; + vm.prank(actors[1]); + vm.expectRevert( + abi.encodeWithSelector( + ISeaDropMinter.IntentNonceUsed.selector, + intent.params.wallet, + intent.nonce + ) + ); + minter.mintWithIntent{ value: value }( + intent, lastIntentSignature, lastAuthorization + ); + ++rejectedCalls; + } + + /// @dev Force an actual limit violation; successful actions alone cannot + /// detect a removed wallet or stage guard because they stay in bounds. + function rejectLimit(uint256 kindSeed, uint256 actorSeed, bool walletLimit) + public + { + uint256 kind = kindSeed % 2; + address wallet = actors[actorSeed % ACTORS]; + uint256 quantity = walletLimit + ? WALLET_LIMIT - walletMints[kind][wallet] + 1 + : stageCaps[kind] - sold[kind] - ownerMinted[kind] + 1; + // The wallet guard runs before the supply guard. + if (!walletLimit && walletMints[kind][wallet] + quantity > WALLET_LIMIT) + { + return; + } + ISeaDropMinter.MintParams memory params = + _params(_token(kind), _id(kind), wallet, wallet, quantity); + params.currency = _currency(kind); + params.maxTotalPrice = _price(kind) * quantity; + vm.prank(wallet); + if (walletLimit) { + vm.expectRevert( + abi.encodeWithSelector( + ISeaDropMinter.MintQuantityExceedsWalletLimit.selector, + walletMints[kind][wallet] + quantity, + WALLET_LIMIT + ) + ); + } else { + vm.expectRevert( + abi.encodeWithSelector( + ISeaDropMinter.MintQuantityExceedsMaxTokenSupplyForStage + .selector, + sold[kind] + ownerMinted[kind] + quantity, + stageCaps[kind] + ) + ); + } + minter.mint{ value: kind == 0 ? params.maxTotalPrice : 0 }( + params, _noAuth() + ); + ++rejectedCalls; + } + + /// @dev Model unsolicited surplus separately from proceeds and liabilities. + function donate(uint256 kindSeed, uint256 amountSeed) public { + uint256 kind = kindSeed % 2; + uint256 amount = bound(amountSeed, 1, 1000); + if (kind == 0) { + // A contract without receive() can still receive forced ETH. + vm.deal(address(minter), address(minter).balance + amount); + } else { + vm.prank(actors[0]); + currency.transfer(address(minter), amount); + spent[kind][actors[0]] += amount; + } + donated[kind] += amount; + } + + /// @dev An underpayment must not spend the earlier recipients' credits. + function rejectPayment(uint256 kindSeed) public { + uint256 kind = kindSeed % 2; + address wallet = actors[ACTORS - 1]; + if ( + walletMints[kind][wallet] == WALLET_LIMIT + || sold[kind] + ownerMinted[kind] == stageCaps[kind] + ) return; + ISeaDropMinter.MintParams memory params = + _params(_token(kind), _id(kind), wallet, wallet, 1); + params.currency = _currency(kind); + params.maxTotalPrice = _price(kind); + if (kind == 1) currency.setTransferFeeBps(100); + vm.prank(wallet); + if (kind == 0) { + vm.expectRevert( + abi.encodeWithSelector( + ISeaDropMinter.IncorrectPayment.selector, PRICE - 1, PRICE + ) + ); + } else { + vm.expectRevert( + abi.encodeWithSelector( + ISeaDropMinter.ERC20AmountNotReceived.selector, + TOKEN_PRICE - TOKEN_PRICE / 100, + TOKEN_PRICE + ) + ); + } + minter.mint{ value: kind == 0 ? PRICE - 1 : 0 }(params, _noAuth()); + if (kind == 1) currency.setTransferFeeBps(0); + ++rejectedCalls; + } + + function assertAccountingAndSupply() external view { + for (uint256 kind; kind < 2; ++kind) { + address asset = _currency(kind); + uint256 held = kind == 0 + ? address(minter).balance + : currency.balanceOf(address(minter)); + uint256 paidCreator = kind == 0 + ? address(rejectingCreator).balance + : currency.balanceOf(address(rejectingCreator)); + uint256 paidFee = kind == 0 + ? feeRecipient.balance + : currency.balanceOf(feeRecipient); + uint256 sink = kind == 0 + ? withdrawalSink.balance + : currency.balanceOf(withdrawalSink); + assertEq( + minter.credited(address(rejectingCreator), asset), + expectedCreatorCredit[kind] + ); + assertEq( + minter.credited(feeRecipient, asset), expectedFeeCredit[kind] + ); + assertEq( + held, + expectedCreatorCredit[kind] + expectedFeeCredit[kind] + + donated[kind] + ); + assertEq(sink, withdrawn[kind]); + assertEq( + collected[kind] + donated[kind], + held + paidCreator + paidFee + sink + ); + uint256 supply = sold[kind] + ownerMinted[kind]; + assertLe(supply, stageCaps[kind]); + assertLe(supply, SUPPLY); + uint256 sumBalances; + for (uint256 i; i < ACTORS; ++i) { + address wallet = actors[i]; + uint256 funding = kind == 0 ? 1000 ether : 1_000_000_000; + uint256 funds = + kind == 0 ? wallet.balance : currency.balanceOf(wallet); + assertEq(funds, funding - spent[kind][wallet]); + assertEq( + minter.mintedByWallet(_token(kind), _id(kind), wallet), + walletMints[kind][wallet] + ); + assertLe(walletMints[kind][wallet], WALLET_LIMIT); + uint256 balance = kind == 0 + ? token721.balanceOf(wallet) + : token1155.balanceOf(wallet, ID_1155); + assertEq(balance, delivered[kind][wallet]); + sumBalances += balance; + } + assertEq(sumBalances, supply); + } + } +} + +contract SeaDropMinterInvariantTest is StdInvariant, Test { + SeaDropInvariantHandler internal handler; + + function setUp() public { + handler = new SeaDropInvariantHandler(); + handler.setUp(); + // Exercise success, credit creation, failed withdrawal, withdrawal, + // signature authorization and nonce rejection before every campaign. + handler.mint(0, 0, 1, false, false, false, false); + handler.mint(1, 0, 1, true, true, true, true); + handler.withdraw(0, false, true); + handler.withdraw(1, false, true); + handler.withdraw(0, false, false); + handler.withdraw(1, false, false); + handler.rejectPayment(0); + handler.rejectPayment(1); + handler.donate(0, 17); + handler.donate(1, 19); + handler.rejectReplay(); + handler.rejectUnauthorized(0, 0); + handler.rejectUnauthorized(1, 1); + handler.rejectUnauthorized(0, 2); + handler.rejectLimit(0, 0, true); + handler.setCap(1, 1); + handler.rejectLimit(1, 1, false); + handler.setCap(1, 63); + + bytes4[] memory selectors = new bytes4[](9); + selectors[0] = handler.mint.selector; + selectors[1] = handler.ownerMint.selector; + selectors[2] = handler.setCap.selector; + selectors[3] = handler.withdraw.selector; + selectors[4] = handler.rejectUnauthorized.selector; + selectors[5] = handler.rejectReplay.selector; + selectors[6] = handler.rejectLimit.selector; + selectors[7] = handler.donate.selector; + selectors[8] = handler.rejectPayment.selector; + targetSelector(FuzzSelector(address(handler), selectors)); + targetContract(address(handler)); + } + + function invariant_paymentsAndTokenAccounting() public view { + handler.assertAccountingAndSupply(); + assertGe(handler.successfulMints(), 2); + assertGe(handler.successfulWithdrawals(), 2); + assertGe(handler.rejectedCalls(), 10); + } +} From 1705b382f5225886209eb5bebab91df47bc00f91 Mon Sep 17 00:00:00 2001 From: Ryan Ghods Date: Tue, 17 Nov 2026 11:25:59 -0800 Subject: [PATCH 3/8] Exercise owner mint max supply rejection in invariant sequences --- test/v3/SeaDropMinterInvariant.t.sol | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/test/v3/SeaDropMinterInvariant.t.sol b/test/v3/SeaDropMinterInvariant.t.sol index 8b04d1e1..37df16ce 100644 --- a/test/v3/SeaDropMinterInvariant.t.sol +++ b/test/v3/SeaDropMinterInvariant.t.sol @@ -179,6 +179,20 @@ contract SeaDropInvariantHandler is SeaDropV3TestHelper { ++delivered[kind][recipient]; } + function rejectOwnerSupply(uint256 kindSeed) public { + uint256 kind = kindSeed % 2; + uint256 quantity = SUPPLY - sold[kind] - ownerMinted[kind] + 1; + vm.expectRevert( + abi.encodeWithSelector( + ISeaDropMinter.MintQuantityExceedsMaxSupply.selector, + SUPPLY + 1, + SUPPLY + ) + ); + minter.ownerMint(_token(kind), _id(kind), actors[0], quantity); + ++rejectedCalls; + } + function withdraw(uint256 kindSeed, bool fee, bool fail) public { uint256 kind = kindSeed % 2; uint256 amount = @@ -441,11 +455,13 @@ contract SeaDropMinterInvariantTest is StdInvariant, Test { handler.rejectUnauthorized(1, 1); handler.rejectUnauthorized(0, 2); handler.rejectLimit(0, 0, true); + handler.rejectOwnerSupply(0); + handler.rejectOwnerSupply(1); handler.setCap(1, 1); handler.rejectLimit(1, 1, false); handler.setCap(1, 63); - bytes4[] memory selectors = new bytes4[](9); + bytes4[] memory selectors = new bytes4[](10); selectors[0] = handler.mint.selector; selectors[1] = handler.ownerMint.selector; selectors[2] = handler.setCap.selector; @@ -455,6 +471,7 @@ contract SeaDropMinterInvariantTest is StdInvariant, Test { selectors[6] = handler.rejectLimit.selector; selectors[7] = handler.donate.selector; selectors[8] = handler.rejectPayment.selector; + selectors[9] = handler.rejectOwnerSupply.selector; targetSelector(FuzzSelector(address(handler), selectors)); targetContract(address(handler)); } @@ -463,6 +480,6 @@ contract SeaDropMinterInvariantTest is StdInvariant, Test { handler.assertAccountingAndSupply(); assertGe(handler.successfulMints(), 2); assertGe(handler.successfulWithdrawals(), 2); - assertGe(handler.rejectedCalls(), 10); + assertGe(handler.rejectedCalls(), 12); } } From 1b32c5a70ddf99b6ba4f222eebd22227d75f8259 Mon Sep 17 00:00:00 2001 From: Ryan Ghods Date: Tue, 17 Nov 2026 11:26:31 -0800 Subject: [PATCH 4/8] Split invariant assertions to fit the non-IR compiler stack --- test/v3/SeaDropMinterInvariant.t.sol | 48 +++++++++++++++------------- 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/test/v3/SeaDropMinterInvariant.t.sol b/test/v3/SeaDropMinterInvariant.t.sol index 37df16ce..6e7f6ed5 100644 --- a/test/v3/SeaDropMinterInvariant.t.sol +++ b/test/v3/SeaDropMinterInvariant.t.sol @@ -406,29 +406,33 @@ contract SeaDropInvariantHandler is SeaDropV3TestHelper { collected[kind] + donated[kind], held + paidCreator + paidFee + sink ); - uint256 supply = sold[kind] + ownerMinted[kind]; - assertLe(supply, stageCaps[kind]); - assertLe(supply, SUPPLY); - uint256 sumBalances; - for (uint256 i; i < ACTORS; ++i) { - address wallet = actors[i]; - uint256 funding = kind == 0 ? 1000 ether : 1_000_000_000; - uint256 funds = - kind == 0 ? wallet.balance : currency.balanceOf(wallet); - assertEq(funds, funding - spent[kind][wallet]); - assertEq( - minter.mintedByWallet(_token(kind), _id(kind), wallet), - walletMints[kind][wallet] - ); - assertLe(walletMints[kind][wallet], WALLET_LIMIT); - uint256 balance = kind == 0 - ? token721.balanceOf(wallet) - : token1155.balanceOf(wallet, ID_1155); - assertEq(balance, delivered[kind][wallet]); - sumBalances += balance; - } - assertEq(sumBalances, supply); + _assertSupply(kind); + } + } + + function _assertSupply(uint256 kind) internal view { + uint256 supply = sold[kind] + ownerMinted[kind]; + assertLe(supply, stageCaps[kind]); + assertLe(supply, SUPPLY); + uint256 sumBalances; + for (uint256 i; i < ACTORS; ++i) { + address wallet = actors[i]; + uint256 funding = kind == 0 ? 1000 ether : 1_000_000_000; + uint256 funds = + kind == 0 ? wallet.balance : currency.balanceOf(wallet); + assertEq(funds, funding - spent[kind][wallet]); + assertEq( + minter.mintedByWallet(_token(kind), _id(kind), wallet), + walletMints[kind][wallet] + ); + assertLe(walletMints[kind][wallet], WALLET_LIMIT); + uint256 balance = kind == 0 + ? token721.balanceOf(wallet) + : token1155.balanceOf(wallet, ID_1155); + assertEq(balance, delivered[kind][wallet]); + sumBalances += balance; } + assertEq(sumBalances, supply); } } From fad90ad24fbfbb841f35fb64299003ee9c0d7b42 Mon Sep 17 00:00:00 2001 From: Ryan Ghods Date: Tue, 17 Nov 2026 11:29:12 -0800 Subject: [PATCH 5/8] Bound invariant mint stack usage with a structured action --- test/v3/SeaDropMinterInvariant.t.sol | 88 +++++++++++++++++++--------- 1 file changed, 61 insertions(+), 27 deletions(-) diff --git a/test/v3/SeaDropMinterInvariant.t.sol b/test/v3/SeaDropMinterInvariant.t.sol index 6e7f6ed5..b5ba595e 100644 --- a/test/v3/SeaDropMinterInvariant.t.sol +++ b/test/v3/SeaDropMinterInvariant.t.sol @@ -97,47 +97,76 @@ contract SeaDropInvariantHandler is SeaDropV3TestHelper { minter.setStage(_token(kind), _id(kind), 1, stage); } - function mint( - uint256 kindSeed, - uint256 actorSeed, + struct MintAction { + uint256 kindSeed; + uint256 actorSeed; + uint256 quantitySeed; + bool signedStage; + bool useIntent; + bool blockCreator; + bool blockFee; + } + + function mint(MintAction memory action) public { + uint256 kind = action.kindSeed % 2; + uint256 actorIndex = action.actorSeed % ACTORS; + ISeaDropMinter.MintParams memory params = _mintParams( + kind, actorIndex, action.quantitySeed, action.useIntent + ); + if (params.quantity == 0) return; + params.stageIndex = action.signedStage ? 1 : 0; + ISeaDropMinter.Authorization memory auth = _noAuth(); + if (action.signedStage) { + auth = _authorize(params, signer, signerKey, 0, false, 0); + } + currency.setBlocked(address(rejectingCreator), action.blockCreator); + currency.setBlocked(feeRecipient, action.blockFee); + _executeMint(params, auth, actorIndex, action.useIntent); + _recordMint( + kind, + params, + actors[(actorIndex + 1) % ACTORS], + action.blockCreator, + action.blockFee + ); + } + + function _mintParams( + uint256 kind, + uint256 actorIndex, uint256 quantitySeed, - bool signedStage, - bool useIntent, - bool blockCreator, - bool blockFee - ) public { - uint256 kind = kindSeed % 2; - uint256 actorIndex = actorSeed % ACTORS; + bool useIntent + ) internal view returns (ISeaDropMinter.MintParams memory params) { address wallet = actors[actorIndex]; uint256 room = stageCaps[kind] - sold[kind] - ownerMinted[kind]; uint256 walletRoom = WALLET_LIMIT - walletMints[kind][wallet]; if (room > walletRoom) room = walletRoom; - if (room == 0) return; + if (room == 0) return params; uint256 quantity = bound(quantitySeed, 1, room > 3 ? 3 : room); - address payer = actors[(actorIndex + 1) % ACTORS]; address recipient = useIntent ? actors[(actorIndex + 2) % ACTORS] : wallet; - ISeaDropMinter.MintParams memory params = - _params(_token(kind), _id(kind), wallet, recipient, quantity); + params = _params(_token(kind), _id(kind), wallet, recipient, quantity); params.currency = _currency(kind); params.maxTotalPrice = _price(kind) * quantity; - params.stageIndex = signedStage ? 1 : 0; - ISeaDropMinter.Authorization memory auth = _noAuth(); - if (signedStage) { - auth = _authorize(params, signer, signerKey, 0, false, 0); - } - currency.setBlocked(address(rejectingCreator), blockCreator); - currency.setBlocked(feeRecipient, blockFee); - uint256 value = kind == 0 ? params.maxTotalPrice : 0; + } + + function _executeMint( + ISeaDropMinter.MintParams memory params, + ISeaDropMinter.Authorization memory auth, + uint256 actorIndex, + bool useIntent + ) internal { + address payer = actors[(actorIndex + 1) % ACTORS]; + uint256 value = params.currency == address(0) ? params.maxTotalPrice : 0; if (useIntent) { ISeaDropMinter.MintIntent memory intent = ISeaDropMinter.MintIntent( - params, nextNonce[wallet]++, vm.getBlockTimestamp() + 100 + params, nextNonce[params.wallet]++, vm.getBlockTimestamp() + 100 ); bytes memory signature = _sign(actorIndex + 100, _intentDigest(intent)); vm.prank(payer); minter.mintWithIntent{ value: value }(intent, signature, auth); - assertTrue(minter.intentNonceUsed(wallet, intent.nonce)); + assertTrue(minter.intentNonceUsed(params.wallet, intent.nonce)); lastIntent = intent; lastIntentSignature = signature; lastAuthorization = auth; @@ -146,7 +175,6 @@ contract SeaDropInvariantHandler is SeaDropV3TestHelper { vm.prank(payer); minter.mint{ value: value }(params, auth); } - _recordMint(kind, params, payer, blockCreator, blockFee); } function _recordMint( @@ -444,8 +472,14 @@ contract SeaDropMinterInvariantTest is StdInvariant, Test { handler.setUp(); // Exercise success, credit creation, failed withdrawal, withdrawal, // signature authorization and nonce rejection before every campaign. - handler.mint(0, 0, 1, false, false, false, false); - handler.mint(1, 0, 1, true, true, true, true); + handler.mint( + SeaDropInvariantHandler.MintAction( + 0, 0, 1, false, false, false, false + ) + ); + handler.mint( + SeaDropInvariantHandler.MintAction(1, 0, 1, true, true, true, true) + ); handler.withdraw(0, false, true); handler.withdraw(1, false, true); handler.withdraw(0, false, false); From ce8cfba0814ecda501f39b33bdfead7bbe92ea27 Mon Sep 17 00:00:00 2001 From: Ryan Ghods Date: Tue, 17 Nov 2026 11:30:33 -0800 Subject: [PATCH 6/8] Install the test-only handler without relaxing production size limits --- test/v3/SeaDropMinterInvariant.t.sol | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/test/v3/SeaDropMinterInvariant.t.sol b/test/v3/SeaDropMinterInvariant.t.sol index b5ba595e..3257f319 100644 --- a/test/v3/SeaDropMinterInvariant.t.sol +++ b/test/v3/SeaDropMinterInvariant.t.sol @@ -468,7 +468,14 @@ contract SeaDropMinterInvariantTest is StdInvariant, Test { SeaDropInvariantHandler internal handler; function setUp() public { - handler = new SeaDropInvariantHandler(); + // This test-only handler embeds the fixture's creation code. Install + // it without relaxing EIP-170 for the production contracts it deploys. + address handlerAddress = makeAddr("invariantHandler"); + deployCodeTo( + "SeaDropMinterInvariant.t.sol:SeaDropInvariantHandler", + handlerAddress + ); + handler = SeaDropInvariantHandler(handlerAddress); handler.setUp(); // Exercise success, credit creation, failed withdrawal, withdrawal, // signature authorization and nonce rejection before every campaign. From d88b8786a2d8f93c2001774e863192fface4f26e Mon Sep 17 00:00:00 2001 From: Ryan Ghods Date: Tue, 17 Nov 2026 11:33:23 -0800 Subject: [PATCH 7/8] Clarify agent metadata resolution and write permissions (#238) The agent guide incorrectly says OpenSea never reads ERC-8048 records and describes batch writes without the owner/holder permission settings. Clarify that explicit ERC-8493 `onchain:` URIs resolve ERC-8048-backed metadata, while arbitrary agent records are not interpreted automatically. Also explain batch permission checks and how holders clear a metadata-policy delegation. Documentation only. Checked against `ERC8048OnchainMetadata`, `MetadataWriterPolicy`, OpenSea's `OnchainUriResolver`, and the published metadata-storage guide. CI validates formatting and the existing contract suite; no local tests or Docker runs. --- docs/AgentNFTs.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/AgentNFTs.md b/docs/AgentNFTs.md index 47435f28..5cc8910d 100644 --- a/docs/AgentNFTs.md +++ b/docs/AgentNFTs.md @@ -79,7 +79,7 @@ When holders can write, a seller can change their token's records up to the mome ### Reference policy -`src/lib/MetadataWriterPolicy.sol` is a small policy contract to set as the metadata authority. The contract doesn't need it, and it shows what a policy can do. Its owner (the admin) can allow several writer addresses with `setWriter`, such as a hot wallet that runs a metadata job. A writer can write records and nothing else. A token's current holder can delegate their token's writes to one address with `setDelegate`, such as their agent's wallet. A delegation counts only while the holder who set it still holds the token, so it lapses on transfer. It counts again if the token comes back to that holder. +`src/lib/MetadataWriterPolicy.sol` is a small policy contract to set as the metadata authority. The contract doesn't need it, and it shows what a policy can do. Its owner (the admin) can allow several writer addresses with `setWriter`, such as a hot wallet that runs a metadata job. A writer can write records and nothing else. A token's current holder can delegate their token's writes to one address with `setDelegate`, such as their agent's wallet. A delegation applies only while the holder who set it still holds the token. It stops applying on transfer and applies again if the token comes back to that holder. The current holder can clear it with `setDelegate(tokenId, address(0))`. Writers and delegates call the policy's `setMetadata` and `setMetadataBatch`, which check the caller and forward the write to the token. The admin can also call `setCollectionAuthority` through the policy, for example to hand the authority to a new policy. @@ -93,7 +93,7 @@ The admin can unmark a key, and the owner can replace an unlocked policy. For a ### Batches -`setMetadataBatch` writes many records in one transaction. If the caller can't write any one entry, the whole batch reverts. A set authority, or the owner while the authority is blank, can write every entry. +`setMetadataBatch` writes many records in one transaction. If the caller can't write any one entry, the whole batch reverts. A set authority can write every entry. With a blank authority, the owner can write every entry only while `ownerCannotWrite` is off. Holders can write entries only for tokens they currently hold, and only while `holderCanWrite` is on. ### Events and keys @@ -116,6 +116,6 @@ Token id 0 is not special. Put collection-level data in the contract URI. - The NFT's page shows that the token is bound to an agent, from the adapter's `AgentBound` event. - The agent card shows on the agent's identity item in the ERC-8004 registry, read from the agent URI. -- OpenSea doesn't read ERC-8048 records. Anything OpenSea should show, such as the name, image and traits, goes in the `tokenURI` JSON. Don't copy agent keys such as `context` or `endpoint[mcp]` into that JSON: ERC-8495, the draft standard for `tokenURI` JSON, asks for field names of lowercase letters, digits and underscores that won't collide with future extensions. +- OpenSea does not automatically interpret arbitrary ERC-8048 agent records. The token's name, image and traits come from its `tokenURI` metadata. Explicit ERC-8493 `onchain:` URIs in that metadata, or returned by `tokenURI`, can resolve values stored through ERC-8048; see [Metadata storage](https://docs.opensea.io/docs/metadata-storage). Don't copy agent keys such as `context` or `endpoint[mcp]` into that JSON: ERC-8495, the draft standard for `tokenURI` JSON, asks for field names of lowercase letters, digits and underscores that won't collide with future extensions. - OpenSea refreshes a token's metadata when it sees an ERC-4906 event, and every record write to a minted token emits one. - Agents created with the adapter's `counterfactualRegister` are not indexed. From 1a024eff5781e403ede6f0d4fb745c2d8cd8c369 Mon Sep 17 00:00:00 2001 From: Ryan Ghods Date: Tue, 17 Nov 2026 11:34:32 -0800 Subject: [PATCH 8/8] Associate the invariant handler with its fuzzing interface --- test/v3/SeaDropMinterInvariant.t.sol | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/test/v3/SeaDropMinterInvariant.t.sol b/test/v3/SeaDropMinterInvariant.t.sol index 3257f319..c2bfd229 100644 --- a/test/v3/SeaDropMinterInvariant.t.sol +++ b/test/v3/SeaDropMinterInvariant.t.sol @@ -517,6 +517,11 @@ contract SeaDropMinterInvariantTest is StdInvariant, Test { selectors[7] = handler.donate.selector; selectors[8] = handler.rejectPayment.selector; selectors[9] = handler.rejectOwnerSupply.selector; + // Etched handlers need an explicit artifact association so Forge can + // generate typed calldata for the selected action functions. + string[] memory artifacts = new string[](1); + artifacts[0] = "SeaDropMinterInvariant.t.sol:SeaDropInvariantHandler"; + targetInterface(FuzzInterface(address(handler), artifacts)); targetSelector(FuzzSelector(address(handler), selectors)); targetContract(address(handler)); }