Search code examples
ethereumsoliditysmartcontracts

Saving Addresses


I have project addresses and I want to create more project with a function. So I want to save these addresses at somewhere. Then, these project addresses should have more than one key. Also I want to reach these keys with project addresses.

Example

For example, I have Project 1 address. Project 1 has apple's address and Orange's address as keys When I ask "Does project 1 address has apple's address?" It should return True The important part is I want to create project with a function then reach them as I told. How can I do that?


Solution

  • You can store the addresses in a mapping, where the key is string "apple", "banana", etc.

    There's no validation if a key has been set (because of the way how mappings store data). But you can validate whether the value of the specified key is non-zero (zero is the default value).

    pragma solidity ^0.8.4;
    
    contract Project {
        mapping (string => address) addresses;
        
        constructor() {
            addresses['apple'] = address(0x123);
            addresses['orange'] = address(0x456);
        }
        
        function hasAddressOf(string memory _identifier) external view returns (bool) {
            return addresses[_identifier] != address(0);
        }
    }
    

    This contract can be deployed to "Project 1 address". Your client app then calls its hasAddressOf() function to see whether "Project 1 has an Orange address stored".


    Or even a simpler Solidity code, where you make the addresses property public.

    The client app can get the value of addresses['apple'] which returns 0x123 or addresses['mango'] which returns 0x0.

    pragma solidity ^0.8.4;
    
    contract Project {
        mapping (string => address) public addresses;
        
        constructor() {
            addresses['apple'] = address(0x123);
            addresses['orange'] = address(0x456);
        }
    }