Untitled

 avatar
unknown
plain_text
a year ago
1.7 kB
6
Indexable
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/access/Ownable.sol";

contract AddressBook is Ownable(msg.sender) {

    struct Contact {
        uint id;
        string firstName;
        string lastName;
        uint[] phoneNumbers;
    }

    mapping(uint => Contact) public contacts; // Storage for contacts
    uint public nextId; // Counter for assigning unique IDs

    // Add a new contact
    function addContact(string memory _firstName, string memory _lastName, uint[] memory _phoneNumbers) public onlyOwner {
        contacts[nextId] = Contact(nextId, _firstName, _lastName, _phoneNumbers);
        nextId++;
    }

    // Delete a contact by ID
    function deleteContact(uint _id) public onlyOwner {
        require(contacts[_id].id > 0, "ContactNotFound");
        delete contacts[_id];
    }

    // Get contact details by ID
    function getContact(uint _id) public view returns (Contact memory) {
        require(contacts[_id].id > 0, "ContactNotFound");
        return contacts[_id];
    }

    // Get all non-deleted contacts
    function getAllContacts() public view returns (Contact[] memory) {
        Contact[] memory allContacts = new Contact[](nextId);
        uint counter = 0;
        for (uint i = 0; i < nextId; i++) {
            if (contacts[i].id > 0) { // Check if contact exists and not deleted
                allContacts[counter] = contacts[i];
                counter++;
            }
        }
        Contact[] memory activeContacts = new Contact[](counter);
        for (uint i = 0; i < counter; i++) {
            activeContacts[i] = allContacts[i];
        }
        return activeContacts;
    }
Editor is loading...
Leave a Comment