Skip to content

feat(peanut): vendor Peanut V4.4 + EnvelopeApprovalPaymaster, deploy to ZkSync Sepolia#115

Open
Douglasacost wants to merge 30 commits into
mainfrom
feat/peanut-protocol
Open

feat(peanut): vendor Peanut V4.4 + EnvelopeApprovalPaymaster, deploy to ZkSync Sepolia#115
Douglasacost wants to merge 30 commits into
mainfrom
feat/peanut-protocol

Conversation

@Douglasacost
Copy link
Copy Markdown
Collaborator

@Douglasacost Douglasacost commented May 13, 2026

Summary

  • Vendors Peanut Protocol V4.4 (vault + batcher) from peanutprotocol/peanut-contracts@main under src/envelope/ with OZ-v5 / ZkSync-aligned patches, security hardening, and a full Peanut → Envelope rebrand (contract symbols, source files, directories, env vars, salt constant — only GPL-required attribution + factual upstream identification still mention Peanut).
  • Adds EnvelopeApprovalPaymaster — a single paymaster with two modes:
    • Mode A sponsors user-side approve(envelope, …) / setApprovalForAll(envelope, true) for Path C, gated by an EIP-712 grant signed off-chain by the operator (supports both EOA and EIP-1271 contract signers).
    • Mode B sponsors operator-EOA calls to allowlisted targets (e.g. vault.makeCustomDeposit, vault.withdrawDeposit) — no grant required, the operator's allowlist membership is the auth.
  • Wires Hardhat-zksync deploy scripts and ships the full stack to ZkSync Sepolia, all contracts verified.
  • Adds src/envelope/doc/ with one spec markdown per contract, plus a clear mixed-license layout.
  • GPL-3.0-or-later compliance pass: bundled GPL text, file-level modification notices, derivative test files relicensed.
  • Tests adapted to repo style (*.t.sol, named imports, serious-only comments) and significantly extended with edge-case + reentrancy + Mode B + EIP-1271 coverage on top of the vendored upstream suite.

What's in this branch

Commit Scope
34180c0 Vendor Peanut V4.4 under OZ v5
1f677da <address>.transfer().call{value:}("") (EraVM-safe)
12a77ce Security hardening + ZkSync alignment (S1–S4 + Z1–Z4 + M1–M3 + T1–T4)
bc2ae42 Foundry deploy script (superseded)
e15a351 Switch to Hardhat-zksync deploy (canonical for this repo)
265c5c8 Move mocks out of src/ into test/peanut/mocks/
051edcf PeanutApprovalPaymaster first cut
040626c Paymaster inherits BasePaymaster (drop duplication)
cc12351 Split paymaster validation into helpers (fix zksolc stack-too-deep at verify)
2b2f0c6 Rename Peanut → Envelope on the paymaster, drop token allowlist, add per-tx ETH cap
15599a0 Spec sheet per contract
d2b2c12 T5 regression — pin the L2ECO withdrawal bug fix with two new tests
149e192 Spellcheck whitelist + fix own typos
09812ee Fix 12 upstream typos in vendored copy
f25eca5 Tests adapted to repo style + 20 new edge-case tests
8fe7adb .solhintignore for vendored sources (preserve upstream require-string style)
fb450f5 Address 4 Copilot review findings: SignatureChecker for EIP-1271, batcher ETH-iteration bug, SPDX consistency, ecoAddress immutable
3a76b01 Mode B — operator-EOA + allowlisted-target sponsorship
0db2d21 Spec catch-up to Mode B + earlier hardening
db71727 Seed Mode B from deploy script + Sepolia address refresh
1fcbcf0 Remove unused PeanutV4Router (no Squid integration on Nodle)
c47e402 Drop residual router note from README
be97cd1 GPL-3.0-or-later compliance: bundled license text, file-level modification notices, derivative test files relicensed
9989954 Rename contract symbols PeanutV4EnvelopeVault, PeanutBatcherV4EnvelopeBatcher; EIP-712 vault domain "Peanut""Envelope"
8cf63eb Cosmetic cleanup: env vars (PEANUT_*ENVELOPE_*), test + doc filenames
74db895 Rename directories src/peanut/src/envelope/, test/peanut/test/envelope/
d0af357 Full sweep: DeployPeanut.tsDeployEnvelope.ts, test class names, local var names, PEANUT_SALTENVELOPE_SALT (value preserved), comments
9bca40a Rename source files PeanutV4.4.solEnvelopeVault.sol, PeanutBatcherV4.4.solEnvelopeBatcher.sol

Deployed on ZkSync Sepolia (chain 300)

Redeployed 2026-05-13 after the Envelope rebrand — the EIP-712 vault domain name flipped from "Peanut" to "Envelope", and the paymaster's immutable envelopeVault had to follow the new vault. Old addresses drained, fully retired.

Contract Address
EnvelopeVault 0x37dbCC12784727AdE2A78AFbcb686b0eb915574f
EnvelopeBatcher 0xe8c0aEC0F90f99968B2bf517ECa2BBd41A4926c1
EnvelopeApprovalPaymaster (Mode A + Mode B) 0x842fe6fC8358c5eeBf5b7dA4E8546DB3d8ADA268

All three verified. Paymaster funded with 0.0015 ETH; Mode B seeded with the deployer EOA as operator and the vault as allowed target. Vault DOMAIN_SEPARATOR sanity-checked on-chain against {name: "Envelope", version: "4.4", chainId: 300, verifyingContract: vault}.

License posture

This subtree mixes licenses. The repo-root LICENSE (Clear BSD) doesn't apply uniformly here; see src/envelope/doc/README.md for the full layout.

Files License Notes
src/envelope/V4/EnvelopeVault.sol, EnvelopeBatcher.sol GPL-3.0-or-later Modified vendored copies (originally PeanutV4.4.sol / PeanutBatcherV4.4.sol). Full GPL v3 text bundled at src/envelope/V4/LICENSE-GPL. Each carries a top-of-file Modified by Nodle notice per GPL §5(a).
src/envelope/util/IEIP3009.sol, IL2ECO.sol MIT Vendored interfaces, unchanged
src/paymasters/EnvelopeApprovalPaymaster.sol BSD-3-Clause-Clear Our code; doesn't import GPL → not derivative
test/envelope/**/*.t.sol (files importing the vault/batcher) GPL-3.0-or-later Strict-derivative reading per GPL
All other repo files unchanged

The OSI's "mere aggregation" interpretation covers the rest of the repo (independent files in the same git repo aren't infected).

Compliance is technical, not legal advice. Counsel should sign off before mainnet.

Naming convention

  • Source files (now EnvelopeVault.sol, EnvelopeBatcher.sol) carry full attribution to upstream via SPDX header + // Modified by Nodle notice + // @author Squirrel Labs block + LICENSE-GPL bundle + git history. The original Peanut filenames are preserved in commit history (rename detected as ≥99% similarity).
  • Contract symbols (EnvelopeVault, EnvelopeBatcher, EnvelopeApprovalPaymaster) use the Envelope brand — what shows up on the explorer / in the SDK / in the EIP-712 domain.
  • On-chain hashed constants (ENVELOPE_SALT, formerly PEANUT_SALT) keep upstream values — the symbol was renamed, but the hash 0x70adbbeb…d94e0 stays so the signature scheme remains compatible with anything that uses the upstream Peanut digest format.

