3分钟Solidity: 5.8 创建其他合约的合约

38 阅读1分钟

欢迎订阅专栏3分钟Solidity--Web3区块链技术必学

如需获取本内容的最新版本,请参见 Cyfrin.io 上的“创建其他合约的合约(代码示例)”

合约可以通过使用 new 关键字由其他合约创建。

自 0.8.0 版本起,new 关键字支持通过指定 salt 选项来使用 create2 功能。

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

contract Car {
    address public owner;
    string public model;
    address public carAddr;

    constructor(address _owner, string memory _model) payable {
        owner = _owner;
        model = _model;
        carAddr = address(this);
    }
}

contract CarFactory {
    Car[] public cars;

    function create(address _owner, string memory _model) public {
        Car car = new Car(_owner, _model);
        cars.push(car);
    }

    function createAndSendEther(address _owner, string memory _model)
        public
        payable
    {
        Car car = (new Car){value: msg.value}(_owner, _model);
        cars.push(car);
    }

    function create2(address _owner, string memory _model, bytes32 _salt)
        public
    {
        Car car = (new Car){salt: _salt}(_owner, _model);
        cars.push(car);
    }

    function create2AndSendEther(
        address _owner,
        string memory _model,
        bytes32 _salt
    ) public payable {
        Car car = (new Car){value: msg.value, salt: _salt}(_owner, _model);
        cars.push(car);
    }

    function getCar(uint256 _index)
        public
        view
        returns (
            address owner,
            string memory model,
            address carAddr,
            uint256 balance
        )
    {
        Car car = cars[_index];

        return (car.owner(), car.model(), car.carAddr(), address(car).balance);
    }
}

Remix Lite 尝试一下

solidity-newContract

END