Solidity代码反馈-基本任务跟踪存储和检索



我刚刚完成了一些基本的Solidity教程,想尝试一下基本的任务跟踪器。。。它基本上允许用户创建任务,并将它们分配给用户和项目。

我最大的问题是关于映射部分。如果我想轻松地检索给定项目的所有任务或给定用户的所有任务,我的实现是否正确?有什么方法可以让我使用:

uint256 newIndex = _taskList.length;
_taskList.push(Task(project, title, description, false, dueDate, assignedUser, msg.value, msg.sender));
_userTasks[assignedUser].push(newIndex);
_projectTasks[project].push(newIndex);

可能由于比赛条件或同时呼叫而导致不良信息?感谢所有评论,谢谢!

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
contract ProjectTaskList {

struct Task {
string project;
string title;
string description;
bool isCompleted;
uint256 dueDate;
address assignedUser;
uint256 payment;
address owner;
}
Task[] public _taskList;
mapping(address => uint256[])  _userTasks;
mapping(string => uint256[] )  _projectTasks;
function getContractBalance() public view returns (uint256){
return address(this).balance;
}
function addToDo(string memory project, string memory title, string memory description, uint256 dueDate, address assignedUser) public payable {
require(bytes(project).length > 0, "Project is required");
require(bytes(title).length > 0, "Title is required");
require(bytes(description).length > 0, "Description is required");
require(dueDate > 0, "DueDate is required");
require(assignedUser != address(0), "Assigned User is required");
uint256 newIndex = _taskList.length;
_taskList.push(Task(project, title, description, false, dueDate, assignedUser, msg.value, msg.sender));
_userTasks[assignedUser].push(newIndex);
_projectTasks[project].push(newIndex);
}
function getUserTasks(address user) public view returns (uint256[] memory){
return _userTasks[user];
}
function geProjectTasks(string memory projectName) public view returns (uint256[] memory){
return _projectTasks[projectName];
}
function updateTask(uint256 index, string memory project, string memory title, string memory description, uint256 dueDate, address assignedUser){
require(bytes(project).length > 0, "Project is required");
require(bytes(title).length > 0, "Title is required");
require(bytes(description).length > 0, "Description is required");
require(dueDate > 0, "DueDate is required");
require(assignedUser != address(0), "Assigned User is required");
Task foundTask = _taskList[index];
require(foundTask.owner == msg.sender, "You do not have the right to update this task");
// more code to see if the user or project has been assigned and update the Project and User array correctly
// then update the code
}

除了缺少注释之外,我认为您的代码没有什么大问题。也许一些气体优化是可行的

  1. 您可以限制projecttitle字段的大小。EVM将数据存储在256比特的块中。因此,对它们中的每一个使用128比特(最好更少(将花费更少的气体,因为EVM将在单个块中同时处理这两个问题
  2. 您已经在结构中保留了已分配的用户。为用户任务使用第二个mapping可能看起来更快、更干净,但存储操作成本高昂。用于该目的的getter函数会更便宜
  3. 与(2(相同,但具有项目任务映射
  4. 你不能有比赛条件。EVM没有并行性的概念

最新更新