Blockchain 仅按唯一键以稳定方式排列

Blockchain 仅按唯一键以稳定方式排列,blockchain,ethereum,solidity,Blockchain,Ethereum,Solidity,我希望构建一个简单的智能合约,能够创建资产并向其添加具有不同角色的用户。每个用户在分配每个资产时只能有一个角色 实体代码: contract AccessManagement { struct Authorization { string role; bool active; } struct Asset { address owner; address[] authorizationList; mapping(address => Author

我希望构建一个简单的智能合约,能够创建资产并向其添加具有不同角色的用户。每个用户在分配每个资产时只能有一个角色

实体代码:

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”是否为 等于管理员

    • 我看不到您在任何地方使用授权列表。你可以移除它。要确保始终只有一个授权密钥,可以使用现有映射。现有条目将被覆盖。 当您想知道密钥是否存在时,请检查
      活动
      是否为
      ,因为对于所有不存在的密钥,默认情况下都是
      。 您是否需要在某个点迭代所有地址

      为了检查角色是否等于Admin,我将为角色创建一个函数,并与之进行比较。大概是这样的:

      // Enum
      enum Roles { User, Admin };
      
      // Struct
      struct Authorization {
          Roles role;
          bool active;
      }
      
      // Checking
      if (assetStructs[assetKey].authorizationStructs[authorizationKey].role == Roles.Admin) {
          // something here
      }