仅将唯一键按入Solidity中的数组

时间:2018-09-02 12:34:06

标签: blockchain ethereum solidity

我想构建一个简单的智能合约,该合约可以创建资产并将具有不同角色的用户添加到其中。每个用户每次分配资产时只能拥有一个角色。

代码牢固:

contract AccessManagement {

struct Authorization {
    string role;
    bool active;
}

struct Asset {
    address owner;
    address[] authorizationList;
    mapping(address => Authorization) authorizationStructs;
    bool initialized;    
}

mapping(string => Asset) assetStructs;
string[] assetList;

function newAsset(string assetKey) public returns(bool success) {
    // Check for duplicates
    assetStructs[assetKey].owner = msg.sender;
    assetStructs[assetKey].initialized = true;
    assetList.push(assetKey);
    return true;
} 

function addAuthorization(string assetKey, address authorizationKey, string authorizationRole) public returns(bool success) {
    // ??? - Require Role "Admin"
    // ??? - Push only if "authorizationKey" is unique. Otherwise change the values.
    assetStructs[assetKey].authorizationList.push(authorizationKey);
    assetStructs[assetKey].authorizationStructs[authorizationKey].role = authorizationRole;
    assetStructs[assetKey].authorizationStructs[authorizationKey].active = true;
    return true;
}
function getAssetAuthorization(string assetKey, address authorizationKey) public constant returns(string authorizationRole) {
    return(assetStructs[assetKey].authorizationStructs[authorizationKey].role);
}
}

我对此的疑问:

  • 如何确保“ authorizationKey”被推送到authorizationList [](如果唯一)?如果不是唯一的,则仅应更改值。
  • 如何检查“ assetStructs [assetKey] .authorizationStructs [msg.sender] .role”是否为 等于管理员?

1 个答案:

答案 0 :(得分:0)

我看不到您在任何地方使用授权列表。您可以删除它。为确保始终只有一个授权密钥,可以使用现有的地图。现有条目将被覆盖。 如果您想知道密钥是否存在,请检查active是否为true,因为对于所有不存在的密钥,默认情况下它将为false。 您是否需要在某个时刻迭代所有地址?

要检查角色是否等于Admin,我将为角色创建Enum并与之进行比较。像这样:

// Enum
enum Roles { User, Admin };

// Struct
struct Authorization {
    Roles role;
    bool active;
}

// Checking
if (assetStructs[assetKey].authorizationStructs[authorizationKey].role == Roles.Admin) {
    // something here
}