Solidity

如何檢查結構是否屬於地址?

  • August 23, 2018

我正在嘗試創建一個智能合約,允許合約的創建者添加資產屬性並將其分配到一個地址。完成後,接收地址現在可以將其發送到另一個地址,前提是它是目前所有者。

我試圖通過將地址映射到作為正在創建的資產計數的assetId 來分配結構“資產”。

我不確定它是否是正確的方法。對於如何根據 AssetId 檢查目前所有者也有點困惑(因為在 c#/LINQ 中沒有 where 子句。)以及將資產從目前所有者分配給下一個所有者的正確方法是什麼。

pragma solidity ^0.4.2;

contract AssetDistribution { 
address public issuer;
uint public assetCount;

event AllocationDetails(address from, address to, string description);

function AssetDistribution() {
   issuer = msg.sender;
   //ContractorDetails(issuer);
}

struct Asset {
   uint assetId;
   address currentOwner;
   string description;
   uint cost;
}
mapping (address=> mapping(uint=>Asset)) private owners;
//mapping(address=> mapping(uint=>bool)) private ownerPropertyCheck;

//creates an asset and allocates it to an address at the same time. 

function setCreateAsset(address newOwner, string description, uint cost) 
   returns(string) {
   if (msg.sender == issuer) {
   assetCount++;
   Asset memory myAsset = Asset(assetCount,newOwner,description,cost);      
   owners[newOwner][assetCount] = myAsset;
   AllocationDetails(msg.sender,newOwner,description);
   return "created By: government";
   //return strConcat("created By: ","test");
   } else { 
       return "This is not the creator";
   }
}

function getassetCount() constant returns(uint) {
   return assetCount;
}

function getOwner(uint id) returns(address) {
  //return
}

}

在 C# 中,我主要會創建一個具有資產屬性的類,並且會在傳輸完成時更改 currentOwner。在這裡,我無法以類似的方式接近。我什至應該為此使用 struct 嗎?

編輯一個 - 我的解決方案

將assetId映射到ownerAddress並將地址+assetId映射到結構解決了我遇到的困境

mapping(uint=>address) assetAddress;
mapping(address=>mapping(uint=>Asset)) ownerAssets ;

返回資產的目前所有者地址

function getCurrentOwner(uint assetId) constant public returns (address) {
   return assetAddress[assetId];
}

檢查assetId(結構的Id)是否屬於地址

function isOwnerOfAsset(address userId, uint assetId) private constant returns(bool) {
   return assetAddress[assetId] == userId? true:false;
}

PS 我主要用 C#/Backend 編寫程式碼,跳到solidity 讓我有點困惑。如果您知道任何可以參考的好資源,請隨時分享。

由於映射是不可迭代的,我建議您保留一個映射來辨識資產的所有者,如下所示,

mapping (uint => address) private assetOwners;

在內部創建資產時setCreateAsset,使用assetId的鍵設置帳號的值,

assetOwners[assetCount] = newOwner;

獲取給定assetId的資產所有者的accountNo,

address assetOwner = assetOwners[assetId];

要重新分配資產,您可以這樣做,

Asset newAsset = owners[currentOwner];
newAsset.currentOwner = newOwner;
owners[newOwner] = newAsset;
delete owners[currentOwner];

引用自:https://ethereum.stackexchange.com/questions/25508