// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; contract D { uint public x; constructor(uint a) { x = a; } }
contract C { function createDSalted(bytes32 salt, uint arg) public { // This complicated expression just tells you how the address // can be pre-computed. It is just there for illustration. // You actually only need ``new D{salt: salt}(arg)``. //这些复杂的表达只是告诉我们地址是如何被提前计算的,仅作展示 //事实上只需要``(new D){salt: salt}(arg)`` address predictedAddress = address(uint160(uint(keccak256(abi.encodePacked( bytes1(0xff), address(this), salt, keccak256(abi.encodePacked( type(D).creationCode, abi.encode(arg) )) )))));
D d = new D{salt: salt}(arg); require(address(d) == predictedAddress); } }
pragma solidity ^0.8.17; //SPDX-License-Identifier: MIT contract Car{ address owner;//表示拥有者 string public model;//表示车型 address carAddr;//表示合约地址 constructor(address _owner, string memory _model) payable{ owner = _owner; model = _model; carAddr = address(this); } } contract CarFactory{ Car[] public cars; function createNewCar(string memory _model) public { cars.push(new Car(address(this), _model)); } function createNewCarAndSendEther(string memory _model) public payable { Car car = (new Car){value:msg.value}(address(this), _model); cars.push(car); }
function create2NewCar(string memory _model, bytes32 salt) public { Car car = (new Car){salt:salt}(address(this), _model); cars.push(car); } function create2NewCarWithEther(string memory _model, bytes32 salt) public payable { Car car = (new Car){value:msg.value, salt:salt}(address(this), _model); cars.push(car); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.17;
library Math { function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 (default value) } }
contract TestMath { function testSquareRoot(uint x) public pure returns (uint) { return Math.sqrt(x); } }
// Array function to delete element at index and re-organize the array // so that there are no gaps between the elements. library Array { function remove(uint[] storage arr, uint index) public { // Move the last element into the place to delete require(arr.length > 0, "Can't remove from empty array"); arr[index] = arr[arr.length - 1]; arr.pop(); } }
contract TestArray { using Array for uint[];
uint[] public arr;
function testArrayRemove() public { for (uint i = 0; i < 3; i++) { arr.push(i); }