Search code examples
ethereumblockchainsoliditysmartcontracts

What is the best way to assign an ID to a deposit?


What would be the best way to get an id for the releaseDeposit(id) function? I know there are a few options, such as using counters or mapping, however, is there one that would be the preferred way, and how would it be implemented?

Any help would be greatly appreciated.

The code in question:

pragma solidity ^0.8.4;

contract DepositsWithIds {
    address owner;

    struct Deposit {
        uint256 depositAmount;
        address buyer;
        address seller;}

    constructor() payable {
    owner = msg.sender;}

    Deposit[] public activeDeposits;

    function deposit(address seller) public payable {

        Deposit memory newDeposit = Deposit(

        msg.value,
        msg.sender,
        seller);

    activeDeposits.push(newDeposit);

    function releaseDeposit(uint256 id) public {

        require (msg.sender == activeDeposits[id].buyer,
        "Only maker of the deposit can release deposit.");

        payable(activeDeposits[id].seller).transfer(activeDeposits[id].depositAmount);}
}

Solution

  • Its better to use mapping instead of arrays, thus i deleted array and make everything working via mapping. You can test it in remix and make sure its working like you need.

    contract Escrow {
    
    address owner;
    uint public _counter; 
    
    struct Deposit {
        uint256 depositAmount;
        address buyer;
        address seller;
    }
    
    constructor() payable {
    owner = msg.sender;
    }
    
    mapping(uint => Deposit) public ids; 
    
    event DepositMade(address depositor, uint depositAmount);
    
    function deposit(address _seller) public payable {
    
        require(msg.value > 0, "error"); 
    
        Deposit storage _deposit = ids[_counter]; 
    
        _deposit.depositAmount = msg.value; 
    
        _deposit.buyer = msg.sender;
        
        _deposit.seller = _seller; 
    
        _counter++; 
    
        emit DepositMade(msg.sender, msg.value);
    }
    
    function releaseDeposit(uint256 id) public {
    
        require (msg.sender == ids[id].buyer, "Only maker of the deposit can release deposit.");
    
        payable(ids[id].seller).transfer(ids[id].depositAmount);
    }
    
    }