Skip to content

Add v3 accounting invariants and run CI on v3 pushes - #237

Merged
ryanio merged 9 commits into
v3from
ryan/v3-invariants
Nov 17, 2026
Merged

ryanio merged 9 commits into
v3from
ryan/v3-invariants

Conversation

@ryanio

@ryanio ryanio commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

SeaDrop v3 now runs CI on pushes to v3 as well as PRs. Add a stateful Foundry campaign that checks native and ERC-20 payment conservation, exact outstanding payout credits, actor balances, token delivery, and cumulative wallet and supply accounting across public and signed stages.

The handler interleaves paid mints, signed intents, owner mints, cap changes, failed payouts, successful and failed withdrawals, and unsolicited surplus. It also attempts unauthorized recipient redirects, invalid signatures, unauthorized owner mints, intent replay, wallet/stage limit violations, owner-mint max-supply violations, native underpayment and fee-on-transfer ERC-20 underpayment. An independent model tracks requested quantities and prices; assertions compare it against actual balances and minter accounting. Both currencies and their liabilities share one minter.

Each campaign starts with successful mints and withdrawals plus rejected calls, so an all-revert run cannot pass. Unexpected handler reverts fail the campaign. Foundry runs 128 sequences of 64 calls. Existing tests and assertions are unchanged; no production contract code or bytecode changes.

The outer test deploys the existing fixture and passes its minter and tokens to a normally deployed handler. The handler reuses signing helpers but overrides setup without embedding fixture deployment. Production code-size limits and CI size checks remain unchanged.

The audit scope now describes this coverage. Further adversarial callback, currency and delegation cases remain part of audit preparation in #235.

Validation: pinned formatting and lint pass locally. Tests, coverage and contract-size checks run in CI; no local test suite or Docker was used.

ryanio and others added 2 commits November 17, 2026 10:58
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](ethereum/ERCs#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 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The invariant handler exceeds EIP-170’s runtime size limit, causing deployment to fail during setup and preventing the invariant campaign from running.

1 open issue
What changed in this PR

Adds stateful accounting checks for SeaDrop v3 and enables CI on v3 pushes, supporting audit preparation tracked in #235. No production contract code changes are included.

Changes:

  • Adds modeled checks for payments, payout credits, token delivery, wallet limits, supply, and rejected calls.
  • Configures 128 invariant sequences of 64 calls, with unexpected reverts treated as failures.
  • Enables CI on v3 pushes and documents the new coverage.
File Description
test/​v3/​SeaDropMinterInvariant.t.sol Adds the stateful handler and accounting invariant campaign.
foundry.toml Sets invariant run count, depth, and revert behavior.
docs/​v3/​AuditScope.md Documents stateful accounting and rejection-path coverage.
.github/​workflows/​test.yml Adds v3 to CI push triggers.

Review effort: Balanced

Comment thread test/v3/SeaDropMinterInvariant.t.sol Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues are reported for the invariant-testing and CI changes.

1 open issue

Review effort: Balanced

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.
@ryanio
ryanio requested a balanced review from Copilot November 17, 2026 19:34
@ryanio
ryanio merged commit 5d9f725 into v3 Nov 17, 2026
3 of 5 checks passed
@ryanio
ryanio deleted the ryan/v3-invariants branch November 17, 2026 19:35

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues are recorded for the stateful invariant tests and v3 CI changes.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@ryanio
ryanio requested a balanced review from Copilot November 17, 2026 19:38
ryanio added a commit that referenced this pull request Nov 17, 2026
The v3 invariant suite merged in #237 cannot start its randomized
campaign: Forge reports that the etched handler address has no
associated contract for `targetSelectors`. The seeded setup calls
succeed, but the campaign runs zero calls.

Deploy the existing minter/token fixture in the outer test and pass
those references to a normally deployed handler. The handler still
reuses the shared signing helpers, but its setup does not embed the
fixture's deployment code. This removes `deployCodeTo` and
`targetInterface`, preserves all ten randomized actions and every
assertion, and keeps production size limits unchanged.

Validation: pinned formatting and lint pass. Test execution and coverage
run in CI only, with no Docker or local test suite.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The test still uses deployCodeTo and deployment-heavy super.setUp() rather than the described injected-fixture refactor, leaving the implementation inconsistent with the PR description and review reply.

1 open issue

Review effort: Balanced

Comment on lines +474 to +477
deployCodeTo(
"SeaDropMinterInvariant.t.sol:SeaDropInvariantHandler",
handlerAddress
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants