-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path35_ContractFactory.sol
97 lines (83 loc) · 2.89 KB
/
35_ContractFactory.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity ^0.8.13;
// Contract that Creates other Contracts
// Contracts can be created by other contracts using the new keyword. Since 0.8.0, new keyword supports create2 feature by specifying salt options.
/**
* Contract can create another contract
*
* How it's useful?
* - pass fixed input to new contract
* - manage many contract from a single contract
*
* Example:
* - Create new contract
* - Send Ether and create new contract
*/
// When we deploy same contract many times with diffrent input params
// Want to manage contarcts deployed from same contract
// https://www.youtube.com/watch?v=CyzsUA12ju4&ab_channel=SmartContractProgrammer
// https://www.youtube.com/watch?v=883-koWrsO4&ab_channel=SmartContractProgrammer
// Creates Car
contract CarFactory {
// Keep all cars in Dynamic Array
Car[] public cars;
function createCar(address _owner, string calldata _model) public payable {
Car car;
if (msg.value != 0){
car = (new Car){value: msg.value}(_model, _owner);
// Creating Car and Sending ETH to that newly creating Car?
} else {
car = new Car(_model, _owner);
}
// Object Instantiating
// As we do in JAVA
// new returns newly created object refrence var here it's address
// Adding in dynamic array
cars.push(car);
}
// contuctor is payable but we can call it with 0 ETH as well
// Overloaded
function createCar(string calldata _model) public payable {
Car car;
if (msg.value != 0){
car = (new Car){value: msg.value}(_model, msg.sender);
} else {
car = new Car(_model, msg.sender);
}
cars.push(car);
}
function createCar(string calldata _model, bytes32 _salt) public payable {
Car car;
if (msg.value != 0){
car = (new Car){
value: msg.value,
salt: _salt // Random 32bytes of our choise (Can also cast uint to bytes 32 to pass it as salt)
}
(
_model,
msg.sender
);
} else {
car = new Car{salt: _salt}(_model, msg.sender);
}
cars.push(car);
}
// More Details about Salt next time?
// I'll cover up in projects
// We can determine address of contract to be deployed before deploying
// get car info
function getCar(uint index) public view returns (address, string memory, uint){
Car car = cars[index];
return (car.owner(), car.model(), address(car).balance);
}
// there is getter functions for feild same as their name
}
// Boiler Plate
contract Car {
string public model;
address public owner;
constructor(string memory _model, address _owner) payable {
model = _model;
owner = _owner;
}
}