-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNewContract.sol
More file actions
83 lines (65 loc) · 2.28 KB
/
NewContract.sol
File metadata and controls
83 lines (65 loc) · 2.28 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
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import "@openzeppelin/contracts/access/Ownable.sol";
contract AddressBook is Ownable {
struct Contact {
uint id;
string firstName;
string lastName;
uint[] phoneNumbers;
}
Contact[] private contacts;
mapping(uint => uint) private idToIndex;
uint private nextId = 1;
error ContactNotFound(uint id);
constructor(address _initialOwner) Ownable(_initialOwner) {}
function addContact(
string calldata _firstName,
string calldata _lastName,
uint[] calldata _phoneNumbers
) external onlyOwner {
Contact memory newContact = Contact({
id: nextId,
firstName: _firstName,
lastName: _lastName,
phoneNumbers: _phoneNumbers
});
contacts.push(newContact);
idToIndex[nextId] = contacts.length - 1;
nextId++;
}
function deleteContact(uint _id) external onlyOwner {
uint index = idToIndex[_id];
// Check if contact exists (id must be > 0 and within bounds)
if (_id == 0 || index >= contacts.length || contacts[index].id != _id) {
revert ContactNotFound(_id);
}
// Move last element to deleted position
uint lastIndex = contacts.length - 1;
if (index != lastIndex) {
Contact memory lastContact = contacts[lastIndex];
contacts[index] = lastContact;
idToIndex[lastContact.id] = index;
}
// Remove last element
contacts.pop();
delete idToIndex[_id];
}
function getContact(uint _id) external view returns (Contact memory) {
uint index = idToIndex[_id];
// Check if contact exists
if (_id == 0 || index >= contacts.length || contacts[index].id != _id) {
revert ContactNotFound(_id);
}
return contacts[index];
}
function getAllContacts() external view returns (Contact[] memory) {
return contacts;
}
}
contract AddressBookFactory {
function deploy() external returns (address) {
AddressBook newAddressBook = new AddressBook(msg.sender);
return address(newAddressBook);
}
}