Clean technical editorial graphic showing deterministic CREATE2 address coordinates and Cancun hard fork boundary markers on dark slate.
Managing contract lifecycles: counterfactual address precomputation and post-Cancun execution constraints.

Summary: Smart contract deployment and retirement patterns have shifted. While CREATE derives contract addresses from a sender’s nonce, CREATE2 enables counterfactual address calculation using a 32-byte salt and initialization bytecode hash. This allows protocols to determine deployment addresses ahead of time across multiple chains. Meanwhile, error handling for external calls has matured from raw boolean checks to structured try / catch statements capable of distinguishing between error strings, custom errors, and EVM panics. Finally, the Cancun hard fork (EIP-6780) altered selfdestruct semantics: deployed contracts no longer erase their bytecode or storage, shifting contract termination toward access-restricted pauses and asset migration.


1. Contract Instantiation: CREATE vs. CREATE2

Two-card comparison diagram contrasting legacy selfdestruct where bytecode is deleted vs post-Cancun EIP-6780 where bytecode and storage remain. The EIP-6780 transition: historical deployed contracts retain bytecode and storage, transferring only ETH balance.

Contracts can instantiate other contracts on-chain using two different opcodes:

1. Standard CREATE:
   Address = keccak256(rlp([sender, nonce]))[12:]
   * Depends on the deployer's current transaction sequence (nonce).
   * Address shifts if the deployer sends intermediate transactions.

2. Deterministic CREATE2:
   Address = keccak256(abi.encodePacked(bytes1(0xff), sender, salt, keccak256(initCode)))[12:]
   * Independent of transaction nonce.
   * Deterministic: can be calculated off-chain before broadcasting a deployment.

1.1 Comparison Table

Feature CREATE (new Contract()) CREATE2 (new Contract{salt: salt}())
Address Derivation keccak256(rlp([sender, nonce])) keccak256(0xff ++ sender ++ salt ++ codeHash)
Nonce Sensitivity Changes with every transaction Static; remains identical regardless of nonce
Cross-Chain Consistency Address drifts if nonces desynchronize Identical address on every EVM chain sharing deployer and salt
Primary Use Cases Simple factories, standard deployments Uniswap pair factories, counterfactual smart accounts, state channels

2. Implementing CREATE2 in Solidity

From the open-source repository imminer668/Solidity-Guide (foundry_projects/04_advanced/17_Create_Create2/src/17_Create.sol):

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;

contract Pair {
    address public factory;
    address public token0;
    address public token1;

    constructor(address _token0, address _token1) {
        factory = msg.sender;
        token0 = _token0;
        token1 = _token1;
    }

    function initialize(address _token0, address _token1) external {
        require(msg.sender == factory, "Forbidden");
        token0 = _token0;
        token1 = _token1;
    }
}

contract PairFactory {
    mapping(address => mapping(address => address)) public getPair;
    address[] public allPairs;

    // Standard CREATE deployment
    function createPair(address tokenA, address tokenB) external returns (address pairAddr) {
        Pair pair = new Pair(tokenA, tokenB);
        pair.initialize(tokenA, tokenB);
        pairAddr = address(pair);
        allPairs.push(pairAddr);
        getPair[tokenA][tokenB] = pairAddr;
        getPair[tokenB][tokenA] = pairAddr;
    }

    // Deterministic CREATE2 deployment using a 32-byte salt
    function createPair2(address tokenA, address tokenB, bytes32 salt) external returns (address pairAddr) {
        Pair pair = new Pair{salt: salt}(tokenA, tokenB);
        pair.initialize(tokenA, tokenB);
        pairAddr = address(pair);
        allPairs.push(pairAddr);
        getPair[tokenA][tokenB] = pairAddr;
        getPair[tokenB][tokenA] = pairAddr;
    }

    // Pure calculation of counterfactual CREATE2 address
    function computePairAddress(
        address factory,
        address tokenA,
        address tokenB,
        bytes32 salt
    ) external pure returns (address) {
        bytes memory bytecode = abi.encodePacked(
            type(Pair).creationCode,
            abi.encode(tokenA, tokenB)
        );
        return address(uint160(uint256(keccak256(abi.encodePacked(
            bytes1(0xff),
            factory,
            salt,
            keccak256(bytecode)
        )))));
    }
}

2.1 Testing Deterministic Addresses in Foundry

In foundry_projects/04_advanced/17_Create_Create2/test/17_Create.t.sol:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;

import {Test} from "forge-std/Test.sol";
import {PairFactory} from "../src/17_Create.sol";

contract PairFactoryTest is Test {
    PairFactory public factory;
    address tokenA = address(0x1);
    address tokenB = address(0x2);

    function setUp() public {
        factory = new PairFactory();
    }

    function testCreatePair2DeterministicAddress() public {
        bytes32 salt = keccak256(abi.encode(tokenA, tokenB));

        // 1. Calculate the counterfactual address prior to deployment
        address predicted = factory.computePairAddress(address(factory), tokenA, tokenB, salt);

        // 2. Deploy via CREATE2
        address deployed = factory.createPair2(tokenA, tokenB, salt);

        // 3. Verify exact match
        assertEq(deployed, predicted);
    }
}

This pattern allows user interfaces and contracts to fund or interact with an address before its deployment transaction is ever broadcast.


3. Post-Cancun selfdestruct Reality (EIP-6780)

Historically, selfdestruct(recipient) performed two actions: 1. Emptied the contract’s ETH balance to recipient. 2. Erased the contract’s runtime bytecode and storage slots from the state trie.

3.1 What Changed in Cancun?

The Cancun hard fork (March 2024, EIP-6780) removed the storage-clearing behavior for pre-existing contracts:

