TExcelTAD
Home › Solidity › Creating Contracts

Creating Contracts

Contracts can deploy other contracts. This is how factories work: a single factory contract creates one escrow per deal, one wallet per user, or one trading pair per token combination. Solidity offers two creation mechanisms, CREATE and CREATE2, and they differ in how the new address is chosen.

new with CREATE

new C(args) deploys C and returns a reference to it. The new address is derived from the creator's address and its nonce (how many contracts it has created so far), so it is predictable but depends on order:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Escrow {
    address public buyer;
    address public seller;
    uint256 public price;

    constructor(address buyer_, address seller_, uint256 price_) {
        buyer = buyer_;
        seller = seller_;
        price = price_;
    }
}

contract EscrowFactory {
    Escrow[] public escrows;
    event EscrowCreated(uint256 indexed id, address escrow);

    function create(address buyer, address seller, uint256 price) external returns (Escrow e) {
        e = new Escrow(buyer, seller, price);
        escrows.push(e);
        emit EscrowCreated(escrows.length - 1, address(e));
    }

    function count() external view returns (uint256) {
        return escrows.length;
    }
}

contract Main {
    function main() external {
        EscrowFactory factory = new EscrowFactory();
        Escrow first = factory.create(address(0xA), address(0xB), 100);
        factory.create(address(0xC), address(0xD), 250);
        console.log("escrows:", factory.count());
        console.log("first price:", first.price());
        console.log("second price:", factory.escrows(1).price());
    }
}
escrows: 2
first price: 100
second price: 250
event EscrowCreated(id: 0, escrow: 0x8Ff3801288a85ea261E4277d44E1131Ea736F77B)
event EscrowCreated(id: 1, escrow: 0x4CEc804494d829bEA93AB8eA7045A7efBED3c229)

Each Escrow is a separate contract with its own address and storage. The factory keeps a list so they can be found later, and an event announces each one to off-chain indexers.

Sending ether at creation

new C{value: amount}(args) funds the new contract immediately, which requires a payable constructor (see Constructors).

CREATE2: addresses you can predict

new C{salt: s}(args) uses CREATE2. The address depends only on:

  • the creator's address,
  • the 32-byte salt you choose,
  • the hash of the contract's creation code (including constructor arguments).

So the address can be computed before deployment, by anyone. That's used for counterfactual wallets (you can receive funds at an address before deploying the wallet) and for exchanges that find a pair's address without a lookup.

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Wallet {
    address public owner;
    constructor(address owner_) {
        owner = owner_;
    }
}

contract WalletFactory {
    function predict(address owner, bytes32 salt) public view returns (address) {
        bytes memory initCode = abi.encodePacked(type(Wallet).creationCode, abi.encode(owner));
        bytes32 hash = keccak256(abi.encodePacked(bytes1(0xff), address(this), salt, keccak256(initCode)));
        return address(uint160(uint256(hash)));
    }

    function deploy(address owner, bytes32 salt) external returns (Wallet) {
        return new Wallet{salt: salt}(owner);
    }
}

contract Main {
    function main() external {
        WalletFactory factory = new WalletFactory();
        address alice = address(0xA11CE);
        bytes32 salt = keccak256("alice-wallet");

        address predicted = factory.predict(alice, salt);
        Wallet w = factory.deploy(alice, salt);

        console.log("predicted:", predicted);
        console.log("deployed :", address(w));
        console.log("match?", predicted == address(w));

        factory.deploy(alice, salt);    // same salt + code: address already used
    }
}
predicted: 0x09be62B936696184EB1aB98cdbc0857d0148cBeB
deployed : 0x09be62B936696184EB1aB98cdbc0857d0148cBeB
match? true
main() failed: reverted without a reason

Deploying twice with the same salt and code fails, because the address is already occupied. The playground shows this as a revert without a reason: the creation itself failed, and Solidity's new then reverts.

Cloning: cheap copies

Deploying a full contract for every user is expensive when the code is large. Minimal proxies (ERC-1167, "clones") are tiny contracts of 45 bytes that forward every call with delegatecall to one shared implementation. OpenZeppelin's Clones library creates them. The Proxies lesson explains delegatecall.

Checking that an address is a contract

addr.code.length > 0 tells you whether code is deployed at addr. Be careful: during its own constructor a contract has no code yet, so this check can't reliably tell humans from contracts.

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Probe {
    uint256 public codeSizeDuringConstructor;
    constructor() {
        codeSizeDuringConstructor = address(this).code.length;
    }
}

contract Main {
    function main() external {
        Probe p = new Probe();
        console.log("code size during constructor:", p.codeSizeDuringConstructor());
        console.log("code size after deployment  :", address(p).code.length);
        console.log("EOA code size               :", msg.sender.code.length);
    }
}
code size during constructor: 0
code size after deployment  : 172
EOA code size               : 0

Test yourself

What does the address of a contract created with new C() (CREATE) depend on?

  1. The contract's code only
  2. The creator's address and nonce
  3. The block timestamp
  4. A random number

Which inputs determine a CREATE2 address?

  1. Creator, nonce, gas price
  2. Creator, salt, hash of the creation code
  3. Salt only
  4. Creator and block number

Why is addr.code.length == 0 not proof that addr is a person's wallet?

  1. Wallets also have code
  2. A contract under construction has no code yet, and future CREATE2 addresses are empty too
  3. code.length is always 0
  4. It only works for libraries