diff --git a/contracts/ethregistrar/BaseRegistrarImplementation.sol b/contracts/ethregistrar/BaseRegistrarImplementation.sol index b4dff0256..c7eb16c97 100644 --- a/contracts/ethregistrar/BaseRegistrarImplementation.sol +++ b/contracts/ethregistrar/BaseRegistrarImplementation.sol @@ -21,7 +21,8 @@ interface ISubnameHook { /// @dev INVARIANT (ERC721Enumerable): enumeration (`totalSupply`, /// `tokenByIndex`, `balanceOf`, `tokenOfOwnerByIndex`) is maintained on /// transfer/mint/burn, NOT on expiry — a name is only burned when it is -/// re-registered after its grace period. So enumeration includes +/// re-registered after its grace period or its unregistration. +/// So enumeration includes /// expired-but-unburned names and can disagree with the grace-period /// `ownerOf` (which reverts once expired). Readers MUST filter by /// `nameExpires(id) > block.timestamp` to get the live set. @@ -60,9 +61,13 @@ contract BaseRegistrarImplementation is event MaxLabelLengthChanged(uint256 maxLabelLength); event SubnameHookChanged(address indexed hook); event NamePolicyChanged(address indexed namePolicy); + event NameUnregistered(uint256 indexed id); error LabelTooLong(uint256 length, uint256 max); error NamePolicyMismatch(); + error DisputePeriodOver(uint256 id); + error DisputePeriodNotOver(uint256 id); + error DisputeUntilMismatch(uint256 named, uint256 current); /// v2.1.3 version of _isApprovedOrOwner which calls ownerOf(tokenId) and takes grace period into consideration instead of ERC721.ownerOf(tokenId); /// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.1.3/contracts/token/ERC721/ERC721.sol#L187 @@ -164,7 +169,8 @@ contract BaseRegistrarImplementation is function registerWithLabel( string calldata label, address owner, - uint256 duration + uint256 duration, + uint256 disputePeriod ) external returns (uint256) { if (maxLabelLength != 0 && bytes(label).length > maxLabelLength) revert LabelTooLong(bytes(label).length, maxLabelLength); @@ -172,6 +178,9 @@ contract BaseRegistrarImplementation is if (bytes(labelOf[id]).length == 0) { labelOf[id] = label; } + disputeUntil[id] = disputePeriod == 0 + ? 0 + : block.timestamp + disputePeriod; return _register(id, owner, duration); } @@ -223,6 +232,7 @@ contract BaseRegistrarImplementation is uint256 id, uint256 duration ) external override live onlyController returns (uint256) { + if (block.timestamp < disputeUntil[id]) revert DisputePeriodNotOver(id); require(expiries[id] + GRACE_PERIOD >= block.timestamp); // Name must be registered here or in grace period require( expiries[id] + duration + GRACE_PERIOD > duration + GRACE_PERIOD @@ -239,6 +249,25 @@ contract BaseRegistrarImplementation is return expiries[id]; } + function unregister( + uint256 id, + uint256 until + ) external live onlyController { + if (disputeUntil[id] != until) + revert DisputeUntilMismatch(until, disputeUntil[id]); + if (block.timestamp >= disputeUntil[id]) revert DisputePeriodOver(id); + delete disputeUntil[id]; + expiries[id] = 0; + ens.setSubnodeRecord(baseNode, bytes32(id), address(0), address(0), 0); + if (subnameHook != address(0)) { + ISubnameHook(subnameHook).onExpiryChanged( + keccak256(abi.encodePacked(baseNode, bytes32(id))), + 0 + ); + } + emit NameUnregistered(id); + } + /// @dev Reclaim ownership of a name in ENS, if you own it in the registrar. function reclaim(uint256 id, address owner) external override live { require(_isApprovedOrOwner(msg.sender, id)); @@ -343,6 +372,8 @@ contract BaseRegistrarImplementation is /// `approve`, so a claim signature is valid for one offer and no later one. mapping(uint256 => uint256) public offers; + mapping(uint256 => uint256) public disputeUntil; + /// @dev ERC-5564 `Announcement`, verbatim in name, parameter list and /// indexing, so any indexer that knows the standard decodes ours by /// topic without special-casing. It carries the sender's ephemeral diff --git a/contracts/simplex/SimplexController.sol b/contracts/simplex/SimplexController.sol index 85d682cef..c80e7fb90 100644 --- a/contracts/simplex/SimplexController.sol +++ b/contracts/simplex/SimplexController.sol @@ -47,6 +47,8 @@ contract SimplexController is uint256 public constant MIN_RENEWAL_DURATION = 365 days; uint256 public constant MAX_REGISTRATION_DURATION = MAX_REGISTRATION; uint256 public constant MAX_SPONSORED_REGISTRATION_DURATION = MAX_SPONSORED_REGISTRATION; + uint256 public constant MIN_DISPUTE_DAYS = 14; + uint256 public constant MAX_DISPUTE_DAYS = 120; // Manual reentrancy guard (see `_reentrancyStatus` + `nonReentrant`). // Implemented by hand rather than inheriting ReentrancyGuardUpgradeable so @@ -124,6 +126,7 @@ contract SimplexController is error PublicSalesClosed(); error OwnerMustBeCaller(); error NotSponsor(); + error DisputeDaysOutOfRange(uint256 disputeDays); event NameRegistered( string label, @@ -424,7 +427,7 @@ contract SimplexController is uint256 totalPrice = price.base + price.premium; if (msg.value < totalPrice) revert InsufficientValue(); - _registerCore(registration, labelhash, price); + _registerCore(registration, labelhash, price, 0); if (msg.value > totalPrice) { (bool ok, ) = payable(msg.sender).call{value: msg.value - totalPrice}(""); @@ -436,11 +439,14 @@ contract SimplexController is /// The fee would have gone to the controller and been withdrawn back /// to the same treasury, so it is removed rather than performed. function registerSponsored( - Registration calldata registration + Registration calldata registration, + uint256 disputeDays ) external onlySponsor nonReentrant { bytes32 labelhash = keccak256(bytes(registration.label)); if (registration.duration > _sponsoredHorizon(labelhash)) revert DurationTooLong(registration.duration); + if (disputeDays < MIN_DISPUTE_DAYS || disputeDays > MAX_DISPUTE_DAYS) + revert DisputeDaysOutOfRange(disputeDays); _checkSimplexGates(registration.label, false); // Zero cost in the event, and no `_rentPrice` call: nothing is paid on @@ -448,7 +454,7 @@ contract SimplexController is // and reading it would couple the sponsored flow to the ETH/USD feed, // which is the one dependency this path exists without. What was // actually consumed is in the sponsor's `RegistrarAllowanceSpent`, in attoUSD. - _registerCore(registration, labelhash, IPriceOracle.Price(0, 0)); + _registerCore(registration, labelhash, IPriceOracle.Price(0, 0), disputeDays * 1 days); } /// @dev Everything both registration paths share: availability, the @@ -456,7 +462,8 @@ contract SimplexController is function _registerCore( Registration calldata registration, bytes32 labelhash, - IPriceOracle.Price memory price + IPriceOracle.Price memory price, + uint256 disputePeriod ) private returns (uint256 expires) { if (!_available(registration.label, labelhash)) revert NameNotAvailable(registration.label); @@ -500,13 +507,15 @@ contract SimplexController is expires = base.registerWithLabel( registration.label, registration.owner, - registration.duration + registration.duration, + disputePeriod ); } else { expires = base.registerWithLabel( registration.label, address(this), - registration.duration + registration.duration, + disputePeriod ); ens.setRecord( @@ -592,6 +601,15 @@ contract SimplexController is emit NameRenewed(label, labelhash, cost, expires, referrer); } + function unregister(string calldata label, uint256 until) external onlyOwnerOrBeneficiary { + bytes32 labelhash = keccak256(bytes(label)); + bytes32 node = keccak256(abi.encodePacked(tldNode, labelhash)); + _retireStaleRecords(node); + address resolver = defaultResolver; + if (resolver != address(0)) IClearableResolver(resolver).clearRecords(node); + base.unregister(uint256(labelhash), until); + } + /// @notice Pays the beneficiary, never `owner()`, so revenue is independent of /// the admin key. Permissionless to call. function withdraw() public nonReentrant { diff --git a/contracts/simplex/SimplexNamePolicy.sol b/contracts/simplex/SimplexNamePolicy.sol index 132dfd43a..d3aa38a0f 100644 --- a/contracts/simplex/SimplexNamePolicy.sol +++ b/contracts/simplex/SimplexNamePolicy.sol @@ -184,7 +184,7 @@ contract SimplexNamePolicy is INamePolicy { emit ReservedNameRemoved(label); bytes32 namehash = keccak256(abi.encodePacked(_tldNode, labelhash)); - registrar.registerWithLabel(label, address(this), duration); + registrar.registerWithLabel(label, address(this), duration, 0); _retireStaleRecords(namehash); address resolver = controller.defaultResolver(); if (resolver != address(0)) diff --git a/contracts/simplex/SimplexSponsor.sol b/contracts/simplex/SimplexSponsor.sol index efd48c5b7..970608d0b 100644 --- a/contracts/simplex/SimplexSponsor.sol +++ b/contracts/simplex/SimplexSponsor.sol @@ -21,7 +21,7 @@ contract SimplexSponsor { bytes32 private constant _EIP712_VERSION = keccak256("1"); bytes32 public constant REGISTER_TYPEHASH = keccak256( - "RegisterName(string label,address owner,uint256 duration,address resolver,bytes[] data,uint256 nonce,uint256 deadline)" + "RegisterName(string label,address owner,uint256 duration,address resolver,bytes[] data,uint256 disputeDays,uint256 nonce,uint256 deadline)" ); SimplexController public immutable controller; @@ -67,22 +67,23 @@ contract SimplexSponsor { /// @notice Register with no value attached, spending the name's list price /// from the caller's allowance. /// @param sig The owner's EIP-712 `RegisterName` signature, which covers the - /// label, the duration, the resolver and `data`, not the secret or referrer. + /// label, the duration, the resolver, `data` and `disputeDays`, not the secret or referrer. /// Not checked when the owner is the caller. function registerWithCredit( IETHRegistrarController.Registration calldata registration, + uint256 disputeDays, uint256 nonce, uint256 deadline, bytes calldata sig ) external { if (registration.owner != msg.sender) - _consumeIntent(registration, nonce, deadline, sig); + _consumeIntent(registration, disputeDays, nonce, deadline, sig); IPriceOracle.Price memory usd = controller.rentPriceUSD( registration.label, registration.duration ); _spendAllowance(usd.base + usd.premium); - controller.registerSponsored(registration); + controller.registerSponsored(registration, disputeDays); } /// @notice Renew with no value attached, spending the name's list price @@ -130,6 +131,7 @@ contract SimplexSponsor { /// @dev Verify the owner's signature, then spend the nonce. function _consumeIntent( IETHRegistrarController.Registration calldata registration, + uint256 disputeDays, uint256 nonce, uint256 deadline, bytes calldata sig @@ -153,6 +155,7 @@ contract SimplexSponsor { registration.duration, registration.resolver, keccak256(abi.encodePacked(dataHashes)), + disputeDays, nonce, deadline ) diff --git a/contracts/simplex/SubnameRegistrar.sol b/contracts/simplex/SubnameRegistrar.sol index 76bc5cbd1..39d9fd76e 100644 --- a/contracts/simplex/SubnameRegistrar.sol +++ b/contracts/simplex/SubnameRegistrar.sol @@ -402,7 +402,8 @@ contract SubnameRegistrar is ISubnameRegistrar { } /// @notice Called by BaseRegistrar whenever 2LD `node`'s expiry moves - /// (registration or renewal), so subname authority can follow the + /// (registration, renewal or unregistration), so subname + /// authority can follow the /// registration rather than the registry record it outlives. function onExpiryChanged(bytes32 node, uint256 expiry) external { if (msg.sender != baseRegistrar) revert NotBaseRegistrar(); diff --git a/docs/upgrades.md b/docs/upgrades.md index fef20f3b3..c1e3fb6b6 100644 --- a/docs/upgrades.md +++ b/docs/upgrades.md @@ -220,7 +220,7 @@ declaration order, so reordering them swaps the two lists; keep them unchanged | `ENSRegistry` | `SimplexResolver` | `owner` | | `ENSRegistry` | `Root` | `setSubnodeOwner`, `setResolver` | | `ENSRegistry` | `UniversalResolver` | `resolver` | -| `BaseRegistrarImplementation` | `SimplexController` | `available`, `nameExpires`, `registerWithLabel`, `renew`, `transferFrom` | +| `BaseRegistrarImplementation` | `SimplexController` | `available`, `nameExpires`, `registerWithLabel`, `renew`, `transferFrom`, `unregister` | | `BaseRegistrarImplementation` | `SimplexNamePolicy` | `available`, `registerWithLabel`, `transferFrom` | | `SimplexController` | `SimplexNamePolicy` | `owner`, `beneficiary`, `defaultResolver`, `wasDefaultResolver`, `commitments`, `maxCommitmentAge`, `commit`; `ens` and `tldNode` in its constructor | | `SimplexController` | `SimplexSponsor` | `beneficiary`, `rentPriceUSD`, `registerSponsored`, `renewSponsored` | diff --git a/test/ethregistrar/TestBaseRegistrar.test.ts b/test/ethregistrar/TestBaseRegistrar.test.ts index a6f3bf570..7ea2fdc18 100644 --- a/test/ethregistrar/TestBaseRegistrar.test.ts +++ b/test/ethregistrar/TestBaseRegistrar.test.ts @@ -32,7 +32,7 @@ const loadFixture = async () => connection.networkHelpers.loadFixture(fixture) async function fixtureWithRegistration() { const existing = await loadFixture() await existing.baseRegistrar.write.registerWithLabel( - ['newname', registrantAccount.address, 86400n], + ['newname', registrantAccount.address, 86400n, 0n], { account: controllerAccount, }, @@ -47,7 +47,7 @@ describe('BaseRegistrar', () => { const { ensRegistry, baseRegistrar } = await loadFixture() const hash = await baseRegistrar.write.registerWithLabel( - ['newname', registrantAccount.address, 86400n], + ['newname', registrantAccount.address, 86400n, 0n], { account: controllerAccount, }, @@ -87,7 +87,7 @@ describe('BaseRegistrar', () => { await expect( baseRegistrar.write.registerWithLabel( - ['foo', otherAccount.address, 86400n], + ['foo', otherAccount.address, 86400n, 0n], { account: otherAccount, }, @@ -110,7 +110,7 @@ describe('BaseRegistrar', () => { await expect( baseRegistrar.write.registerWithLabel( - ['newname', registrantAccount.address, 86400n], + ['newname', registrantAccount.address, 86400n, 0n], { account: controllerAccount, }, @@ -255,7 +255,7 @@ describe('BaseRegistrar', () => { ).toBeRevertedWithoutReason() await baseRegistrar.write.registerWithLabel( - ['newname', otherAccount.address, 86400n], + ['newname', otherAccount.address, 86400n, 0n], { account: controllerAccount, }, diff --git a/test/simplex/TestApproveClaimWithSig.test.ts b/test/simplex/TestApproveClaimWithSig.test.ts index b30ef5b3e..a74590503 100644 --- a/test/simplex/TestApproveClaimWithSig.test.ts +++ b/test/simplex/TestApproveClaimWithSig.test.ts @@ -40,6 +40,7 @@ async function fixture() { 'alicechat', aliceAccount.address, DURATION, + 0n, ]) return { ensRegistry, baseRegistrar } } diff --git a/test/simplex/TestDisputePeriod.test.ts b/test/simplex/TestDisputePeriod.test.ts new file mode 100644 index 000000000..3a8805b91 --- /dev/null +++ b/test/simplex/TestDisputePeriod.test.ts @@ -0,0 +1,475 @@ +import hre from 'hardhat' +import { + concat, + getAddress, + keccak256, + labelhash, + zeroAddress, + zeroHash, +} from 'viem' +import { describe, expect, it } from 'vitest' + +import { + acceptGeneralTermsForClaim, + AMPLE_ALLOWANCE, + commitUnderGeneralTerms, + deployNamesV2, + MIN_DISPUTE_DAYS, + MIN_REGISTRATION, + node, + Reason, + registration, + signRegistration, + TLD, + YEAR, + YEAR_PRICE_USD, +} from './fixtures/namesV2.js' +import { DAY } from '../fixtures/constants.js' + +const MAX_DISPUTE_DAYS = 120n +const KEY = 'simplex.contact' +const EXACT = { gas: 5_000_000n } + +const connection = await hre.network.connect() +const publicClient = await connection.viem.getPublicClient() +const testClient = await connection.viem.getTestClient() +const [ + ownerClient, + guardianClient, + registrarClient, + aliceClient, + bobClient, + carolClient, +] = await connection.viem.getWalletClients() +const owner = ownerClient.account +const guardian = guardianClient.account +const registrar = registrarClient.account +const alice = aliceClient.account +const bob = bobClient.account +const carol = carolClient.account +type Account = typeof alice + +async function fixture() { + const f = await deployNamesV2(connection, { + owner: owner.address, + beneficiary: guardian.address, + }) + await f.sponsor.write.setRegistrarAllowance( + [registrar.address, AMPLE_ALLOWANCE], + { account: guardian }, + ) + await f.controller.write.setPublicSalesOpen([true], { account: owner }) + return f +} +const load = () => connection.networkHelpers.loadFixture(fixture) +type Fixture = Awaited> + +const id = (label: string) => BigInt(labelhash(label)) + +async function timeOf(hash: `0x${string}`) { + const { blockNumber } = await publicClient.waitForTransactionReceipt({ hash }) + return (await publicClient.getBlock({ blockNumber })).timestamp +} + +const exactly = (timestamp: bigint) => + testClient.setNextBlockTimestamp({ timestamp }) + +async function sponsored( + f: Fixture, + label: string, + { + holder = alice, + days = MIN_DISPUTE_DAYS, + resolver = zeroAddress, + }: Partial<{ holder: Account; days: bigint; resolver: `0x${string}` }> = {}, +) { + const reg = registration(label, holder.address, { resolver }) + await commitUnderGeneralTerms(connection, f.controller, reg, { + account: holder, + }) + const hash = await f.sponsor.write.registerWithCredit( + await signRegistration(connection, f.sponsor, reg, { disputeDays: days }), + { account: registrar }, + ) + return (await timeOf(hash)) + days * DAY +} + +async function paid(f: Fixture, label: string, holder: Account = alice) { + const reg = registration(label, holder.address) + await commitUnderGeneralTerms(connection, f.controller, reg, { + account: holder, + }) + return timeOf( + await f.controller.write.register([reg], { + account: holder, + value: 2n * YEAR_PRICE_USD, + }), + ) +} + +const unregister = ( + f: Fixture, + label: string, + until: bigint, + account: Account = guardian, + options = {}, +) => f.controller.write.unregister([label, until], { account, ...options }) + +async function withSubname(f: Fixture, label: string) { + await f.ens.write.setApprovalForAll([f.subnameRegistrar.address, true], { + account: alice, + }) + await f.subnameRegistrar.write.createSubname([node(label), 'pay'], { + account: alice, + }) + return BigInt(keccak256(concat([node(label), labelhash('pay')]))) +} + +describe('dispute period', () => { + describe('registration', () => { + it('stores the end of a sponsored registration of 14 to 120 days', async () => { + const f = await load() + for (const [label, days] of [ + ['fourteendays', MIN_DISPUTE_DAYS], + ['hundredtwenty', MAX_DISPUTE_DAYS], + ] as const) { + const until = await sponsored(f, label, { days }) + expect(await f.baseRegistrar.read.disputeUntil([id(label)])).toBe(until) + } + expect(await f.controller.read.MIN_DISPUTE_DAYS()).toBe(MIN_DISPUTE_DAYS) + expect(await f.controller.read.MAX_DISPUTE_DAYS()).toBe(MAX_DISPUTE_DAYS) + }) + + it('reverts DisputeDaysOutOfRange below 14 and above 120 days', async () => { + const f = await load() + for (const [label, days] of [ + ['thirteendays', MIN_DISPUTE_DAYS - 1n], + ['zerodaysname', 0n], + ['toomanydays', MAX_DISPUTE_DAYS + 1n], + ] as const) { + const reg = registration(label, alice.address) + await commitUnderGeneralTerms(connection, f.controller, reg, { + account: alice, + }) + await expect( + f.sponsor.write.registerWithCredit( + await signRegistration(connection, f.sponsor, reg, { + disputeDays: days, + }), + { account: registrar }, + ), + ).toBeRevertedWithCustomErrorFrom(f.controller, 'DisputeDaysOutOfRange') + } + }) + + it('binds the dispute days in RegisterName', async () => { + const f = await load() + const reg = registration('signeddays', alice.address) + await commitUnderGeneralTerms(connection, f.controller, reg, { + account: alice, + }) + const [, days, nonce, deadline, sig] = await signRegistration( + connection, + f.sponsor, + reg, + { disputeDays: MAX_DISPUTE_DAYS }, + ) + await expect( + f.sponsor.write.registerWithCredit( + [reg, MIN_DISPUTE_DAYS, nonce, deadline, sig], + { account: registrar }, + ), + ).toBeRevertedWithCustomError('InvalidSignature') + await f.sponsor.write.registerWithCredit([reg, days, nonce, deadline, sig], { + account: registrar, + }) + }) + + it('gives the payable path and registerReserved no dispute period', async () => { + const f = await load() + await paid(f, 'paidineth') + expect(await f.baseRegistrar.read.disputeUntil([id('paidineth')])).toBe(0n) + await f.namePolicy.write.addReservedNames( + [['brandname'], Reason.Trademark], + { account: guardian }, + ) + await f.namePolicy.write.registerReserved( + ['brandname', bob.address, MIN_REGISTRATION], + { account: owner }, + ) + expect(await f.baseRegistrar.read.disputeUntil([id('brandname')])).toBe(0n) + for (const label of ['paidineth', 'brandname']) + await expect(unregister(f, label, 0n)).toBeRevertedWithCustomErrorFrom( + f.baseRegistrar, + 'DisputePeriodOver', + ) + }) + }) + + describe('unregistration', () => { + it('is made by the guardian or the admin, before the end of the dispute period', async () => { + const f = await load() + const byGuardian = await sponsored(f, 'byguardian') + const byAdmin = await sponsored(f, 'byadmin') + const lastSecond = await sponsored(f, 'lastsecond') + const atEnd = await sponsored(f, 'atitsend') + for (const account of [registrar, alice, carol]) + await expect( + unregister(f, 'byguardian', byGuardian, account), + ).toBeRevertedWithCustomError('NotOwnerOrBeneficiary') + await unregister(f, 'byguardian', byGuardian, guardian) + await unregister(f, 'byadmin', byAdmin, owner) + await exactly(lastSecond - 1n) + await unregister(f, 'lastsecond', lastSecond, guardian, EXACT) + await exactly(atEnd) + await expect( + unregister(f, 'atitsend', atEnd, guardian, EXACT), + ).toBeRevertedWithCustomErrorFrom(f.baseRegistrar, 'DisputePeriodOver') + for (const label of ['byguardian', 'byadmin', 'lastsecond']) + expect(await f.baseRegistrar.read.nameExpires([id(label)])).toBe(0n) + expect(await f.baseRegistrar.read.ownerOf([id('atitsend')])).toBe( + getAddress(alice.address), + ) + }) + + it('ends the registration, its records and its subnames at once', async () => { + const f = await load() + const until = await sponsored(f, 'disputed', { resolver: f.resolver.address }) + await f.resolver.write.setText([node('disputed'), KEY, 'https://smp/alice'], { + account: alice, + }) + const sub = await withSubname(f, 'disputed') + await expect(unregister(f, 'disputed', until)) + .toEmitEventFrom(f.baseRegistrar, 'NameUnregistered') + .withArgs({ id: id('disputed') }) + expect(await f.baseRegistrar.read.nameExpires([id('disputed')])).toBe(0n) + expect(await f.baseRegistrar.read.disputeUntil([id('disputed')])).toBe(0n) + expect(await f.baseRegistrar.read.available([id('disputed')])).toBe(true) + expect(await f.controller.read.available(['disputed'])).toBe(true) + await expect( + f.baseRegistrar.read.ownerOf([id('disputed')]), + ).toBeRevertedWithoutReason() + expect(await f.ens.read.owner([node('disputed')])).toBe(zeroAddress) + expect(await f.ens.read.resolver([node('disputed')])).toBe(zeroAddress) + expect(await f.resolver.read.text([node('disputed'), KEY])).toBe('') + expect(await f.subnameRegistrar.read.ownerOf([sub])).toBe(zeroAddress) + expect(await f.subnameRegistrar.read.expiryOf([node('disputed')])).toBe(0n) + await f.subnameRegistrar.write.purge([node('disputed'), [labelhash('pay')]], { + account: carol, + }) + expect( + await f.subnameRegistrar.read.childrenLength([node('disputed')]), + ).toBe(0n) + await expect( + f.resolver.write.setText([node('disputed'), KEY, 'https://smp/again'], { + account: alice, + }), + ).toBeRevertedWithoutReason() + await expect(unregister(f, 'disputed', until)).toBeRevertedWithCustomErrorFrom( + f.baseRegistrar, + 'DisputeUntilMismatch', + ) + await expect(unregister(f, 'disputed', 0n)).toBeRevertedWithCustomErrorFrom( + f.baseRegistrar, + 'DisputePeriodOver', + ) + }) + + it('refuses a claim and a renewal of an unregistered name', async () => { + const f = await load() + const until = await sponsored(f, 'nomoreclaim') + await f.baseRegistrar.write.approve([bob.address, id('nomoreclaim')], { + account: alice, + }) + await acceptGeneralTermsForClaim( + connection, + f.baseRegistrar, + id('nomoreclaim'), + alice.address, + { account: bob }, + ) + await unregister(f, 'nomoreclaim', until) + await expect( + f.baseRegistrar.write.transferFrom( + [alice.address, bob.address, id('nomoreclaim')], + { account: bob }, + ), + ).toBeRevertedWithoutReason() + await expect( + f.controller.write.renew(['nomoreclaim', YEAR, zeroHash], { + account: alice, + value: YEAR_PRICE_USD, + }), + ).toBeRevertedWithoutReason() + }) + + it('lets anyone register the name again at once, without the old subnames and records', async () => { + const f = await load() + const until = await sponsored(f, 'freedname', { resolver: f.resolver.address }) + await f.resolver.write.setText([node('freedname'), KEY, 'https://smp/alice'], { + account: alice, + }) + const sub = await withSubname(f, 'freedname') + await unregister(f, 'freedname', until) + await paid(f, 'freedname', bob) + expect(await f.baseRegistrar.read.ownerOf([id('freedname')])).toBe( + getAddress(bob.address), + ) + expect(await f.baseRegistrar.read.balanceOf([alice.address])).toBe(0n) + expect(await f.baseRegistrar.read.disputeUntil([id('freedname')])).toBe(0n) + expect(await f.subnameRegistrar.read.ownerOf([sub])).toBe(zeroAddress) + expect(await f.resolver.read.text([node('freedname'), KEY])).toBe('') + }) + + it('writes a new dispute end at a sponsored registration after an unregistration', async () => { + const f = await load() + await unregister(f, 'secondsale', await sponsored(f, 'secondsale')) + const until = await sponsored(f, 'secondsale', { + holder: bob, + days: MAX_DISPUTE_DAYS, + }) + expect(await f.baseRegistrar.read.disputeUntil([id('secondsale')])).toBe(until) + }) + + it('refuses an unregistration prepared for an earlier registration of the name', async () => { + const f = await load() + const first = await sponsored(f, 'resold') + await unregister(f, 'resold', first) + const second = await sponsored(f, 'resold', { holder: bob }) + await expect( + unregister(f, 'resold', first), + ).toBeRevertedWithCustomErrorFrom(f.baseRegistrar, 'DisputeUntilMismatch') + expect(await f.baseRegistrar.read.ownerOf([id('resold')])).toBe( + getAddress(bob.address), + ) + await unregister(f, 'resold', second) + expect(await f.baseRegistrar.read.nameExpires([id('resold')])).toBe(0n) + }) + + it('takes the name from a recipient of a claim in the dispute period', async () => { + const f = await load() + const until = await sponsored(f, 'soldearly') + await f.baseRegistrar.write.approve([bob.address, id('soldearly')], { + account: alice, + }) + await acceptGeneralTermsForClaim( + connection, + f.baseRegistrar, + id('soldearly'), + alice.address, + { account: bob }, + ) + await f.baseRegistrar.write.transferFrom( + [alice.address, bob.address, id('soldearly')], + { account: bob }, + ) + await unregister(f, 'soldearly', until) + expect(await f.baseRegistrar.read.nameExpires([id('soldearly')])).toBe(0n) + expect(await f.ens.read.owner([node('soldearly')])).toBe(zeroAddress) + }) + + it('refuses a renewal on both paths until the dispute period ends', async () => { + const f = await load() + const paths = { + renewpaid: () => + f.controller.write.renew(['renewpaid', YEAR, zeroHash], { + account: alice, + value: YEAR_PRICE_USD, + ...EXACT, + }), + renewcredit: () => + f.sponsor.write.renewWithCredit(['renewcredit', YEAR, zeroHash], { + account: registrar, + ...EXACT, + }), + } + for (const [label, renew] of Object.entries(paths)) { + const until = await sponsored(f, label) + await exactly(until - 1n) + await expect(renew()).toBeRevertedWithCustomErrorFrom( + f.baseRegistrar, + 'DisputePeriodNotOver', + ) + await exactly(until) + await renew() + expect(await f.baseRegistrar.read.nameExpires([id(label)])).toBe( + until - MIN_DISPUTE_DAYS * DAY + MIN_REGISTRATION + YEAR, + ) + } + }) + + it('clears the default resolver although the holder points the name elsewhere', async () => { + const f = await load() + const until = await sponsored(f, 'repointed', { resolver: f.resolver.address }) + await f.resolver.write.setText([node('repointed'), KEY, 'https://smp/alice'], { + account: alice, + }) + await f.ens.write.setResolver([node('repointed'), zeroAddress], { + account: alice, + }) + await unregister(f, 'repointed', until) + await sponsored(f, 'repointed', { holder: bob, resolver: f.resolver.address }) + expect(await f.resolver.read.text([node('repointed'), KEY])).toBe('') + }) + + it('is not blocked by a holder who points the name at a contract that is no resolver', async () => { + const f = await load() + const until = await sponsored(f, 'blocking') + await f.ens.write.setResolver([node('blocking'), f.sponsor.address], { + account: alice, + }) + await unregister(f, 'blocking', until) + expect(await f.baseRegistrar.read.nameExpires([id('blocking')])).toBe(0n) + }) + + it('clears a past default resolver the name points at', async () => { + const f = await load() + const until = await sponsored(f, 'pastdefault', { resolver: f.resolver.address }) + await f.resolver.write.setText([node('pastdefault'), KEY, 'https://smp/alice'], { + account: alice, + }) + const next = await connection.viem.deployContract('SimplexResolver', [ + f.ens.address, + f.subnameRegistrar.address, + f.controller.address, + zeroAddress, + ]) + await f.controller.write.setDefaultResolver([next.address], { account: owner }) + await unregister(f, 'pastdefault', until) + expect(await f.resolver.read.text([node('pastdefault'), KEY])).toBe('') + }) + + it('is made without a default resolver', async () => { + const f = await load() + const until = await sponsored(f, 'nodefault') + await f.controller.write.setDefaultResolver([zeroAddress], { account: owner }) + await unregister(f, 'nodefault', until) + expect(await f.baseRegistrar.read.nameExpires([id('nodefault')])).toBe(0n) + }) + + it('is refused while the registrar does not own the TLD node', async () => { + const f = await load() + const until = await sponsored(f, 'notlive') + await f.ens.write.setSubnodeOwner([zeroHash, labelhash(TLD), carol.address], { + account: owner, + }) + await f.ens.write.setApprovalForAll([f.baseRegistrar.address, true], { + account: carol, + }) + await expect(unregister(f, 'notlive', until)).toBeRevertedWithoutReason() + expect(await f.baseRegistrar.read.nameExpires([id('notlive')])).not.toBe(0n) + }) + + it('is made on the registrar by a registrar controller only', async () => { + const f = await load() + const until = await sponsored(f, 'directcall') + for (const account of [owner, guardian, alice]) + await expect( + f.baseRegistrar.write.unregister([id('directcall'), until], { account }), + ).toBeRevertedWithoutReason() + expect(await f.baseRegistrar.read.ownerOf([id('directcall')])).toBe( + getAddress(alice.address), + ) + }) + }) +}) diff --git a/test/simplex/TestLaunchLifecycle.test.ts b/test/simplex/TestLaunchLifecycle.test.ts index b7cb334df..67fdb3db7 100644 --- a/test/simplex/TestLaunchLifecycle.test.ts +++ b/test/simplex/TestLaunchLifecycle.test.ts @@ -23,6 +23,7 @@ import { implementationOf, type InitializeParameters, MIN_REGISTRATION, + passDisputePeriod, PRICE_BASE, PRICE_EXCEPTIONS, registerWithCredit, @@ -743,6 +744,7 @@ describe('launch lifecycle', () => { const allowanceBefore = await sponsor.read.registrarAllowance([ registrar.address, ]) + await passDisputePeriod(connection) await sponsor.write.renewWithCredit([OWNED, YEAR, zeroHash], { account: registrar, }) diff --git a/test/simplex/TestPublicSalesSwitch.test.ts b/test/simplex/TestPublicSalesSwitch.test.ts index 5ea09ba71..73263c295 100644 --- a/test/simplex/TestPublicSalesSwitch.test.ts +++ b/test/simplex/TestPublicSalesSwitch.test.ts @@ -7,6 +7,7 @@ import { commitUnderGeneralTerms, deployNamesV2, MIN_REGISTRATION, + passDisputePeriod, registerWithCredit, registration, sponsorOf, @@ -92,6 +93,7 @@ describe('public sales switch', () => { it('renewal is exempt in both forms, so a pause never costs anyone a name', async () => { const { controller, sponsor } = await load() await creditedRegister(controller, 'renewany') + await passDisputePeriod(connection) expect(await controller.read.publicSalesOpen()).toBe(false) await controller.write.renew(['renewany', YEAR, zeroHash], { diff --git a/test/simplex/TestRecipientConsent.test.ts b/test/simplex/TestRecipientConsent.test.ts index 3b9402fc7..d644623a2 100644 --- a/test/simplex/TestRecipientConsent.test.ts +++ b/test/simplex/TestRecipientConsent.test.ts @@ -17,6 +17,7 @@ import { commitUnderGeneralTerms, deployNamesV2, FAR_FUTURE, + MIN_DISPUTE_DAYS, MIN_REGISTRATION, node, registerWithCredit, @@ -87,7 +88,7 @@ describe('recipient consent', () => { expect(await sponsor.read.REGISTER_TYPEHASH()).toBe( keccak256( toHex( - 'RegisterName(string label,address owner,uint256 duration,address resolver,bytes[] data,uint256 nonce,uint256 deadline)', + 'RegisterName(string label,address owner,uint256 duration,address resolver,bytes[] data,uint256 disputeDays,uint256 nonce,uint256 deadline)', ), ), ) @@ -120,7 +121,7 @@ describe('recipient consent', () => { const reg = registration('nosigname', bob.address) await commit(controller, reg) await expect( - sponsor.write.registerWithCredit([reg, 0n, FAR_FUTURE, '0x'], { + sponsor.write.registerWithCredit([reg, MIN_DISPUTE_DAYS, 0n, FAR_FUTURE, '0x'], { account: registrar, }), ).toBeRevertedWithCustomError('InvalidSignature') @@ -139,7 +140,7 @@ describe('recipient consent', () => { const signed = registration('signedname', bob.address, { resolver: resolver.address, }) - const [, nonce, deadline, sig] = await signRegistration( + const [, disputeDays, nonce, deadline, sig] = await signRegistration( connection, sponsor, signed, @@ -162,13 +163,13 @@ describe('recipient consent', () => { for (const reg of tampered) { await commit(controller, reg) await expect( - sponsor.write.registerWithCredit([reg, nonce, deadline, sig], { + sponsor.write.registerWithCredit([reg, disputeDays, nonce, deadline, sig], { account: registrar, }), ).toBeRevertedWithCustomError('InvalidSignature') } await commit(controller, signed) - await sponsor.write.registerWithCredit([signed, nonce, deadline, sig], { + await sponsor.write.registerWithCredit([signed, disputeDays, nonce, deadline, sig], { account: registrar, }) expect( @@ -178,7 +179,7 @@ describe('recipient consent', () => { it('leaves the secret to the payer', async () => { const { controller, sponsor, baseRegistrar } = await load() - const [signed, nonce, deadline, sig] = await signRegistration( + const [signed, disputeDays, nonce, deadline, sig] = await signRegistration( connection, sponsor, registration('payername', bob.address), @@ -188,7 +189,7 @@ describe('recipient consent', () => { secret: keccak256(toHex('chosen later')), } await commit(controller, reg) - await sponsor.write.registerWithCredit([reg, nonce, deadline, sig], { + await sponsor.write.registerWithCredit([reg, disputeDays, nonce, deadline, sig], { account: registrar, }) expect( @@ -232,7 +233,7 @@ describe('recipient consent', () => { const reg = registration('directname', registrar.address) await commit(controller, reg) await expect( - controller.write.registerSponsored([reg], { account: registrar }), + controller.write.registerSponsored([reg, MIN_DISPUTE_DAYS], { account: registrar }), ).toBeRevertedWithCustomError('NotSponsor') await expect( controller.write.renewSponsored( @@ -246,7 +247,7 @@ describe('recipient consent', () => { const { controller, sponsor, baseRegistrar } = await load() const reg = registration('selfname', registrar.address) await commit(controller, reg) - await sponsor.write.registerWithCredit([reg, 0n, 0n, '0x'], { + await sponsor.write.registerWithCredit([reg, MIN_DISPUTE_DAYS, 0n, 0n, '0x'], { account: registrar, }) expect( diff --git a/test/simplex/TestRegistrarAllowance.test.ts b/test/simplex/TestRegistrarAllowance.test.ts index 9310bcf8d..f6a0648ea 100644 --- a/test/simplex/TestRegistrarAllowance.test.ts +++ b/test/simplex/TestRegistrarAllowance.test.ts @@ -6,6 +6,8 @@ import { AMPLE_ALLOWANCE, commitUnderGeneralTerms, deployNamesV2, + MIN_DISPUTE_DAYS, + passDisputePeriod, registerWithCredit, registration, signRegistration, @@ -14,6 +16,7 @@ import { YEAR_PRICE_USD, yearPriceUSD, } from './fixtures/namesV2.js' +import { DAY } from '../fixtures/constants.js' const connection = await hre.network.connect() const publicClient = await connection.viem.getPublicClient() @@ -260,6 +263,7 @@ describe('registrar allowance', () => { { account: guardian }, ) await sponsoredRegister(controller, registration('renewable', alice.address)) + await passDisputePeriod(connection) const afterRegister = await sponsor.read.registrarAllowance([ registrar.address, ]) @@ -309,7 +313,9 @@ describe('registrar allowance', () => { { account: guardian }, ) await sponsoredRegister(controller, registration('decade', alice.address)) - await sponsor.write.renewWithCredit(['decade', 9n * YEAR, zeroHash], { + await passDisputePeriod(connection) + const longest = 9n * YEAR + MIN_DISPUTE_DAYS * DAY + await sponsor.write.renewWithCredit(['decade', longest, zeroHash], { account: registrar, }) await expect( diff --git a/test/simplex/TestRegistrarV3.test.ts b/test/simplex/TestRegistrarV3.test.ts index d06eee7e4..87ccfccc7 100644 --- a/test/simplex/TestRegistrarV3.test.ts +++ b/test/simplex/TestRegistrarV3.test.ts @@ -47,7 +47,7 @@ const registerLabel = ( baseRegistrar: any, label: string, owner: `0x${string}`, -) => baseRegistrar.write.registerWithLabel([label, owner, DURATION]) +) => baseRegistrar.write.registerWithLabel([label, owner, DURATION, 0n]) describe('BaseRegistrarImplementation v3', () => { describe('label index', () => { @@ -184,7 +184,7 @@ describe('BaseRegistrarImplementation v3', () => { const { baseRegistrar } = await loadFixture() await expect( baseRegistrar.write.registerWithLabel( - ['alice', otherAccount.address, DURATION], + ['alice', otherAccount.address, DURATION, 0n], { account: otherAccount }, ), ).rejects.toThrow() diff --git a/test/simplex/TestSimplexResolver.test.ts b/test/simplex/TestSimplexResolver.test.ts index aba38e15b..6a49429e1 100644 --- a/test/simplex/TestSimplexResolver.test.ts +++ b/test/simplex/TestSimplexResolver.test.ts @@ -53,6 +53,7 @@ async function fixture() { 'alicechat', aliceAccount.address, DURATION, + 0n, ]) return { ensRegistry, baseRegistrar, resolver } } diff --git a/test/simplex/TestSponsoredPathIndependence.test.ts b/test/simplex/TestSponsoredPathIndependence.test.ts index b92d83f56..252fae64a 100644 --- a/test/simplex/TestSponsoredPathIndependence.test.ts +++ b/test/simplex/TestSponsoredPathIndependence.test.ts @@ -6,6 +6,7 @@ import { AMPLE_ALLOWANCE, commitUnderGeneralTerms, deployNamesV2, + passDisputePeriod, registerWithCredit, registration, sponsorOf, @@ -63,6 +64,7 @@ describe('the sponsored path does not depend on the price feed', () => { const tokenId = BigInt(labelhash('deadfeed')) const before = await baseRegistrar.read.nameExpires([tokenId]) + await passDisputePeriod(connection) await sponsor.write.renewWithCredit(['deadfeed', YEAR, zeroHash], { account: registrar, }) @@ -118,6 +120,7 @@ describe('the sponsored path does not depend on the price feed', () => { it('credited renewal emits a zero cost too', async () => { const { controller, sponsor } = await load() await sponsoredRegister(controller, 'renewevent') + await passDisputePeriod(connection) const hash = await sponsor.write.renewWithCredit( ['renewevent', YEAR, zeroHash], { account: registrar }, diff --git a/test/simplex/__snapshots__/storageLayouts.json b/test/simplex/__snapshots__/storageLayouts.json index 9ea9b4012..934dcb3be 100644 --- a/test/simplex/__snapshots__/storageLayouts.json +++ b/test/simplex/__snapshots__/storageLayouts.json @@ -34,7 +34,8 @@ "18:0+32 BaseRegistrarImplementation.baseNode bytes32", "19:0+32 BaseRegistrarImplementation.controllers mapping(address => bool)", "20:0+32 BaseRegistrarImplementation.nonces mapping(address => uint256)", - "21:0+32 BaseRegistrarImplementation.offers mapping(uint256 => uint256)" + "21:0+32 BaseRegistrarImplementation.offers mapping(uint256 => uint256)", + "22:0+32 BaseRegistrarImplementation.disputeUntil mapping(uint256 => uint256)" ], "SimplexResolver": [ "0:0+32 ResolverBase.recordVersions mapping(bytes32 => uint64)", diff --git a/test/simplex/fixtures/namesV2.ts b/test/simplex/fixtures/namesV2.ts index d52b89334..4ca6b2f05 100644 --- a/test/simplex/fixtures/namesV2.ts +++ b/test/simplex/fixtures/namesV2.ts @@ -472,6 +472,7 @@ export const eip712Types = { { name: 'duration', type: 'uint256' }, { name: 'resolver', type: 'address' }, { name: 'data', type: 'bytes[]' }, + { name: 'disputeDays', type: 'uint256' }, { name: 'nonce', type: 'uint256' }, { name: 'deadline', type: 'uint256' }, ], @@ -513,6 +514,11 @@ export const eip712Types = { export const FAR_FUTURE = 4102444800n +export const MIN_DISPUTE_DAYS = 14n + +export const passDisputePeriod = (connection: NetworkConnection) => + connection.networkHelpers.time.increase(MIN_DISPUTE_DAYS * DAY) + /** Sign one of the intents above against `verifyingContract`. */ export async function signIntent( publicClient: any, @@ -565,8 +571,12 @@ export async function signRegistration< connection: NetworkConnection, sponsor: any, reg: R, - { signer, deadline = FAR_FUTURE }: { signer?: any; deadline?: bigint } = {}, -): Promise<[R, bigint, bigint, `0x${string}`]> { + { + signer, + deadline = FAR_FUTURE, + disputeDays = MIN_DISPUTE_DAYS, + }: { signer?: any; deadline?: bigint; disputeDays?: bigint } = {}, +): Promise<[R, bigint, bigint, bigint, `0x${string}`]> { const client = signer ?? (await connection.viem.getWalletClients()).find( @@ -586,11 +596,12 @@ export async function signRegistration< duration: reg.duration, resolver: reg.resolver, data: reg.data, + disputeDays, nonce, deadline, }, ) - return [reg, nonce, deadline, sig] + return [reg, disputeDays, nonce, deadline, sig] } /** `sponsor.registerWithCredit` for `reg`, signed by its owner. */