微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何存储要在智能合约中使用的数据?

如何解决如何存储要在智能合约中使用的数据?

我是区块链新手,所以我需要您的建议。我想编写一个智能合约,根据到期日期(提前一周)向供应商发送项目通知。那么存储商品数据的合适方法是什么?

解决方法

简短回答:您可以将数据存储在合同中,但无法通知他们。

智能合约的工作方式与 APIRest 非常相似,除非外部调用触发它们,否则它们不会执行任何操作。

你不能创建一个函数,一旦调用它就会触发一个永远运行的计时器,因为gas消耗会阻止“无限”逻辑形式的发生。

智能合约并不意味着用作应用程序的后端,当调用其函数或访问其属性时,它们会将数据和逻辑提供给应用程序,但它们不会自动执行任何操作,你需要一些外部的东西来触发它的逻辑。

您必须将数据存储在智能合约上,并使用其他方式通知用户,或者让前端(您的客户端应用程序)在每个用户登录时获取他们的所有项目,并且然后将到期日期与当前日期进行比较并通知他们。

为了存储数据,我建议使用结构数组的映射(结构是具有其属性的项目),例如:

contract ItemManager {
// We map user addresses to Item arrays,this way,each address has an array of Items assigned to them.
mapping (address => Item[]) public items;

// The structs of the Item.
struct Item {
  string name;
  string description;
  uint256 expiryDate;
}

...

// Emits an event when a new item is added,you can use this to update remote item lists.
event itemAdded(address user,string name,string description,uint256 exipryDate);

...

// Gets the items for the used who called the function
function getItems() public view returns (Item [] memory){
   return items[msg.sender];
}


// Adds an item to the user's Item list who called the function.
function addItem(string memory name,string memory description,uint256 memory expiryDate) public {

    // require the name to not be empty.
    require(bytes(name).length > 0,"name is empty!");

    // require the description to not be empty.
    require(bytes(description).length > 0,"description is empty!");

    // require the expiryDate to not be empty.
    require(bytes(expiryDate).length > 0,"expiryDate is empty!");

    // adds the item to the storage.
    Item newItem = Item(name,description,expiryDate);
    items[msg.sender].push(newItem);

    // emits item added event.
    emit itemAdded(msg.sender,newItem.name,newItem.description,newItem.expiryDate);
}

...

}

然后在您的前端,您可以检查合同属性(使用 web3 制作的示例):

...
const userItems = await itemManager.methods.items().call();
...

注意:您可以使用 uint256 类型存储时间戳(纪元),但如果您想将它们存储为字符串,因为它更容易解析,那么您可以随意这样做。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。