Security hardening applied at vendoring

  • S1onERC{721,1155,1155Batch}Received revert on non-self operator (upstream silently dropped direct transfers, stranding tokens)
  • S3MFA_AUTHORIZER: hardcoded constant → immutable constructor arg
  • S4_storeDeposit rejects pubKey20 == 0 && recipient == 0 (would otherwise be claimable by anyone)
  • T5 upstream bug fix_withdrawDeposit L2ECO branch was sending to _deposit.senderAddress instead of _recipientAddress; recipients claiming L2ECO links would silently receive nothing while the deposit was marked claimed. The other four contractType branches (ETH, ERC-20, ERC-721, ERC-1155) all correctly target _recipientAddress — this was a copy-paste from the parallel _withdrawDepositSender function. Fix: route to _recipientAddress and use SafeERC20.safeTransfer. Pinned by two regression tests in test/envelope/EnvelopeHardening.t.sol; the first was confirmed to FAIL against the upstream-bug code path before reverting to the fix.
  • ecoAddress — promoted to immutable (matches MFA_AUTHORIZER, slight gas saving)

(S2 originally hardened PeanutRouter.withdrawFees to use SafeERC20.safeTransfer — moot now that the router is gone.)

ZkSync alignment

  • All vendored pragmas pinned to 0.8.26
  • <address>.transfer().call{value:}("") everywhere (EraVM rejects the 2300-gas stipend)
  • EnvelopeBatcher dropped public peanut storage var → local per call (saves pubdata)
  • EnvelopeBatcher.batchMakeDepositNoReturn now requires msg.value == _amount * N for ETH and msg.value == 0 for non-ETH (fixes a latent upstream bug where iteration 2 would revert with insufficient balance)
  • All raw IL2ECO.transfer* switched to SafeERC20
  • Hardhat config skips L1-only / Anvil-only sources (SwarmRegistryL1Upgradeable, FleetIdentity.t.sol, TestUpgradeOnAnvil.s.sol) so yarn hardhat compile works
  • deployPaths: ["hardhat-deploy"] added so deploy-zksync finds the scripts
  • .solhintignore for vendored sources (preserve upstream's require-string style; our own contracts use custom errors and remain lint-checked)

EnvelopeApprovalPaymaster — single paymaster, two modes, one ETH pool

Mode Caller Auth gate What it sponsors
A regular user EIP-712 grant signed by operatorSigner (verified via SignatureChecker.isValidSignatureNow — supports EOA + EIP-1271 contract signers) + selector check + spender check token.approve(envelope, …) / setApprovalForAll(envelope, true)
B operator EOA on isOperator allowlist tx.to on isAllowedTarget allowlist Anything (e.g. vault.makeCustomDeposit, vault.withdrawDeposit)

Both modes share maxEthPerTx and the QuotaControl daily counter. Single ETH top-up funds both flows.

Mode A flow (Path C): operator backend signs EnvelopeApprovalGrant(user, deadline, nonce) off-chain → user attaches (deadline, nonce, signature) in paymasterParams → user signs and submits the approve tx → paymaster validates and pays the bootloader.

Mode B flow (operator gas pool): admin allowlists operator EOAs and target contracts (e.g. envelope vault). Operator submits any tx to allowlisted target with paymaster params → paymaster pays gas. Rotating operators is one tx (setOperator(newEOA, true) + setOperator(oldEOA, false)) — no balance migration.

EIP-712 domain names (for backend integrations)

Surface Domain name Notes
Vault gasless reclaim (GaslessReclaim) "Envelope" renamed from "Peanut" in 9989954 — backend signing code that calls the vault's gasless reclaim path needs the new domain name
Paymaster grants (EnvelopeApprovalGrant) "EnvelopeApprovalPaymaster" unchanged

Test suite (966 / 966 pass)

Envelope tests — 90 tests

  • 56 vendored
  • 11 hardening (S1, S3, S4, S5 + T5 L2ECO regression)
  • 23 edge cases (deposit/withdraw input validation, views, reentrancy, batcher input validation, L2ECO inflation accounting)

Paymaster tests — 27 tests

  • Mode A — 19 tests (per-gate revert + happy paths + period rollover + admin gates + EIP-1271 contract signer)
  • Mode B — 7 tests (operator + allowed-target happy path, TargetNotAllowed, fall-through to Mode A, per-tx cap shared, quota shared, operator revocation, non-admin can't manage allowlists)
  • EIP-1271 — 1 test (SCW as operatorSigner)

Rest of repo — 849 tests, no regressions

Test plan checklist

  • forge test — 966 / 966 pass
  • yarn lint — 0 errors
  • yarn spellcheck — 0 issues / 242 files
  • yarn hardhat compile — clean
  • forge build --zksync — peanut clean (only cosmetic warnings)
  • T5 regression verified end-to-end: temporarily reintroduced the bug, confirmed test_T5_L2ECOWithdrawGoesToRecipientNotSender fails with recipient must receive the L2ECO tokens: 0 != 100; restored the fix → green again
  • Sepolia deploy verified end-to-end (Path C ready: paymaster Mode A grant flow + Mode B operator pool both seeded against the new vault)
  • GPL-3.0-or-later compliance pass: license text bundled, modification notices added, derivative test files relicensed
  • Full Peanut → Envelope rebrand: contract symbols + source files + directories + env vars + deploy script + salt constant + comments. Only GPL-required attribution + factual upstream identification still mention Peanut.
  • Counsel to sign off on the GPL compliance posture for mainnet (technical compliance ≠ legal sign-off)
  • Reviewer to decide if IL2ECO / contractType==4 rebasing branches should be kept (Nodle has no rebasing token today)

Test style alignment with repo

  • All vendored test files renamed to *.t.sol and live under test/envelope/
  • Dead stubs deleted (testBatch.sol, Batch/, hardhat/PeanutV4.1.spec.ts)
  • Casual comments replaced with serious technical ones
  • 12 upstream comment typos fixed in our copy (no bytecode impact)

What still says "Peanut" — and why each one stays

Where Reason
// @title Peanut Protocol, // @author Squirrel Labs, peanutprotocol/peanut-contracts@main in vendored sources Required by GPL §5(d) — must keep author/copyright notices
ENVELOPE_SALT preimage comment "Konrad makes tokens go woosh tadam" Documents how the constant value was derived; auditor can recompute the hash
.solhintignore / deploy script header / README mentions of "vendored Peanut V4.4" Factual identification of what we vendored

Docs

src/envelope/doc/:

  • README.md — overview, deployed addresses, license notice, naming convention, three deposit paths, test totals
  • EnvelopeVault.md — full vault spec
  • EnvelopeBatcher.md — batcher spec
  • EnvelopeApprovalPaymaster.md — paymaster spec covering both modes, gates per mode, threat model split (shared / Mode A / Mode B), backend signing skeleton, operational seeding

.env-test updates required (local file, not in git)

ENVELOPE_VAULT=0x37dbCC12784727AdE2A78AFbcb686b0eb915574f
ENVELOPE_BATCHER=0xe8c0aEC0F90f99968B2bf517ECa2BBd41A4926c1
ENVELOPE_PAYMASTER=0x842fe6fC8358c5eeBf5b7dA4E8546DB3d8ADA268
ENVELOPE_MFA_AUTHORIZER=…    # whatever was previously in PEANUT_MFA_AUTHORIZER

(Drop the old PEANUT_* keys.)

Follow-ups (not in this PR)

  • Counsel sign-off on the GPL compliance posture before mainnet
  • Decide if IL2ECO / contractType==4 rebasing branches should be kept (Nodle has no rebasing token today)

Imports peanutprotocol/peanut-contracts V4.4 (vault + batcher + router)
plus EIP-3009 mocks, sample SCW, and Squid mock into src/peanut/, with
the squirrel-labs test suite under test/peanut/.

OZ v5 patches applied during vendoring:
- ReentrancyGuard moved from security/ to utils/
- ECDSA.toEthSignedMessageHash -> MessageHashUtils
- SafeERC20.safeApprove -> forceApprove
- Ownable constructor takes initial owner explicitly
- EIP3009Implementation marks interface fns override

60/60 peanut tests pass. Open follow-ups: MFA_AUTHORIZER hardcoded to
upstream key, no deploy script yet, IL2ECO branches kept (unused on Nodle).
ZkSync rejects <address>.transfer() under the sendtransfer error policy
because the 2300 gas stipend isn't safe under EraVM pubdata costs.
This was the only native .transfer() in the peanut suite — IERC20.transfer
calls elsewhere are fine.
Security fixes:
- ERC721/1155 receivers now revert on direct (non-self) transfers instead
  of silently dropping (was: implicit return bytes4(0); some tokens accepted
  it and the assets got stuck with no recovery path)
- PeanutRouter.withdrawFees uses SafeERC20.safeTransfer (works with USDT
  and other non-bool-returning ERC20s)
- MFA_AUTHORIZER promoted from hardcoded constant to immutable constructor
  arg, so each deploy can pick its own signer (or address(0) to disable)
- _storeDeposit rejects deposits with both pubKey20 == 0 and recipient == 0
  (would otherwise be claimable by anyone)
- Fixed upstream bug: _withdrawDeposit's L2ECO branch was sending tokens to
  senderAddress instead of recipientAddress; now correct
- PeanutRouter switched to Ownable2Step (safer ownership handoff)

ZkSync-aligned patterns:
- Pragma pinned to 0.8.26 (matches repo, aligns with zksolc)
- Batcher dropped public PeanutV4 storage var; uses local in each call so
  EraVM doesn't charge pubdata for every batch invocation
- Explicit override(IERC165) on supportsInterface for stricter solc/zksolc
- All raw IL2ECO transfer/transferFrom calls replaced with SafeERC20

Modernization:
- Named imports throughout
- Cleaner NatSpec on constructors and public methods
- Removed unused parameter names from receiver hooks (silences zksolc warns)

Tests:
- Updated all `new PeanutV4(address(0))` call sites to the 2-arg constructor
- testMFA pins LEGACY_MFA_AUTHORIZER (the upstream Squirrel address) so its
  pre-baked authorization signature still verifies
- New PeanutHardening.t.sol with 11 tests covering each fix above

71/71 peanut tests pass (60 vendored + 11 hardening).
849/849 rest-of-repo tests still pass — no regressions.
zksolc compiles peanut clean (only cosmetic warnings; pre-existing repo-level
zksync errors in SwarmRegistryL1Upgradeable / FleetIdentity.t.sol /
TestUpgradeOnAnvil.s.sol are unrelated).
Three-step deploy: PeanutV4 (always), PeanutBatcherV4 (default on),
PeanutV4Router (default off — only useful for cross-chain via Squid).

Env-driven config:
- ECO_TOKEN:      gates contractType==1 deposits from a rebasing token (default 0)
- MFA_AUTHORIZER: per-deploy MFA signer; 0 disables MFA (default 0)
- DEPLOY_BATCHER: skip the batcher if not needed (default true)
- DEPLOY_ROUTER:  enable the cross-chain router (default false)
- SQUID_ADDRESS:  required when DEPLOY_ROUTER=true
- ROUTER_OWNER:   if set, initiates Ownable2Step handoff to this address;
                  the new owner must call acceptOwnership() in a follow-up tx

Header documents the workaround for the repo's pre-existing zksolc errors
(SwarmRegistryL1 / FleetIdentity.t.sol / TestUpgradeOnAnvil) so users know
to pass --skip flags until those are wired into [profile.zksync].
The Foundry script never had a clean path on ZkSync because the repo's
zksolc compile graph picks up L1-only files (SwarmRegistryL1Upgradeable
uses EXTCODECOPY) that no per-script --skip flag can fully suppress.
Hardhat-zksync is what the team actually uses to deploy
(hardhat-deploy/DeployS*.ts), so mirror that pattern.

Changes:
- Drop script/DeployPeanutZkSync.s.sol — Foundry path was a dead end.
- Add hardhat-deploy/DeployPeanut.ts following the canonical
  DeploySwarmUpgradeable.ts pattern: zksync-ethers + Deployer +
  estimateDeployFee + verify:verify per contract. Same env-var surface as
  before (PEANUT_* prefix to avoid colliding with existing scripts).
- hardhat.config.ts:
  * Add a TASK_COMPILE_SOLIDITY_GET_SOURCE_PATHS subtask that filters out
    SwarmRegistryL1Upgradeable.sol, FleetIdentity.t.sol, and
    TestUpgradeOnAnvil.s.sol — files that can't compile under zksolc.
    All three are L1-only or Anvil-only test/script artifacts; excluding
    them from the zksync compile graph is a no-op for the L1 toolchain
    but unblocks every Hardhat-zksync command.
  * Add deployPaths: ["hardhat-deploy"] so deploy-zksync can locate scripts.

Verified:
- yarn hardhat compile: clean (141 files, peanut included)
- yarn hardhat deploy-zksync --script DeployPeanut.ts: runs end-to-end
  through config + estimate; only fails at the actual RPC connect when
  no zksync node is running locally (expected).
- forge test: 71/71 peanut + 849/849 rest-of-repo, no regressions.
Mock contracts have no business in the production source tree. They were
only there because the upstream peanut repo kept them in src/util/.

Moved to test/peanut/mocks/:
  - Mocks: ERC20Mock, ERC721Mock, ERC1155Mock, SampleSCW, SquidMock
  - EIP-3009 chain (only used by ERC20Mock to support gasless tests):
    EIP3009Implementation, EIP3009Internals, EIP712, EIP712Domain, ECRecover

Kept in src/peanut/util/ (used by production peanut code):
  - IEIP3009: interface PeanutV4 calls for receiveWithAuthorization
  - IL2ECO:   interface PeanutV4 calls for rebasing-token deposits

Updated imports:
  - Test files: ../../src/peanut/util/X.sol -> ./mocks/X.sol
  - EIP3009Internals + EIP3009Implementation: ./IEIP3009.sol ->
    ../../../src/peanut/util/IEIP3009.sol (still need the production interface)

Verified:
  - forge build: clean
  - forge test peanut: 71/71 pass
  - hardhat compile: 125 files (was 141 - mocks no longer in production
    compile path, leaner zksolc graph)
…alForAll for the peanut vault

Existing WhitelistPaymaster only inspects (from, to); it can't safely sponsor
token approval txs because the inner selector and spender argument are
invisible to it. This paymaster checks every layer:

  - tx.to must be on a per-token allowlist (admin-curated)
  - inner selector must be approve(address,uint256) or
    setApprovalForAll(address,bool) — same selectors cover ERC-20/721/1155
  - inner first arg (spender/operator) must equal the configured peanutVault
  - tx.from must hold an unexpired EIP-712 grant signed by operatorSigner
    (signature passed in paymasterInput; nonce single-use; no per-user
    onchain whitelist tx needed)
  - global wei-per-period quota via QuotaControl (existing repo pattern)

Doesn't extend BasePaymaster because that base hides transaction.data
behind a (from, to, requiredETH) hook. Instead inherits IPaymaster +
QuotaControl directly and re-implements the bootloader gate inline (~5
lines).

EraVM rules permit writes to paymaster's own storage during validation
(used here for nonce + quota state).

Tests: 19/19 covering happy paths (approve, setApprovalForAll), all 9
revert paths (non-bootloader, wrong flow, expired grant, reused nonce,
wrong signer, wrong user, disallowed token, unsupported selector, wrong
spender, exceeded quota, insufficient balance), quota period rollover,
and admin role gates.
The previous standalone version duplicated bootloader-check logic,
WITHDRAWER_ROLE, Withdrawn event, withdraw(), postTransaction(),
receive(), and the BOOTLOADER_FORMAL_ADDRESS constant.

One-keyword change to BasePaymaster: mark
validateAndPayForPaymasterTransaction as `virtual` so subclasses can
override it when they need access to the full Transaction calldata
(the existing `_validateAndPayGeneralFlow` hook hides `transaction.data`
and `transaction.paymasterInput` by design).

WhitelistPaymaster and BondTreasuryPaymaster are untouched — they
continue to override the internal hook through BasePaymaster's default
outer-function implementation.

PeanutApprovalPaymaster now:
  - is BasePaymaster, QuotaControl
  - overrides validateAndPayForPaymasterTransaction with full peanut-
    specific validation
  - implements the two abstract internal hooks as reverts (general:
    Unused; approvalBased: PaymasterFlowNotSupported)
  - drops 9 lines net of duplication (37 deleted, 28 added)
  - inherits withdraw / postTransaction / receive / Withdrawn /
    AccessRestrictedToBootloader / WITHDRAWER_ROLE / BOOTLOADER_FORMAL_ADDRESS

Tests: 939/939 (19 paymaster-specific + 102 other paymaster tests
including WhitelistPaymaster/BondTreasuryPaymaster suites untouched +
all peanut and rest-of-repo tests). Behavior unchanged externally.

Also adds hardhat-deploy/DeployPeanutPaymaster.ts (Hardhat-zksync
deploy script that matches existing patterns; takes PEANUT_V4 and
operator signer from env, optionally funds + seeds token allowlist).
…maller helpers

validateAndPayForPaymasterTransaction was too dense for zksolc's legacy
codegen — 17 active locals tripped stack-too-deep at the explorer's
verification compile (zksolc doesn't accept Solidity's viaIR flag because
it translates legacy IR to EraVM directly).

Split the validation into 4 internal helpers, each scope <16 locals:
  - _requireGeneralFlow(paymasterInput) — flow selector check
  - _verifyAndConsumeGrant(user, paymasterInput) — EIP-712 grant decode,
    expiry/nonce check, signature recover, nonce mark-used
  - _requireApprovalCallToPeanut(data) — inner selector + spender check
  - _payBootloader(requiredETH) — balance, quota, transfer

Same behavior, just structurally lighter. All 19 paymaster tests pass.

Deployed + verified on ZkSync Sepolia at
0x301DB88e0AdD434CBac07ef3F4207C16E4dEb6a0 (operator signer
0xc1F2A7b888e4837aFACfc5E914AB647476ceCD46, vault
0xC241FE8Af12Cf35Eb346eA8eC3AECFCF6F6c2C44, quota 0.1 ETH/day).
…dd per-tx ETH cap

The per-token allowlist was operator-side ceremony with little marginal safety:
the operator already curates which tokens get grants (by deciding what tx the
backend builds in step 2 of Path C). Removing it cuts an admin workflow.

Replaced with a per-tx ETH cap (`maxEthPerTx`, immutable, constructor-set) so
the worst-case drain under operator-key compromise is bounded per tx, not per
token. Combined with the existing daily QuotaControl cap, the security envelope
is equivalent for honest operation, tighter under compromise.

Renames (paymaster surface only; the vault keeps the upstream PeanutV4 name):
  - PeanutApprovalPaymaster        → EnvelopeApprovalPaymaster
  - peanutVault state              → envelopeVault
  - SpenderNotPeanut error         → SpenderNotEnvelope
  - EIP-712 domain name string     → "EnvelopeApprovalPaymaster"
  - GRANT_TYPEHASH                 → keccak256("EnvelopeApprovalGrant(...)")
  - file + test + deploy script names
  - all NatSpec and comments

NOTE: changing the EIP-712 domain name invalidates the signatures that would
verify against the previously-deployed paymaster at 0x301D...b6a0. That
contract is functionally orphaned now — needs a redeploy of the new bytecode
to a fresh address.

Tests: 19/19 envelope-paymaster (covers per-tx-cap, exceeded-quota via
constructor-tightened paymaster instance, sponsorship works on any token,
all the per-gate reverts). Full repo: 939/939, no regressions.
Mirrors src/swarms/doc/ convention. One markdown file per deployable contract:

  README.md                       — overview, deployed addresses, file map
  PeanutV4.md                     — vault: deposit + withdraw paths, signature
                                    scheme, dual-zero invariant, vendoring
                                    patches, threat model
  PeanutBatcherV4.md              — batcher: stateless design, per-asset pull
                                    pattern, ERC-721-not-implemented rationale
  PeanutRouter.md                 — router: EIP-191 v0x00 routing sig, fee
                                    paths, Ownable2Step note
  EnvelopeApprovalPaymaster.md    — paymaster: 5-gate validation, EIP-712
                                    grant schema, backend signing skeleton,
                                    deliberate drops vs. earlier iterations

735 lines total. Lives in src/peanut/doc/ even though the paymaster source
is at src/paymasters/ — the Envelope product spans both directories.
@github-actions
Copy link
Copy Markdown

github-actions Bot commented May 13, 2026

LCOV of commit 5f9f8ca during checks #689

Summary coverage rate:
  lines......: 26.2% (771 of 2945 lines)
  functions..: 22.5% (105 of 467 functions)
  branches...: 25.3% (140 of 554 branches)

Files changed coverage rate:
                                                  |Lines       |Functions  |Branches    
  Filename                                        |Rate     Num|Rate    Num|Rate     Num
  ======================================================================================
  src/envelope/V4/EnvelopeBatcher.sol             | 0.0%     95| 0.0%    10| 0.0%     39
  src/envelope/V4/EnvelopeVault.sol               | 0.0%    177| 0.0%    29| 0.0%     83
  src/paymasters/BasePaymaster.sol                | 0.0%     33| 0.0%     5| 0.0%      8
  src/paymasters/EnvelopeApprovalPaymaster.sol    | 0.0%     67| 0.0%    11| 0.0%     18
  test/envelope/EnvelopeEdgeCases.t.sol           | 0.0%     11| 0.0%     2| 0.0%      2
  test/envelope/EnvelopeHardening.t.sol           | 0.0%      4| 0.0%     1|    -      0
  test/envelope/mocks/ECRecover.sol               | 0.0%      8| 0.0%     1| 0.0%      4
  test/envelope/mocks/EIP3009Implementation.sol   | 0.0%      6| 0.0%     3|    -      0
  test/envelope/mocks/EIP3009Internals.sol        | 0.0%     32| 0.0%     7| 0.0%     14
  test/envelope/mocks/EIP712.sol                  | 0.0%      7| 0.0%     2|    -      0
  test/envelope/mocks/ERC1155Mock.sol             | 0.0%      4| 0.0%     2|    -      0
  test/envelope/mocks/ERC20Mock.sol               | 0.0%      3| 0.0%     2|    -      0
  test/envelope/mocks/ERC721Mock.sol              | 0.0%      3| 0.0%     2|    -      0
  test/envelope/mocks/L2ECOMock.sol               | 0.0%      8| 0.0%     4|    -      0
  test/envelope/mocks/SampleSCW.sol               | 0.0%      3| 0.0%     1|    -      0

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR vendors Peanut Protocol V4.4 (vault, batcher, router) into src/peanut/, adds an operator-gated EnvelopeApprovalPaymaster for zkSync “Path-C” sponsored approval transactions, and wires Hardhat-zksync deploy + verification scripts plus contract specs.

Changes:

  • Added Peanut V4.4 core contracts (vault + batcher + router) with zkSync/OZ v5 alignment and hardening.
  • Added EnvelopeApprovalPaymaster (EIP-712 operator grant gating + per-tx ETH cap + quota control) and Foundry tests for it.
  • Added Hardhat-zksync deployment scripts, updated Hardhat compilation settings, and added per-contract markdown specs under src/peanut/doc/.

Reviewed changes

Copilot reviewed 42 out of 42 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
hardhat.config.ts Filters out zksolc-incompatible sources and configures deploy script discovery via deployPaths.
hardhat-deploy/DeployPeanut.ts Hardhat-zksync deployment + verification script for Peanut vault/batcher/router.
hardhat-deploy/DeployEnvelopePaymaster.ts Hardhat-zksync deployment + verification script for EnvelopeApprovalPaymaster.
src/paymasters/BasePaymaster.sol Makes validateAndPayForPaymasterTransaction virtual to allow specialization.
src/paymasters/EnvelopeApprovalPaymaster.sol Implements operator-signed EIP-712 grant gating for sponsored approve / setApprovalForAll.
src/QuotaControl.sol (Context) quota mechanism consumed by the new paymaster for daily caps.
src/peanut/V4/PeanutV4.4.sol Vendored Peanut V4.4 vault with hardening + zkSync/OZ v5 patches.
src/peanut/V4/PeanutBatcherV4.4.sol Stateless batch deposit helper for Peanut V4.4 with zkSync alignment.
src/peanut/V4/PeanutRouter.sol Cross-chain router via Squid; Ownable2Step + SafeERC20 fee withdrawal.
src/peanut/util/IEIP3009.sol EIP-3009 interface for gasless token deposits.
src/peanut/util/IL2ECO.sol Interface for ECO-like rebasing multiplier reads.
src/peanut/doc/README.md High-level Envelope/Peanut layout, deposit paths, deploy pointers, and test counts.
src/peanut/doc/PeanutV4.md Vault spec detailing storage, flows, and hardening notes.
src/peanut/doc/PeanutBatcherV4.md Batcher spec and supported batch paths.
src/peanut/doc/PeanutRouter.md Router spec describing signature scheme and bridge flow.
src/peanut/doc/EnvelopeApprovalPaymaster.md Paymaster spec, grant format, validation gates, and backend signing skeleton.
test/paymasters/EnvelopeApprovalPaymaster.t.sol Foundry suite validating all paymaster gates, quota rollover, and admin/withdraw behavior.
test/peanut/PeanutHardening.t.sol Hardening tests for S1–S4/T1–T4 behaviors introduced during vendoring.
test/peanut/PeanutRouter.t.sol Router withdrawal + bridging tests, including fee-tampering resistance.
test/peanut/PeanutBatcher.t.sol Batcher tests for ETH/ERC20/ERC1155 batches and raffle flows.
test/peanut/PeanutV4.t.sol Core PeanutV4 behavior tests (deposits, withdrawals, ECO guard).
test/peanut/PeanutV4Gasless.t.sol Gasless reclaim + EIP-3009 style deposit tests.
test/peanut/RecipeintBound.t.sol Recipient-bound deposit and reclaim tests.
test/peanut/testDeposit.sol Deposit-path tests for ETH/ERC20/ERC721/ERC1155.
test/peanut/testIntegration.sol Integration tests verifying basic invariants across deposit/withdraw paths.
test/peanut/testMFA.sol MFA deposit + withdrawal flow tests.
test/peanut/testSenderWithdraw.sol Sender reclaim tests for ETH/ERC20/ERC721/ERC1155.
test/peanut/testSigWithdraw.sol Signature-based withdrawal tests for ETH.
test/peanut/testBatch.sol (Commented) legacy batch test scaffolding kept in-tree.
test/peanut/Batch/testBatchDeposit.sol (Commented) legacy batch deposit scaffolding.
test/peanut/Batch/testBatchDepositEther.sol (Commented) legacy ETH batch deposit scaffolding.
test/peanut/Batch/testBatchDepositEtherOptimized.sol (Commented) legacy optimized ETH batch scaffolding.
test/peanut/hardhat/PeanutV4.1.spec.ts Vendored Hardhat test for older Peanut behavior (smock-based).
test/peanut/mocks/ERC20Mock.sol ERC20 mock with EIP-3009 test implementation.
test/peanut/mocks/ERC721Mock.sol ERC721 mock used in Peanut tests.
test/peanut/mocks/ERC1155Mock.sol ERC1155 mock used in Peanut tests.
test/peanut/mocks/SquidMock.sol Squid mock used for router bridge call tests.
test/peanut/mocks/SampleSCW.sol Minimal EIP-1271-like sample SCW for gasless reclaim tests.
test/peanut/mocks/EIP712Domain.sol Fixed domain separator helper for EIP-3009 tests.
test/peanut/mocks/EIP712.sol EIP-712 helper library for EIP-3009 tests.
test/peanut/mocks/EIP3009Internals.sol Internal EIP-3009 logic used by mocks.
test/peanut/mocks/EIP3009Implementation.sol EIP-3009 surface implementation used by ERC20Mock.
test/peanut/mocks/ECRecover.sol ECDSA recover helper used by EIP-712/EIP-3009 helpers.

Comment thread src/paymasters/EnvelopeApprovalPaymaster.sol
Comment thread src/envelope/V4/EnvelopeBatcher.sol
Comment thread test/peanut/SigWithdraw.t.sol Outdated
Comment thread test/envelope/RecipientBound.t.sol
Comment thread test/envelope/MFA.t.sol Outdated
Comment thread src/envelope/doc/EnvelopeVault.md
Comment thread test/peanut/PeanutV4Gasless.t.sol Outdated
Upstream PeanutV4.4 had a copy-paste error in _withdrawDeposit's
contractType==4 branch: it transferred to _deposit.senderAddress instead
of _recipientAddress, so a recipient claiming an L2ECO link with a valid
signature would receive nothing — the tokens went back to the sender —
while the deposit was still marked claimed=true.

Two new tests pin the fix:

  test_T5_L2ECOWithdrawGoesToRecipientNotSender
    - sender deposits 100 L2ECO (multiplier=2 → 200 stored inflation-invariant)
    - recipient (not sender) claims with a valid signature
    - asserts: recipient gets 100, sender stays at 0, vault drained
    Confirmed to FAIL against the upstream-bug code path (verified by
    temporarily reintroducing the bug; test failed with
    'recipient must receive the L2ECO tokens: 0 != 100').

  test_T5_L2ECOSenderReclaimStillGoesToSender
    - sanity check: _withdrawDepositSender (separate function) still
      legitimately routes to senderAddress; the fix to _withdrawDeposit
      did not over-correct the parallel reclaim path

Adds test/peanut/mocks/L2ECOMock.sol — minimal ERC20 with a settable
linearInflationMultiplier(). No production code changes; bug fix itself
is in commit 12a77ce.

941/941 repo tests pass.
CI spell check reported 103 issues in 29 files (38 unique words) across
the vendored Peanut suite + my new code. Cleanup:

1. Fixed two typos I introduced:
   - test/paymasters/...: 'nonce-pertx' -> 'nonce-per-tx' (nonce string)
   - src/paymasters/...: 'EraVM's paymaster-validation rules' -> 'EraVM
     paymaster-validation rules' (apostrophe-s tripped cspell)

2. Whitelisted 38 words in .cspell.json:
   - Legitimate domain terms: Axelar, IEIP, calldataload, SECZ, secp,
     tadam, footgun, peanutprotocol, rollup, PRIVKEY, keypair, scwallet,
     gaslessly, Customisable, authorisation, arrayify, nomiclabs, defi,
     MAGICVALUE, unhashed, Hashbinary
   - Vendored upstream typos kept for diff parity (would be a real fix to
     pull from upstream later if they ever clean it up): contractype,
     Recipeint, DOESNT, Suuuuper, talkin, wooooooosh, pretent, Depost,
     alwasy, auhorisation, authorizattion, funfction, gsalessly, provied,
     fuceted

CI passes: 0 issues, 250 files checked. Repo tests unchanged.
All in comments, error strings, function names, or one filename — no
bytecode changes. With these fixed, the cspell whitelist shrinks by 12
entries; only intentional stylistic words remain (Suuuuper, talkin,
wooooooosh — all Peanut Protocol's "nutty" branding).

Source comments:
  src/peanut/V4/PeanutV4.4.sol
    - alwasy → always
    - auhorisation → authorisation
    - funfction → function

Test comments / strings / identifiers:
  test/peanut/PeanutV4.t.sol             pretent → pretend
  test/peanut/PeanutV4Gasless.t.sol      provied → provided, gsalessly → gaslessly
  test/peanut/PeanutV4Gasless.t.sol      testMakeDepost… → testMakeDeposit…
  test/peanut/PeanutRouter.t.sol         fuceted → faucet
  test/peanut/testMFA.sol                authorizattion → authorization
  test/peanut/testSenderWithdraw.sol     contractype → contractType
  test/peanut/mocks/SquidMock.sol        DOESNT → DOES NOT
  test/peanut/RecipeintBound.t.sol → RecipientBound.t.sol (file rename)
  src/peanut/doc/PeanutV4.md             doc reference updated to new filename

941/941 tests pass. Spellcheck: 0 issues / 250 files.
Style alignment with the rest of the repo:
  - File rename: testFoo.sol → Foo.t.sol (matches *.t.sol forge convention)
      testDeposit       → Deposit.t.sol
      testIntegration   → Integration.t.sol
      testMFA           → MFA.t.sol
      testSenderWithdraw → SenderWithdraw.t.sol
      testSigWithdraw   → SigWithdraw.t.sol
  - Delete dead stubs (all entirely commented out / unused):
      testBatch.sol
      test/peanut/Batch/{testBatchDeposit, testBatchDepositEther,
                         testBatchDepositEtherOptimized}.sol
      test/peanut/hardhat/PeanutV4.1.spec.ts  (Hardhat-ts test; repo is Foundry-primary)
  - Cleaned three casual comments to match the repo's serious tone (kept all
    serious/technical comments):
      "Suuuuper dumb squid mock"        → real NatSpec
      "Now we talkin'!"                  → "selfless deposit's owner can reclaim"
      "wooooooosh! Controlling the time" → "advance past reclaimableAfter"
  - Dropped {Suuuuper, talkin, wooooooosh} from .cspell.json whitelist.

New edge-case suite — test/peanut/PeanutEdgeCases.t.sol — 20 tests:
  PeanutV4 deposit input validation:
    - INVALID CONTRACT TYPE (contractType >= 5)
    - WRONG ETH AMOUNT (msg.value mismatch)
    - AMOUNT MUST BE 1 FOR ERC721
    - ECO via plain ERC-20 path rejected
  PeanutV4 withdraw input validation:
    - DEPOSIT INDEX DOES NOT EXIST
    - DEPOSIT ALREADY WITHDRAWN (double-claim)
    - WRONG SIGNATURE (signer mismatch)
    - NOT THE RECIPIENT (withdrawDepositAsRecipient caller mismatch)
    - WRONG RECIPIENT (address-bound deposit claimed by other)
    - TOO EARLY TO RECLAIM (recipient-bound sender reclaim before deadline)
    - NOT THE SENDER (non-sender reclaim)
    - REQUIRES AUTHORIZATION (MFA deposit, MFA_AUTHORIZER == 0)
  Views:
    - getDepositCount tracks length
    - getAllDepositsForAddress filters by sender
  Reentrancy:
    - Malicious ERC-20 reentering withdrawDeposit during safeTransfer is
      caught by nonReentrant (proves the guard works end-to-end).
  PeanutBatcherV4 input validation:
    - INVALID TOTAL ETHER SENT
    - PARAMETERS LENGTH MISMATCH (arbitrary batch)
    - ONLY ETH AND ERC20 RAFFLES ARE SUPPORTED (ERC-721 raffle path)
    - Zero-length pubKeys is a no-op
  L2ECO inflation accounting:
    - Withdraw at higher multiplier returns proportionally less (the
      inflation-invariant share is what the depositor banked).

961/961 repo tests pass (was 941; +20 new edge cases). Spellcheck: 0
issues / 246 files.
The repo's solhint config treats gas-custom-errors as an error (not a
warning). The vendored Peanut V4.4 / Batcher / Router use require-string
patterns extensively (~40 instances). Converting them to custom errors
would diverge significantly from upstream
(peanutprotocol/peanut-contracts@main) without any security or
correctness benefit — only a style change.

Add the three vendored Solidity files to .solhintignore so CI's lint job
passes. The new code in this PR (EnvelopeApprovalPaymaster, hardening
tests, edge-case tests, deploy scripts) already uses custom errors and
is NOT in the ignore list — it remains lint-clean.

Local: yarn lint → 0 errors / 175 warnings (warnings are non-blocking
and all pre-existing in non-peanut code).
Four issues raised by the Copilot review on PR #115:

1. EnvelopeApprovalPaymaster: switch operator-signature verification from
   ECDSA.recover to SignatureChecker.isValidSignatureNow, matching the
   constructor docstring's promise of EOA-or-contract signers. Now
   accepts EIP-1271 smart-contract operatorSigners (multisigs etc.).

2. PeanutBatcherV4.batchMakeDepositNoReturn: latent upstream bug — the
   inner call forwarded {value: msg.value} per loop iteration but the
   batcher only received msg.value once. For ETH batches with N > 1, the
   second iteration would revert with insufficient balance. Now requires
   msg.value == _amount * N for ETH and msg.value == 0 for non-ETH
   (prevents stuck dust in the vault too).

3. test/peanut/SigWithdraw.t.sol: SPDX `BUSL-1.1` → `UNLICENSED` to
   match the rest of the vendored test suite.

4. PeanutV4: `address public ecoAddress` → `immutable` (matches the
   doc + small gas saving; the value is set in constructor and never
   mutated).

New tests:
  - test_acceptsEip1271ContractSigner — proves SignatureChecker path
    accepts a SampleWallet (EIP-1271) as operatorSigner
  - test_BatchNoReturnEth_HappyPath — 3-deposit ETH batch round-trips
  - test_RevertWhen_BatchNoReturnEthAmountMismatch — total mismatch
  - test_RevertWhen_BatchNoReturnEthSentForErc20 — msg.value > 0 with
    ERC-20 path is rejected

forge test: 965/965 (was 961; +4 new). yarn lint: 0 errors. yarn
spellcheck: 0 issues.
…sorship

Single paymaster, two modes, one ETH pool:

  Mode A (existing): user-side approve / setApprovalForAll, gated by an
  EIP-712 grant signed off-chain by operatorSigner. Single-use nonce,
  deadline, selector + spender checks.

  Mode B (new): caller is on isOperator allowlist + tx.to is on
  isAllowedTarget allowlist. No grant required (operator is a trusted
  persistent identity). Lets the operator call any function on the
  envelope vault — typically makeCustomDeposit, withdrawDeposit — without
  holding ETH itself.

Both modes share maxEthPerTx and the QuotaControl daily counter, so a
single ETH top-up funds both flows. Revoking an operator is a tx — no
balance migration needed when rotating relayers.

New state:
  - mapping(address => bool) public isOperator
  - mapping(address => bool) public isAllowedTarget

New events:
  - OperatorSet(operator, allowed)
  - AllowedTargetSet(target, allowed)
  - OperatorCallSponsored(operator, target, gasPaid)   — distinct from
    ApprovalSponsored so indexers can filter

New admin functions (DEFAULT_ADMIN_ROLE):
  - setOperator(address, bool)
  - setAllowedTarget(address, bool)

New error:
  - TargetNotAllowed

Validation flow:
  if isOperator[tx.from]:
      Mode B — verify isAllowedTarget[tx.to], then per-tx cap + quota + pay
  else:
      Mode A — existing grant + selector + spender flow, then per-tx cap + quota + pay

Tests: 7 new in test/paymasters/EnvelopeApprovalPaymaster.t.sol covering
Mode B happy path, target-not-allowed, non-operator falls through to
Mode A, per-tx cap shared, QuotaControl shared between modes, admin role
gates on setOperator/setAllowedTarget, operator revocation.

forge test 972/972 (was 965; +7). lint clean. spellcheck clean.

Doc updated: src/peanut/doc/EnvelopeApprovalPaymaster.md describes both
modes, gates per mode, post-deploy Mode B seeding.

NOTE: Sepolia paymaster at 0xEE95bFF... is now stale bytecode (still
functions for Mode A but doesn't have Mode B). Drain + redeploy needed.
Five gaps in src/peanut/doc/EnvelopeApprovalPaymaster.md:
  - Storage section was missing isOperator and isAllowedTarget mappings
  - Mode A grant gate said ECDSA.recover; switched to
    SignatureChecker.isValidSignatureNow (was changed in fb450f5 for
    EIP-1271 support, doc didn't follow)
  - Events / Errors section missing OperatorSet, AllowedTargetSet,
    OperatorCallSponsored, TargetNotAllowed
  - Threat model missing Mode B specifics (random EOA, malicious target,
    operator key compromise, allowlist multiple operators)
  - Test coverage said 19; now 27 (Mode A + Mode B + EIP-1271)

src/peanut/doc/README.md updates:
  - Paymaster description: "Path-C gas sponsor + operator gas pool"
  - Test totals refreshed to current numbers (peanut 96, paymaster 27,
    total 972) — earlier numbers were from before the hardening + edge
    case suites + Mode B added their tests
…ia address

Deploy script:
  - Two new env vars: ENVELOPE_PAYMASTER_INITIAL_OPERATORS (comma-list,
    default empty) and ENVELOPE_PAYMASTER_INITIAL_TARGETS (comma-list,
    default = PEANUT_V4). After deploy + funding, if the deployer is
    the admin, calls setOperator(...) and setAllowedTarget(...) per entry.
  - If admin != deployer, prints an instruction and skips (admin must
    seed themselves).

Docs:
  - README + EnvelopeApprovalPaymaster.md updated with the new Sepolia
    address: 0x80EA078d599Bc63BB921Cf96CC6861731446e268 (Mode A + Mode B
    bytecode, verified, funded with 0.0015 ETH, deployer seeded as both
    operatorSigner AND Mode-B operator, peanut vault seeded as Mode-B
    target).

Old paymaster (0xEE95bFF…) and a duplicate from a re-run (0x5E44c478…)
were both drained back to deployer; only the new 0x80EA078d… remains.
The router wraps a peanut withdraw with a Squid bridge call for
cross-chain claims. Nodle's deployment doesn't currently use it (no
Squid integration), and it's not deployed on Sepolia. Removing it now
shrinks the audit surface and the test/build matrix; if cross-chain
support becomes a requirement later, re-vendor the upstream router
contract and add it back.

Removed:
  src/peanut/V4/PeanutRouter.sol           (vendored upstream router)
  test/peanut/PeanutRouter.t.sol           (4 tests; no longer applicable)
  test/peanut/mocks/SquidMock.sol          (only the router test used it)
  src/peanut/doc/PeanutRouter.md           (138-line spec)

Updated:
  test/peanut/PeanutHardening.t.sol — drop T3 (withdrawFees safeTransfer
    proof) since the router is gone. Also remove the NonReturningERC20
    inline mock + Ownable + PeanutV4Router + SquidMock imports + router
    state in setUp. T1, T2, T4, T5 unchanged.

  hardhat-deploy/DeployPeanut.ts — drop PEANUT_DEPLOY_ROUTER /
    PEANUT_SQUID_ADDRESS / PEANUT_ROUTER_OWNER env vars and the third
    deploy + verification block.

  src/peanut/doc/README.md — drop router row from the layout / deployed
    addresses tables. Naming convention updated. Test totals refreshed
    (peanut 90, total 966).

  .solhintignore — drop the now-deleted PeanutRouter.sol entry.

Test deltas:
  peanut suite: 96 → 90 (-4 router happy-path, -2 T3)
  repo total:   972 → 966

forge test: 966/966 pass. yarn lint: 0 errors. yarn spellcheck: 0 issues.
Three gaps closed:

1. Bundled the full GNU GPL v3 license text at src/peanut/V4/LICENSE-GPL
   (copied verbatim from peanutprotocol/peanut-contracts@main/LICENSE.md,
   673 lines). GPL §4 wants a copyright notice distributed with the work;
   the SPDX header was the only marker before.

2. Added top-of-file modification notice on the two modified GPL files
   (PeanutV4.4.sol, PeanutBatcherV4.4.sol). GPL §5(a): "carry prominent
   notices stating that you modified it, and giving a relevant date."
   Notice points to the per-file vendoring-patches list in the spec docs
   and the git history for the full patch set.

3. Relicensed test files that import GPL-licensed sources from
   UNLICENSED / BSD-3-Clause-Clear → GPL-3.0-or-later. Strict reading
   of the GPL: a file that imports GPL code becomes a derivative work
   and must itself be GPL. Affected: 11 test files
   (Deposit, Integration, MFA, PeanutBatcher, PeanutEdgeCases,
   PeanutHardening, PeanutV4, PeanutV4Gasless, RecipientBound,
   SenderWithdraw, SigWithdraw).

Plus added a "License notice" section to src/peanut/doc/README.md
documenting the mixed-license layout (GPL parts + BSD parts + MIT parts)
so future contributors don't have to reverse-engineer it.

What stayed BSD-3-Clause-Clear: EnvelopeApprovalPaymaster (doesn't
import any GPL source — references the vault by address only). Repo
root LICENSE is unchanged. The OSI's "mere aggregation" interpretation
covers everything else in the repo.

Tests: 966/966. Lint: clean. Spellcheck: clean.

This is a technical compliance pass, not legal advice — Nodle counsel
should sign off before mainnet.
…k hygiene)

Renames the on-chain-visible contract symbols + EIP-712 domain string from
Squirrel Labs' "Peanut" brand to Nodle's "Envelope" brand. Source file paths
keep their upstream names so the audit lineage to peanutprotocol/peanut-contracts@main
stays grep-friendly via path + git history + LICENSE-GPL + modification notice.

  contract PeanutV4         → EnvelopeVault
  contract PeanutBatcherV4  → EnvelopeBatcher
  EIP712Domain.name "Peanut" → "Envelope" (in PeanutV4.4.sol constructor)

Why: GPL gives us the right to fork the code; it doesn't grant use of the
upstream brand. Renaming the visible symbols closes a trademark vector
independent of license. The previously-renamed paymaster (EnvelopeApprovalPaymaster)
already followed this convention.

What stayed:
  - File paths (PeanutV4.4.sol, PeanutBatcherV4.4.sol) — preserves upstream-diff
  - PEANUT_SALT constant — its on-chain hash is baked into every signature; changing
    the value would break compatibility with anything using the salt convention
  - Author attribution (Squirrel Labs) — kept per GPL §5(d)
  - LICENSE-GPL, top-of-file modification notices — kept

Updated:
  - src/peanut/V4/PeanutV4.4.sol — contract name, EIP-712 domain string
  - src/peanut/V4/PeanutBatcherV4.4.sol — contract name + 5 type refs
  - 11 test files — type refs in imports + state vars + new() calls
  - test/peanut/mocks/L2ECOMock.sol — 1 type ref in comment
  - hardhat-deploy/DeployPeanut.ts — contract name strings for deploy + verify
  - src/peanut/doc/* — symbol references throughout, naming-convention section

Test contract names also updated for consistency:
  PeanutV4Test → EnvelopeVaultTest, PeanutV4DepositTest → EnvelopeVaultDepositTest, etc.

Sepolia redeployed (old addresses orphaned; old paymaster drained ~0.0015 ETH back):
  EnvelopeVault              0x32D02E54EaE5F8Bba75129e9306e0b8b70f05f6a
  EnvelopeBatcher            0x5DAe00DDFA1F96Aaf75d21F49B6FF5C756174816
  EnvelopeApprovalPaymaster  0xc160C8F6faC916De00B55aA0a630eBdce43CD532
All three verified. Paymaster funded with 0.0015 ETH and seeded with the
deployer EOA as Mode B operator + the new vault as Mode B target.

The vault's EIP-712 domain change ("Peanut" → "Envelope") invalidates any
gasless-reclaim signatures produced under the old domain. We had none in
production, so nothing breaks.

forge test 966/966. yarn lint 0 errors. yarn spellcheck 0 issues.
…oc filenames)

Aligns the rest of the developer-facing surface with the Envelope brand.
Pure cosmetic — no behavior change, no redeploy.

Env var renames (deploy scripts read the new names):
  PEANUT_V4              → ENVELOPE_VAULT
  PEANUT_BATCHER         → ENVELOPE_BATCHER
  PEANUT_MFA_AUTHORIZER  → ENVELOPE_MFA_AUTHORIZER
  PEANUT_ECO_TOKEN       → ENVELOPE_ECO_TOKEN
  PEANUT_DEPLOY_BATCHER  → ENVELOPE_DEPLOY_BATCHER

Test file renames (no class names changed — those were already done in 9989954):
  test/peanut/PeanutV4.t.sol         → EnvelopeVault.t.sol
  test/peanut/PeanutBatcher.t.sol    → EnvelopeBatcher.t.sol
  test/peanut/PeanutHardening.t.sol  → EnvelopeHardening.t.sol
  test/peanut/PeanutEdgeCases.t.sol  → EnvelopeEdgeCases.t.sol
  test/peanut/PeanutV4Gasless.t.sol  → EnvelopeGasless.t.sol

Doc file renames:
  src/peanut/doc/PeanutV4.md         → EnvelopeVault.md
  src/peanut/doc/PeanutBatcherV4.md  → EnvelopeBatcher.md

What stays "Peanut" (intentional):
  - File paths src/peanut/V4/PeanutV4.4.sol etc. — preserves upstream-diff lineage
  - PEANUT_SALT constant — its hash is in every signature digest
  - GPL §5(d) attribution comments (`// @author Squirrel Labs`,
    `peanutprotocol/peanut-contracts@main`) — required by the license
  - README mentions "Peanut Protocol V4.4" as the upstream — that's a fact

ACTION REQUIRED for users with .env-test:
  - Rename PEANUT_V4              → ENVELOPE_VAULT
  - Rename PEANUT_BATCHER         → ENVELOPE_BATCHER
  - Rename PEANUT_MFA_AUTHORIZER  → ENVELOPE_MFA_AUTHORIZER
  (PEANUT_ECO_TOKEN and PEANUT_DEPLOY_BATCHER probably weren't set anyway.)

forge test 966/966. yarn lint 0 errors. yarn spellcheck 0 issues.
…eanut → test/envelope

Final cosmetic cleanup. No behavior change, no redeploy.

Path rewrites covered:
  - test imports: ../../src/peanut/V4/PeanutV4.4.sol → ../../src/envelope/V4/PeanutV4.4.sol
  - mock imports: ../../../src/peanut/util/IEIP3009.sol → ../../../src/envelope/util/IEIP3009.sol
  - paymaster test: ../peanut/mocks/SampleSCW.sol → ../envelope/mocks/SampleSCW.sol
  - .solhintignore: src/peanut/V4/* → src/envelope/V4/*
  - hardhat-deploy verify args: contract: "src/peanut/V4/PeanutV4.4.sol:EnvelopeVault"
                                       → "src/envelope/V4/PeanutV4.4.sol:EnvelopeVault"
  - all spec docs (README + EnvelopeVault.md + EnvelopeBatcher.md + EnvelopeApprovalPaymaster.md)
  - LICENSE-GPL stays where it is (now at src/envelope/V4/LICENSE-GPL); modification
    notices in PeanutV4.4.sol / PeanutBatcherV4.4.sol point at the new path.

What stays "Peanut" in the tree (all intentional):
  - File names PeanutV4.4.sol, PeanutBatcherV4.4.sol — preserves per-file diff to upstream
  - PEANUT_SALT constant — its hash is in every signature
  - GPL §5(d) attribution comments — required by the license

forge test 966/966. yarn lint 0 errors. yarn spellcheck 0 issues.
…est classes, locals, PEANUT_SALT, comments)

Final cleanup pass after the directory rename. No on-chain bytecode change.

Renames:
  - hardhat-deploy/DeployPeanut.ts → DeployEnvelope.ts
  - PEANUT_SALT constant → ENVELOPE_SALT (value unchanged at
    0x70adbbeb…d94e0; preimage comment kept for auditor clarity).
    Per user decision (Option 2): symbol-only rename preserves signature-
    scheme interop with the upstream Peanut SDK.
  - test contract classes:
      PeanutHardeningTest → EnvelopeHardeningTest
      PeanutEdgeCasesTest → EnvelopeEdgeCasesTest
      PeanutBatcherTest   → EnvelopeBatcherTest
  - local variables in source + tests + deploy script:
      peanut, peanutV4, nodlePeanut, peanutV4ECO → vault, nodleVault, vaultECO
  - function parameters in batcher source:
      _peanutAddress → _vaultAddress
  - test hash preimages (just nonces, safe to change):
      nodle.peanut.* → nodle.envelope.*
  - prose comments mentioning "Peanut" where it wasn't required attribution:
      "the new peanut instance" → "the new envelope vault"
      "peanut depositor" → "envelope depositor"
      "different Peanut deployment" → "different Envelope deployment"
      DeployPeanut.ts header "Peanut Protocol suite" → "Envelope (vendored Peanut V4.4) suite"

What still says "Peanut" (every occurrence is intentional):
  - File names PeanutV4.4.sol, PeanutBatcherV4.4.sol — preserves
    per-file diff to upstream
  - GPL §5(d) attribution: `// @author Squirrel Labs`,
    `// @title Peanut Protocol`, `peanutprotocol/peanut-contracts@main`
  - ENVELOPE_SALT keccak preimage: "Konrad makes tokens go woosh tadam"
    (kept as documentation of how the constant value was derived)
  - Factual upstream identification in README + .solhintignore + deploy
    script header (e.g., "Vendored Envelope (Peanut V4.4) sources")

Verified: forge test 966/966. yarn lint 0 errors. yarn spellcheck 0
issues / 242 files. Local build artifacts in deployments-zk/ remain
gitignored.
…ol, PeanutBatcherV4.4.sol → EnvelopeBatcher.sol

Final consistency pass after the directory rename + contract symbol rename
+ env var rename + deploy script rename. The "V4.4" suffix is upstream's
versioning, not Envelope's; dropped.

What changed (path-string rewrites only):
  - Batcher's `import {EnvelopeVault} from "./PeanutV4.4.sol"` → `EnvelopeVault.sol`
  - 11 test imports + 2 mock cross-tree imports
  - DeployEnvelope.ts verify args:
      contract: "src/envelope/V4/PeanutV4.4.sol:EnvelopeVault"
        → "src/envelope/V4/EnvelopeVault.sol:EnvelopeVault"
  - Same for batcher
  - .solhintignore (2 entries)
  - Doc spec references throughout

Audit lineage to upstream peanutprotocol/peanut-contracts@main is still
preserved by:
  - GPL §5(d) attribution (`// @title Peanut Protocol`, `// @author Squirrel Labs`)
  - `// Modified by Nodle (2026-05-12)` notice atop each file
  - LICENSE-GPL bundled at src/envelope/V4/LICENSE-GPL
  - Git history (rename detected as 99% similarity)
  - README mention of "vendored Peanut Protocol V4.4"

forge test 966/966. yarn lint 0 errors. yarn spellcheck 0 issues.
…eBatcher and EnvelopeVault

This change modifies the Solidity pragma directive in both EnvelopeBatcher.sol and EnvelopeVault.sol to ensure compatibility with newer compiler versions while maintaining the existing functionality.
Vault, batcher, and paymaster were redeployed on 2026-05-13 because the
EIP-712 vault domain `name` flipped from "Peanut" to "Envelope" — the
prior on-chain instances were inconsistent with the renamed source.
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