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



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

简单回答:您可以将数据存储在合同中,但不可能通知它们。

智能合约的工作原理很像APIRests,除非外部调用触发它们,否则它们不会做任何事情。

你不能让一个函数一旦被调用就会触发一个永远运行的计时器,因为气体消耗会阻止";"无限";逻辑形式正在发生。

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

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

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

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类型存储时间戳(epoch(,但如果您想将它们存储为字符串,因为它更容易解析,那么您可以自由地这样做。

最新更新