starter
starter

Reputation: 3

Data structure in solidity

Can we have a data structure in solidity which is like the below

where address,address1 and address2 are address

lastused is a date

limit is amount in wei

comment is a string

allowedTo is a array of addresses

users[address][lastused]
users[address][limit]
users[address][comment]
users[address][allowedTo][]

users[address1][lastused]
users[address1][limit]
users[address1][comment]
users[address1][allowedTo][]

users[address2][lastused]
users[address2][limit]
users[address2][comment]
users[address2][allowedTo][]

Upvotes: 0

Views: 283

Answers (1)

Petr Hejda
Petr Hejda

Reputation: 43581

You can build this data structure with a combination of a custom struct and a mapping.

pragma solidity ^0.8;

contract MyContract {
    struct Info {
        uint64 lastused;
        uint256 limit;
        string comment;
        address[] allowedTo;
    }

    mapping (address => Info) public users;

    function setUser(address user, uint64 lastused, uint256 limit, string calldata comment, address[] calldata allowedTo) external {
        users[user] = Info(lastused, limit, comment, allowedTo);
    }
}

Note that Remix IDE is not able to display a returned array inside a struct - even though it's stored in the emulator or live blockchain, and retrievable by other functions and contracts. As a workaround, you can implement another function that returns just the allowedTo array.

function getAllowedTo(address user) external view returns (address[] memory) {
    return users[user].allowedTo;
}

Returned data screenshot

Upvotes: 1

Related Questions