使用计数器作为ID -在智能合约中是一个好主意吗?



我编写了以下代码来跟踪智能合约中的存款。我需要能够在未来的功能中引用个人存款。

pragma solidity ^0.8.4;
contract DepositsWithIds {
address owner;
struct Deposit {
uint256 depositAmount;
address depositor;
uint256 counter;
}
constructor() payable {
owner = msg.sender;
}

Deposit[] public activeDeposits;
event DepositMade(address, uint256, uint256);
function deposit() public payable returns (uint256 counter) {
return ++counter;
Deposit memory newDeposit = Deposit(
msg.value,
msg.sender,
counter
);
activeDeposits.push(newDeposit);
emit DepositMade(msg.sender, msg.value, counter);
}
}

使用柜台作为唯一的存款ID是一个好主意吗?在编写下一个函数时,如何将activeDeposits.counter连接到activeDeposits.depositor?

uint public counter;
mapping(uint = > Deposit) public ids; 
function deposit() public payable {
Deposit storage _deposit = ids[_counter]; 
_deposit.depositAmount = msg.value; 
_deposit.depositor = msg.sender;

activeDeposits.push(_deposit);
_counter++; 
emit DepositMade(msg.sender, msg.value);
}

可以将counter从struct中取出:

struct Deposit {
uint256 depositAmount;
address depositor;
}

您将计数器设置为顶级状态变量

uint256 counter;

你可以有一个映射,将counterId映射到Deposit

mapping(uint156=>Deposti) public idToDeposit;

然后通过id获取存款

function getDepositByID(uint id)public view {
idToDeposit[id]
}
  • 你可能会遇到openzeppelin Counters。如何使用计数器

安装npm i @openzeppelin/contracts,导入' ' Counters

import "../node_modules/@openzeppelin/contracts/utils/Counters.sol";

合同中:

contract Test{
// this means all Counters.Counter types in your contract loaded with the methods of Counters library
using Counters for Counters.Counter;
Counters.Counter private depositIds;
}