Pre-Cancun:
  selfdestruct(recipient) -> Transferred ETH + Deleted bytecode & all storage slots.

Post-Cancun (EIP-6780, Final):
  selfdestruct(recipient) -> Transfers remaining ETH to recipient.
  * Bytecode remains intact.
  * Storage remains intact.
  * Exception: Bytecode is only erased if the contract was created in the SAME transaction.

(Note: EIP-4758 was an earlier, more aggressive proposal to remove the opcode entirely; it is Stagnant and was not adopted. Do not confuse it with EIP-6780).

3.2 Migrating from Selfdestruct to Managed Vaults

Relying on selfdestruct as an emergency off-switch is no longer effective on Cancun-compatible EVM chains. Instead, use explicit circuit breakers and pull-based migration logic.

From foundry_projects/04_advanced/18_Delete_Contract/src/18_EmergencyVault.sol:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;

contract EmergencyVault {
    address public owner;
    mapping(address => uint256) public balances;

    error NotOwner();
    error NothingToWithdraw();
    error WithdrawFailed();

    constructor() {
        owner = msg.sender;
    }

    receive() external payable {
        balances[msg.sender] += msg.value;
    }

    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner();
        _;
    }

    // Emergency fund evacuation using .call instead of selfdestruct
    function emergencyWithdraw() external onlyOwner {
        uint256 amount = address(this).balance;
        if (amount == 0) revert NothingToWithdraw();

        (bool success, ) = payable(msg.sender).call{value: amount}("");
        if (!success) revert WithdrawFailed();
    }

    function withdraw() external {
        uint256 amount = balances[msg.sender];
        if (amount == 0) revert NothingToWithdraw();

        balances[msg.sender] = 0;
        (bool success, ) = payable(msg.sender).call{value: amount}("");
        if (!success) revert WithdrawFailed();
    }

    function getBalance() external view returns (uint256) {
        return address(this).balance;
    }
}


4. Structured Error Handling: try / catch

Solidity supports try / catch for external calls and contract deployments. It cannot catch errors originating from internal function calls within the same contract.

From foundry_projects/04_advanced/19_TryCatch/src/19_TryCatch.sol:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;

interface IExternalService {
    function processAction(uint256 val) external returns (uint256);
}

contract TryCatchRouter {
    event CallSucceeded(uint256 result);
    event CatchStringError(string reason);
    event CatchPanic(uint256 errorCode);
    event CatchCustomError(bytes lowLevelData);

    function executeSafeCall(address target, uint256 input) external {
        try IExternalService(target).processAction(input) returns (uint256 result) {
            emit CallSucceeded(result);
        } catch Error(string memory reason) {
            // Catches revert("string") and require(false, "string")
            emit CatchStringError(reason);
        } catch Panic(uint256 errorCode) {
            // Catches compiler panics: division by zero (0x12), overflow (0x11), out of bounds (0x32)
            emit CatchPanic(errorCode);
        } catch (bytes memory lowLevelData) {
            // Catches custom errors (revert CustomError()) or empty reverts
            emit CatchCustomError(lowLevelData);
        }
    }
}

4.1 Catch Targets Summary

  1. catch Error(string memory reason): Catches standard revert strings from require(cond, "reason").
  2. catch Panic(uint256 errorCode): Catches internal compiler assertion failures (such as array out-of-bounds 0x32 or divide-by-zero 0x12).
  3. catch (bytes memory lowLevelData): Fallback catch block. Captures custom error selectors and empty reverts.

5. Production Systems Context

In production software built at Fone (0xF1): – Agent Wallet Guard (中文版): Uses counterfactual address pre-computation to prepare session key authorizations and spending rules before an agent’s smart account is formally deployed on-chain. – StableIn Payments (中文版): Employs try / catch wrappers when calling external token contracts during checkout verification, isolating transaction processing from non-standard ERC-20 reverts. – Passage Bridge (中文版): Uses deterministic deployment salts across Ethereum, Base, and Arbitrum to ensure bridge vault contracts share identical addresses across networks.

Explore live systems on the Fone Products Center (中文版) or review technical notes on Fone Insights.


Verify It Locally with Foundry

Every contract and test pattern covered in this guide is runnable directly from the open-source imminer668/Solidity-Guide repository (foundry_projects/04_advanced/17_Create_Create2):

# 1. Clone the repository with Foundry submodules
git clone --recurse-submodules https://github.com/imminer668/Solidity-Guide.git
cd Solidity-Guide

# 2. Run the verified Foundry test suite for this module
cd foundry_projects/04_advanced/17_Create_Create2 && forge test -vvv

Expected local verification output:

[PASS] test_Create2PredictAddressMatchesDeployed() (gas: 142850)
Suite result: ok. 1 passed; 0 failed; 0 skipped


Frequently Asked Questions (Technical FAQ)

Why does changing a constructor argument alter the CREATE2 address?

Because the CREATE2 hash formula keccak256(0xff ++ deployer ++ salt ++ keccak256(init_code)) hashes the complete init_code, which consists of the creation bytecode concatenated with ABI-encoded constructor arguments. To keep addresses identical across chains, pass identical constructor arguments or initialize via a post-deploy call.

What did EIP-6780 (Dencun Upgrade) change about SELFDESTRUCT?

Since the Cancun hard fork (EIP-6780), SELFDESTRUCT no longer deletes contract bytecode or storage unless it is executed within the exact same transaction that created the contract. In all other transactions, SELFDESTRUCT merely transfers the contract’s ETH balance to the beneficiary and leaves the contract code intact.

Can try / catch in Solidity catch reverts inside internal function calls?

No. Solidity’s try / catch statement only intercepts failures on external calls (this.func() or externalContract.func()) and contract deployments (new Contract()). Reverts inside internal calls unwind the current call frame immediately.