Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(contracts): harden GreenfieldVault, IdentityRegistry and the Uniswap launcher with matching Foundry tests

nirholas606ae23ab105
diff --git a/contracts/src/GreenfieldVault.sol b/contracts/src/GreenfieldVault.sol
index c5ffe7d49..e9b519f58 100644
--- a/contracts/src/GreenfieldVault.sol
+++ b/contracts/src/GreenfieldVault.sol
@@ -37,11 +37,16 @@ import {IApplication} from "./greenfield/IApplication.sol";
* guard so the buyer could be resold access later. Grants are
* otherwise permanent — there is no expiry.
*
+ * Escrow: the listed price stays in the vault from `buy()` until
+ * Greenfield's ack settles. A confirmed grant credits the seller; a
+ * failed one credits the buyer, so a seller who revokes the vault's
+ * role after listing can never keep the price of an undelivered grant.
+ *
* Payment: native BNB. `buy()`/`revoke()` require enough `msg.value`
* to cover both the listed price (buy only) and Greenfield's real
* cross-chain relay fee (`ICrossChain.getRelayFees()`, queried live —
* never hardcoded); any excess is refunded to the caller in the same
- * transaction. Sale proceeds use a pull-payment pattern
+ * transaction. Sale proceeds and refunds use a pull-payment pattern
* (`pendingWithdrawals` + `withdraw()`) so a misbehaving seller
* receive() can never block a buyer's purchase.
*/
@@ -71,7 +76,7 @@ contract GreenfieldVault is ReentrancyGuard, IApplication {
/*----------------- types -----------------*/
struct Listing {
address seller;
- uint256 price; // wei, exact amount credited to the seller per sale
+ uint256 price; // wei, escrowed at buy() and credited to the seller on a confirmed grant
bool active;
}
@@ -97,7 +102,7 @@ contract GreenfieldVault is ReentrancyGuard, IApplication {
/// @dev objectId => buyer => saleId. 0 means "no open purchase" — cleared
/// on Failed/Revoked so the pair can transact again.
mapping(bytes32 => mapping(address => uint256)) public saleIdOf;
- /// @dev Pull-payment balances credited to sellers on each sale.
+ /// @dev Pull-payment balances: sellers on a confirmed grant, buyers on a failed one.
mapping(address => uint256) public pendingWithdrawals;
uint256 public nextSaleId = 1;
@@ -201,6 +206,9 @@ contract GreenfieldVault is ReentrancyGuard, IApplication {
if (!listing.active) revert NotListed();
if (policyData.length == 0) revert EmptyPolicyData();
if (saleIdOf[objectId][msg.sender] != 0) revert AlreadyPurchased();
+ if (!objectAccessControl.hasRole(ROLE_CREATE, listing.seller, address(this))) {
+ revert NotAuthorizedByObjectOwner();
+ }
(uint256 relayFee, uint256 minAckRelayFee) = crossChain.getRelayFees();
uint256 requiredFee = relayFee + minAckRelayFee;
@@ -217,7 +225,6 @@ contract GreenfieldVault is ReentrancyGuard, IApplication {
status: SaleStatus.Pending
});
saleIdOf[objectId][msg.sender] = saleId;
- pendingWithdrawals[listing.seller] += listing.price;
IPermissionHub.ExtraData memory extraData = IPermissionHub.ExtraData({
appAddress: address(this),
@@ -261,13 +268,19 @@ contract GreenfieldVault is ReentrancyGuard, IApplication {
uint256 saleId = abi.decode(callbackData, (uint256));
Sale storage sale = sales[saleId];
if (sale.buyer == address(0)) revert UnknownSale();
+ if (sale.status != SaleStatus.Pending) return; // each sale settles exactly once
if (status == STATUS_SUCCESS) {
sale.policyId = resourceId;
sale.status = SaleStatus.Granted;
+ // The price was escrowed by buy(); the seller earns it only now that
+ // Greenfield confirmed the buyer's read grant.
+ pendingWithdrawals[sale.seller] += sale.price;
emit PolicyGranted(sale.objectId, sale.buyer, saleId, resourceId);
} else {
sale.status = SaleStatus.Failed;
+ // No grant was minted, so the escrowed price goes back to the buyer.
+ pendingWithdrawals[sale.buyer] += sale.price;
saleIdOf[sale.objectId][sale.buyer] = 0; // let the buyer retry
emit PolicyGrantFailed(sale.objectId, sale.buyer, saleId, status);
}
diff --git a/contracts/src/IdentityRegistry.sol b/contracts/src/IdentityRegistry.sol
index 55c2597c9..439c4cc6b 100644
--- a/contracts/src/IdentityRegistry.sol
+++ b/contracts/src/IdentityRegistry.sol
@@ -34,7 +34,12 @@ contract IdentityRegistry is ERC721Enumerable, EIP712, ReentrancyGuard {
mapping(address => uint256) public nonces;
// Max spend per on-chain agent ID per authorized spender (set by agent NFT owner)
- mapping(uint256 => mapping(address => uint256)) public spendAllowance;
+ // Keyed by an ownership epoch so every grant made by a previous owner is void
+ // once the agent NFT changes hands; read it through spendAllowance().
+ mapping(uint256 => mapping(uint256 => mapping(address => uint256))) private _spendAllowance;
+
+ // Bumped on every ownership change of an agent NFT.
+ mapping(uint256 => uint256) private _ownerEpoch;
// Per-agent deposited ETH balance held by this contract. The sum of all
// agentBalance entries equals the contract's spendable ETH; spend() may only
@@ -91,6 +96,30 @@ contract IdentityRegistry is ERC721Enumerable, EIP712, ReentrancyGuard {
constructor() ERC721("ERC-8004 Agent", "AGENT") EIP712("ERC8004-IdentityRegistry", "1") {}
+ // ---------------------------------------------------------------------
+ // Ownership changes
+ // ---------------------------------------------------------------------
+
+ /// @dev A transfer must not carry the previous owner's delegations to the new
+ /// owner: spend allowances are voided by advancing the agent's epoch and
+ /// the delegated wallet binding is cleared.
+ function _update(address to, uint256 tokenId, address auth)
+ internal
+ override
+ returns (address from)
+ {
+ from = super._update(to, tokenId, auth);
+ if (from != address(0) && from != to) {
+ unchecked {
+ _ownerEpoch[tokenId]++;
+ }
+ if (_agentWallet[tokenId] != address(0)) {
+ delete _agentWallet[tokenId];
+ emit WalletUnset(tokenId);
+ }
+ }
+ }
+
// ---------------------------------------------------------------------
// Registration
// ---------------------------------------------------------------------
@@ -257,10 +286,15 @@ contract IdentityRegistry is ERC721Enumerable, EIP712, ReentrancyGuard {
external
{
if (ownerOf(agentId) != msg.sender) revert NotAgentOwner();
- spendAllowance[agentId][spender] = maxWei;
+ _spendAllowance[agentId][_ownerEpoch[agentId]][spender] = maxWei;
emit SpendAllowanceSet(agentId, spender, maxWei);
}
+ /// @notice Remaining spend allowance of `spender` for the agent's current owner.
+ function spendAllowance(uint256 agentId, address spender) public view returns (uint256) {
+ return _spendAllowance[agentId][_ownerEpoch[agentId]][spender];
+ }
+
/// @notice Spend ETH held by this contract on behalf of an agent.
/// Caller must have been granted allowance via setSpendAllowance,
/// AND the spend is capped by the agent's own deposited balance so
@@ -271,10 +305,11 @@ contract IdentityRegistry is ERC721Enumerable, EIP712, ReentrancyGuard {
uint256 amountWei,
string calldata memo
) external nonReentrant {
- require(spendAllowance[agentId][msg.sender] >= amountWei, "allowance exceeded");
+ uint256 epoch = _ownerEpoch[agentId];
+ require(_spendAllowance[agentId][epoch][msg.sender] >= amountWei, "allowance exceeded");
if (recipient == address(0)) revert ZeroRecipient();
if (agentBalance[agentId] < amountWei) revert InsufficientAgentBalance();
- spendAllowance[agentId][msg.sender] -= amountWei;
+ _spendAllowance[agentId][epoch][msg.sender] -= amountWei;
agentBalance[agentId] -= amountWei;
(bool ok, ) = recipient.call{value: amountWei}("");
if (!ok) revert EthTransferFailed();
diff --git a/contracts/src/ThreeWsUniswapLauncher.sol b/contracts/src/ThreeWsUniswapLauncher.sol
index 80236f5b0..b9f5f625e 100644
--- a/contracts/src/ThreeWsUniswapLauncher.sol
+++ b/contracts/src/ThreeWsUniswapLauncher.sol
@@ -274,7 +274,7 @@ contract ThreeWsUniswapLauncher is IERC721Receiver, ReentrancyGuard {
int24 spacing = _validate(p);
if (msg.value != launchFeeWei) revert WrongLaunchFee();
- token = address(new FixedSupplyToken(p.name, p.symbol, SUPPLY_WHOLE, address(this)));
+ token = address(new FixedSupplyToken{salt: _salt(msg.sender, p)}(p.name, p.symbol, SUPPLY_WHOLE, address(this)));
_launching = true;
(pool, tokenId) = _seed(token, p, spacing);
_launching = false;
@@ -291,6 +291,24 @@ contract ThreeWsUniswapLauncher is IERC721Receiver, ReentrancyGuard {
_register(token, pool, tokenId, p);
}
+ /// @notice Address the token of `launch(p)` will get when `launcher` sends it.
+ /// @dev The token is deployed with CREATE2 and a salt that commits to the sender and every launch
+ /// parameter, so its address is not a function of the launcher's nonce. Nobody can pre-create
+ /// and poison the WETH pool of a token address before the launch parameters are known; changing
+ /// any parameter (for example the deadline) yields a fresh address.
+ /// @param launcher The account that will call `launch`.
+ /// @param p Launch parameters exactly as they will be submitted.
+ function predictTokenAddress(address launcher, LaunchParams calldata p) external view returns (address) {
+ bytes32 initCodeHash = keccak256(
+ abi.encodePacked(
+ type(FixedSupplyToken).creationCode, abi.encode(p.name, p.symbol, SUPPLY_WHOLE, address(this))
+ )
+ );
+ return address(
+ uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), address(this), _salt(launcher, p), initCodeHash))))
+ );
+ }
+
/// @notice Collect accrued trading fees of a locked position and distribute them. Callable by anyone.
/// @dev The treasury receives `platformShareBps` of each token, the position's fee recipient the rest.
/// @param tokenId Locked position id.
@@ -396,6 +414,10 @@ contract ThreeWsUniswapLauncher is IERC721Receiver, ReentrancyGuard {
);
}
+ function _salt(address sender, LaunchParams calldata p) private pure returns (bytes32) {
+ return keccak256(abi.encode(sender, p));
+ }
+
function _validate(LaunchParams calldata p) private view returns (int24 spacing) {
if (block.timestamp > p.deadline) revert DeadlinePassed();
spacing = _tickSpacing(p.fee);
diff --git a/contracts/test/GreenfieldVault.t.sol b/contracts/test/GreenfieldVault.t.sol
index db5106408..9f54bec31 100644
--- a/contracts/test/GreenfieldVault.t.sol
+++ b/contracts/test/GreenfieldVault.t.sol
@@ -199,7 +199,7 @@ contract GreenfieldVaultTest is Test {
uint256 saleId = vault.buy{value: TOTAL_REQUIRED}(OBJECT_ID, POLICY_DATA);
assertEq(saleId, 1);
- assertEq(vault.pendingWithdrawals(seller), PRICE);
+ assertEq(vault.pendingWithdrawals(seller), 0);
assertEq(vault.saleIdOf(OBJECT_ID, buyer), 1);
(
@@ -298,6 +298,8 @@ contract GreenfieldVaultTest is Test {
uint256 saleId1 = _buy(buyer, OBJECT_ID);
uint256 saleId2 = _buy(buyer2, OBJECT_ID);
assertTrue(saleId1 != saleId2);
+ permissionHub.settleCreatePolicy(saleId1, STATUS_SUCCESS);
+ permissionHub.settleCreatePolicy(saleId2, STATUS_SUCCESS);
assertEq(vault.pendingWithdrawals(seller), PRICE * 2);
}
@@ -318,6 +320,65 @@ contract GreenfieldVaultTest is Test {
assertTrue(saleId2 != saleId);
}
+ // ── GV-10: proceeds are escrowed until Greenfield confirms the grant ────
+
+ function testSellerNotCreditedUntilGrantSettles() public {
+ _list(seller, OBJECT_ID, PRICE);
+ uint256 saleId = _buy(buyer, OBJECT_ID);
+ assertEq(vault.pendingWithdrawals(seller), 0, "no credit while the ack is pending");
+
+ permissionHub.settleCreatePolicy(saleId, STATUS_SUCCESS);
+ assertEq(vault.pendingWithdrawals(seller), PRICE, "credited on confirmed grant");
+ }
+
+ function testGrantFailureRefundsBuyerAndNeverPaysSeller() public {
+ _list(seller, OBJECT_ID, PRICE);
+ uint256 saleId = _buy(buyer, OBJECT_ID);
+
+ // The seller revokes the role the vault needs before Greenfield acks.
+ bytes32 role = vault.ROLE_CREATE();
+ vm.prank(seller);
+ accessControl.revokeRole(role, address(vault));
+ permissionHub.settleCreatePolicy(saleId, STATUS_FAILED);
+
+ assertEq(vault.pendingWithdrawals(seller), 0, "seller earns nothing from a failed grant");
+ assertEq(vault.pendingWithdrawals(buyer), PRICE, "buyer's price is refundable");
+
+ vm.prank(seller);
+ vm.expectRevert(GreenfieldVault.NothingToWithdraw.selector);
+ vault.withdraw();
+
+ uint256 before = buyer.balance;
+ vm.prank(buyer);
+ vault.withdraw();
+ assertEq(buyer.balance, before + PRICE);
+ }
+
+ function testRepeatedSettlementDoesNotDoubleCredit() public {
+ _list(seller, OBJECT_ID, PRICE);
+ uint256 saleId = _buy(buyer, OBJECT_ID);
+ permissionHub.settleCreatePolicy(saleId, STATUS_SUCCESS);
+
+ vm.prank(address(permissionHub));
+ vault.greenfieldCall(STATUS_FAILED, 0x07, 2, 1, abi.encode(saleId));
+ vm.prank(address(permissionHub));
+ vault.greenfieldCall(STATUS_SUCCESS, 0x07, 2, 1, abi.encode(saleId));
+
+ assertEq(vault.pendingWithdrawals(seller), PRICE);
+ assertEq(vault.pendingWithdrawals(buyer), 0);
+ }
+
+ function testBuyRevertsWhenSellerRevokedRoleAfterListing() public {
+ _list(seller, OBJECT_ID, PRICE);
+ bytes32 role = vault.ROLE_CREATE();
+ vm.prank(seller);
+ accessControl.revokeRole(role, address(vault));
+
+ vm.prank(buyer);
+ vm.expectRevert(GreenfieldVault.NotAuthorizedByObjectOwner.selector);
+ vault.buy{value: TOTAL_REQUIRED}(OBJECT_ID, POLICY_DATA);
+ }
+
// ── GV-6: greenfieldCall access control ────────────────────────────────
/// GV-6 (negative half): only the PermissionHub contract may deliver an ack.
@@ -372,6 +433,7 @@ contract GreenfieldVaultTest is Test {
permissionHub.setRejectOnCreate(false);
uint256 saleId = _buy(buyer, OBJECT_ID);
assertEq(vault.saleIdOf(OBJECT_ID, buyer), saleId);
+ permissionHub.settleCreatePolicy(saleId, STATUS_SUCCESS);
assertEq(vault.pendingWithdrawals(seller), PRICE);
}
@@ -465,7 +527,8 @@ contract GreenfieldVaultTest is Test {
function testWithdrawHappyPath() public {
_list(seller, OBJECT_ID, PRICE);
- _buy(buyer, OBJECT_ID);
+ uint256 saleId = _buy(buyer, OBJECT_ID);
+ permissionHub.settleCreatePolicy(saleId, STATUS_SUCCESS);
uint256 before = seller.balance;
vm.prank(seller);
@@ -493,7 +556,8 @@ contract GreenfieldVaultTest is Test {
accessControl.grantRole(role, address(vault), 0);
badSeller.doList(vault, OBJECT_ID, PRICE);
- _buy(buyer, OBJECT_ID);
+ uint256 saleId = _buy(buyer, OBJECT_ID);
+ permissionHub.settleCreatePolicy(saleId, STATUS_SUCCESS);
assertEq(vault.pendingWithdrawals(address(badSeller)), PRICE);
vm.expectRevert(GreenfieldVault.TransferFailed.selector);
@@ -545,9 +609,11 @@ contract GreenfieldVaultTest is Test {
_list(seller, OBJECT_ID, PRICE);
_list(seller, OBJECT_ID_2, 2 ether);
- _buy(buyer, OBJECT_ID);
+ uint256 s1 = _buy(buyer, OBJECT_ID);
vm.prank(buyer2);
- vault.buy{value: 2 ether + TOTAL_FEE}(OBJECT_ID_2, POLICY_DATA);
+ uint256 s2 = vault.buy{value: 2 ether + TOTAL_FEE}(OBJECT_ID_2, POLICY_DATA);
+ permissionHub.settleCreatePolicy(s1, STATUS_SUCCESS);
+ permissionHub.settleCreatePolicy(s2, STATUS_SUCCESS);
assertEq(vault.pendingWithdrawals(seller), 3 ether);
assertGe(address(vault).balance, vault.pendingWithdrawals(seller), "GV-5: held ETH must cover every credit");
@@ -608,7 +674,8 @@ contract GreenfieldVaultTest is Test {
accessControl.grantRole(role, address(vault), 0);
attacker.doList(OBJECT_ID, PRICE);
- _buy(buyer, OBJECT_ID);
+ uint256 saleId = _buy(buyer, OBJECT_ID);
+ permissionHub.settleCreatePolicy(saleId, STATUS_SUCCESS);
assertEq(vault.pendingWithdrawals(address(attacker)), PRICE);
attacker.arm(abi.encodeWithSelector(GreenfieldVault.withdraw.selector), 0);
diff --git a/contracts/test/IdentityRegistry.t.sol b/contracts/test/IdentityRegistry.t.sol
index a6e64f3d2..4b767a3b5 100644
--- a/contracts/test/IdentityRegistry.t.sol
+++ b/contracts/test/IdentityRegistry.t.sol
@@ -301,6 +301,57 @@ contract IdentityRegistryTest is Test {
assertEq(reg.getAgentWallet(id), bob, "ID-4: the fallback follows the current owner");
}
+ // ── ID-9: a transfer revokes the seller's spend rights and wallet binding ─
+
+ function testTransferRevokesSellerSpendAllowance() public {
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+ vm.prank(alice);
+ reg.setSpendAllowance(id, spender, 5 ether);
+
+ vm.prank(alice);
+ reg.transferFrom(alice, bob, id);
+
+ vm.prank(bob);
+ reg.deposit{value: 3 ether}(id);
+
+ assertEq(reg.spendAllowance(id, spender), 0, "allowance does not survive the sale");
+ vm.prank(spender);
+ vm.expectRevert(bytes("allowance exceeded"));
+ reg.spend(id, payable(spender), 1 ether, "seller drain");
+ assertEq(reg.agentBalance(id), 3 ether);
+ }
+
+ function testNewOwnerCanGrantAllowanceAfterTransfer() public {
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+ vm.prank(alice);
+ reg.transferFrom(alice, bob, id);
+ vm.prank(bob);
+ reg.deposit{value: 2 ether}(id);
+ vm.prank(bob);
+ reg.setSpendAllowance(id, spender, 1 ether);
+
+ vm.prank(spender);
+ reg.spend(id, payable(carol), 1 ether, "ok");
+ assertEq(reg.agentBalance(id), 1 ether);
+ }
+
+ function testTransferClearsDelegatedWallet() public {
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+ address delegate = address(0xDE1E6A7E);
+ uint256 deadline = block.timestamp + 1 hours;
+ bytes memory sig = _signSetWallet(alicePk, alice, id, delegate, deadline);
+ reg.setAgentWallet(id, delegate, deadline, sig);
+ assertEq(reg.getAgentWallet(id), delegate);
+
+ vm.prank(alice);
+ reg.transferFrom(alice, bob, id);
+
+ assertEq(reg.getAgentWallet(id), bob, "the previous owner's delegate no longer represents the agent");
+ }
+
// ── ID-5: ETH only enters through deposit ────────────────────────────────
function testBareEthTransferReverts() public {
diff --git a/contracts/test/ThreeWsUniswapLauncher.t.sol b/contracts/test/ThreeWsUniswapLauncher.t.sol
index 494ad8924..288e8886e 100644
--- a/contracts/test/ThreeWsUniswapLauncher.t.sol
+++ b/contracts/test/ThreeWsUniswapLauncher.t.sol
@@ -85,12 +85,18 @@ contract ThreeWsUniswapLauncherTest is Test {
});
}
- /// Bump the launcher nonce until the next token address sorts on the requested side of WETH.
- function _forceOrdering(ThreeWsUniswapLauncher l, bool tokenIsToken0) internal returns (address predicted) {
+ /// Vary the deadline until the token address this launch will get sorts on the requested side of
+ /// WETH. The address is a CREATE2 function of (sender, every launch parameter), so the deadline
+ /// is the free knob.
+ function _fitOrdering(ThreeWsUniswapLauncher l, ThreeWsUniswapLauncher.LaunchParams memory p, bool tokenIsToken0)
+ internal
+ view
+ returns (address predicted)
+ {
for (uint256 i; i < 64; i++) {
- predicted = vm.computeCreateAddress(address(l), vm.getNonce(address(l)));
+ predicted = l.predictTokenAddress(address(this), p);
if ((predicted < WETH) == tokenIsToken0) return predicted;
- vm.setNonce(address(l), uint64(vm.getNonce(address(l)) + 1));
+ p.deadline += 1;
}
revert("ordering not found");
}
@@ -99,7 +105,7 @@ contract ThreeWsUniswapLauncherTest is Test {
internal
returns (address token, address pool, uint256 tokenId)
{
- address predicted = _forceOrdering(l, tokenIsToken0);
+ address predicted = _fitOrdering(l, p, tokenIsToken0);
(token, pool, tokenId) = l.launch{value: l.launchFeeWei()}(p);
assertEq(token, predicted, "token address prediction");
}
@@ -177,7 +183,7 @@ contract ThreeWsUniswapLauncherTest is Test {
function test_mode0_emitsLaunched() public {
ThreeWsUniswapLauncher.LaunchParams memory p = _params(0, 3000);
- address token = _forceOrdering(plain, true);
+ address token = _fitOrdering(plain, p, true);
vm.recordLogs();
plain.launch(p);
Vm.Log[] memory logs = vm.getRecordedLogs();
@@ -405,28 +411,55 @@ contract ThreeWsUniswapLauncherTest is Test {
// ---------------------------------------------------------------- front-run
- /// The token address is the launcher's next CREATE address, so an attacker can pre-create and
- /// initialise the pool at a hostile price before the launch lands. The launch must revert.
- function test_poolPriceMoved_whenPoolFrontRun() public {
+ /// The token address is a CREATE2 function of the sender and every launch parameter, not of the
+ /// launcher nonce. An attacker who poisons the pool of the address the old CREATE scheme would
+ /// have produced gains nothing, and the launch still succeeds.
+ function test_launchIgnoresPoolsPoisonedAtNonceAddress() public {
for (uint256 i; i < 2; i++) {
bool tokenIsToken0 = i == 0;
- address token = _forceOrdering(plain, tokenIsToken0);
- (address t0, address t1) = tokenIsToken0 ? (token, WETH) : (WETH, token);
- uint160 hostile = TickMath.getSqrtRatioAtTick(tokenIsToken0 ? int24(-100000) : int24(100000));
- vm.prank(makeAddr("attacker"));
- INonfungiblePositionManager(PM).createAndInitializePoolIfNecessary(t0, t1, 10000, hostile);
-
ThreeWsUniswapLauncher.LaunchParams memory p = _params(0, 10000);
- vm.expectRevert(ThreeWsUniswapLauncher.PoolPriceMoved.selector);
- plain.launch(p);
+ address predicted = _fitOrdering(plain, p, tokenIsToken0);
+ address nonceAddress = vm.computeCreateAddress(address(plain), vm.getNonce(address(plain)));
+ assertTrue(nonceAddress != predicted, "token address is not the nonce address");
+
+ (address t0, address t1) = nonceAddress < WETH ? (nonceAddress, WETH) : (WETH, nonceAddress);
+ uint160 hostile = TickMath.getSqrtRatioAtTick(nonceAddress < WETH ? int24(-100000) : int24(100000));
+ for (uint256 f; f < 3; f++) {
+ uint24 fee = f == 0 ? 500 : f == 1 ? 3000 : 10000;
+ vm.prank(makeAddr("attacker"));
+ INonfungiblePositionManager(PM).createAndInitializePoolIfNecessary(t0, t1, fee, hostile);
+ }
- // A different fee tier is unaffected by the poisoned tier.
- p.fee = 3000;
(address deployed,,) = plain.launch(p);
- assertEq(deployed, token);
+ assertEq(deployed, predicted, "CREATE2 address matches the prediction");
}
}
+ function test_predictTokenAddressCommitsToSenderAndParams() public view {
+ ThreeWsUniswapLauncher.LaunchParams memory p = _params(0, 10000);
+ address base = plain.predictTokenAddress(address(this), p);
+ assertTrue(base != plain.predictTokenAddress(stranger, p), "sender is committed");
+ p.deadline += 1;
+ assertTrue(base != plain.predictTokenAddress(address(this), p), "params are committed");
+ }
+
+ /// Backstop: if a pool does exist at the exact token address at a hostile price, the launch still
+ /// reverts instead of seeding liquidity at the wrong price, and a changed parameter escapes it.
+ function test_poolPriceMoved_whenPoolFrontRun() public {
+ ThreeWsUniswapLauncher.LaunchParams memory p = _params(0, 10000);
+ address token = _fitOrdering(plain, p, true);
+ uint160 hostile = TickMath.getSqrtRatioAtTick(int24(-100000));
+ vm.prank(makeAddr("attacker"));
+ INonfungiblePositionManager(PM).createAndInitializePoolIfNecessary(token, WETH, 10000, hostile);
+
+ vm.expectRevert(ThreeWsUniswapLauncher.PoolPriceMoved.selector);
+ plain.launch(p);
+
+ p.deadline += 1;
+ (address deployed,,) = plain.launch(p);
+ assertTrue(deployed != token, "a changed parameter yields a fresh address");
+ }
+
// ---------------------------------------------------------------- NFT custody
function test_rejectsStrayNFTs() public {
@@ -446,14 +479,16 @@ contract ThreeWsUniswapLauncherTest is Test {
// ---------------------------------------------------------------- gas
function test_gas_mode0_and_mode1() public {
- _forceOrdering(plain, true);
+ ThreeWsUniswapLauncher.LaunchParams memory p0 = _params(0, 10000);
+ _fitOrdering(plain, p0, true);
uint256 g = gasleft();
- plain.launch(_params(0, 10000));
+ plain.launch(p0);
emit log_named_uint("gas launch mode0", g - gasleft());
- _forceOrdering(plain, true);
+ ThreeWsUniswapLauncher.LaunchParams memory p1 = _params(1, 10000);
+ _fitOrdering(plain, p1, true);
g = gasleft();
- plain.launch(_params(1, 10000));
+ plain.launch(p1);
emit log_named_uint("gas launch mode1", g - gasleft());
}
}