-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChild.sol
More file actions
94 lines (85 loc) · 2.92 KB
/
Child.sol
File metadata and controls
94 lines (85 loc) · 2.92 KB
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
// SPDX-License-Identifier: Unidentified
pragma solidity 0.8.7;
contract Child {
uint immutable public childNumber;
constructor(uint _x){
childNumber = _x;
}
}
contract ChildFactory{
Child[] public children;
mapping(uint => address) public ownerOfChild;
event childCreated(
uint _timeStamp,
uint _childNumber,
address _childAddress,
address _owner
);
event childAdopted(
uint _timeStamp,
uint _childNumber,
address _childAddress,
address _owner
);
event childAbandoned(
uint _timeStamp,
uint _childNumber,
address _childAddress,
address _owner
);
event childTransfered(
uint _timeStamp,
uint _childNumber,
address _childAddress,
address _oldOwner,
address _newOwner
);
// Fill index[0] of children
constructor(){
Child child = new Child(0);
children.push(child);
}
// Number of children were created
function getChildNumber()private view returns(uint) {
return children.length;
}
// @param justCreate: ignore the childrens with no owner and just create a new children
// @param justCreate: if false, it will adopt 1 of the oldest children with no owner
// or create new children if all childrens were have owner
function createOrAdoptChild(bool justCreate)external{
if(justCreate){
uint number = getChildNumber();
Child child = new Child(number);
children.push(child);
ownerOfChild[number] = msg.sender;
emit childCreated(block.timestamp, number, address(child), msg.sender);
}else{
uint length = children.length;
for(uint i = 1; i <= length;){
if(i == length){
uint number = getChildNumber();
Child child = new Child(number);
children.push(child);
ownerOfChild[number] = msg.sender;
emit childCreated(block.timestamp, number, address(child), msg.sender);
}
else if(ownerOfChild[i] == address(0)){
ownerOfChild[i] = msg.sender;
emit childAdopted(block.timestamp, i, address(children[i]), msg.sender);
return;
}
unchecked{++i;}
}
}
}
function abandonChild(uint index)external{
require(ownerOfChild[index] == msg.sender, 'Not your child');
delete ownerOfChild[index];
emit childAbandoned(block.timestamp, index, address(children[index]), msg.sender);
}
function transferChild(address to, uint index)external{
require(ownerOfChild[index] == msg.sender, 'Not your child');
ownerOfChild[index] = to;
emit childTransfered(block.timestamp, index, address(children[index]), msg.sender, to);
}
}