Solidity

從結構中刪除值

  • April 26, 2022

我如何從結構和/或映射中刪除值。例如,我正在創建一個類似於保險庫的智能合約,我還沒有完成,但我有一個創建帳戶功能。我還想添加一個刪除帳戶功能,我想只是更改結構內的值但是有更好的方法。這是我的一些程式碼:

// Global variables
uint256 uniqueId;

// Account details storage
struct AccDetails {
   string accNickName;
   uint256 creationTimeStamp;
}
mapping(address => AccDetails) public accDetails;

mapping(address => uint256) public balanceOf;
mapping(address => uint256) addrTouniqueIdentifier;
mapping(uint256 => address) uniqueIdentifierToAddr;

// Variables set on contract deployment
constructor() {
   uniqueId = 1;
}


function createAccount(string memory _accNickName) public {
   if(accDetails[msg.sender].creationTimeStamp == 0) {
       accDetails[msg.sender] = AccDetails(_accNickName, block.timestamp);
       addrTouniqueIdentifier[msg.sender] = uniqueId;
       uniqueIdentifierToAddr[uniqueId] = msg.sender;

       emit accountCreated(msg.sender,_accNickName, block.timestamp);

       uniqueId = uniqueId.add(1);
   }else {
       revert("You already have an account created.");
   }
}

不確定這是否是最好的方法,但對我來說這有效,

function deleteAccount() public {
   require(accDetails[msg.sender].creationTimeStamp != 0, "You do not have an account.");
   if(balanceOf[msg.sender] > 0) {
       uint256 _amount = balanceOf[msg.sender];
       balanceOf[msg.sender] = 0;
       payable(msg.sender).transfer(_amount);

       emit withdrawalComplete(msg.sender, accDetails[msg.sender].accNickName, _amount, balanceOf[msg.sender].add(_amount), balanceOf[msg.sender]);
   }
   uint256 _oldUniqueIdentifier = addrTouniqueIdentifier[msg.sender];

   accDetails[msg.sender] = AccDetails("", 0);
   uniqueIdentifierToAddr[addrTouniqueIdentifier[msg.sender]] = address(0);
   addrTouniqueIdentifier[msg.sender] = 0;

   emit accountDeleted(msg.sender, _oldUniqueIdentifier, block.timestamp);
}

根據您的程式碼,deleteAccount將如下所示:

function deleteAccount(address _addr) public {
       delete accDetails[_addr];
       delete balanceOf[_addr];
       delete addrTouniqueIdentifier[_addr];
       delete uniqueIdentifierToAddr[/*balance of the deleted acc*/];
   }

您必須將已刪除帳戶的餘額轉移到另一個地址:

function send(address payable _to) public payable {
       (bool sent, bytes memory data) = _to.call{value: msg.value}("");
       require(sent, "Failed to send Ether");
   }

把所有東西放在一起:

function send(address payable _to) public payable {
       (bool sent, bytes memory data) = _to.call{value: msg.value}("");
       require(sent, "Failed to send Ether");
   }

   function deleteAccount(address _addr) public {
       send(payable(to));
       // Reset the value to the default value.
       delete accDetails[_addr];
       delete balanceOf[_addr];
       delete addrTouniqueIdentifier[_addr];
       delete uniqueIdentifierToAddr[/*balance of the deleted acc*/];
   }

還:

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