1

Let's suppose I have this struct:

struct Agent {
    uint idAgent;
    address direction;
    uint[] preferences;
}
Agent[] agents;

And there's a function:

/// @notice Registra a un nuevo agente a la subasta
/// @param _idAgent identificador del agente dentro de la subasta
/// @param _preferences preferencias del agente
function regAgent(uint[] _preferences) public{
    Agent memory newAgent = Agent(numAgents, msg.sender, _preferences);
    agents.push(newAgent);
    numAgents++;
}

When an agent tries to register twice, how can I check it? I want to check that the agent is already registered but I don't want to go through the agent array. Is that possible?

1 Answer 1

1

You can try this code :

pragma solidity ^0.8.0;

contract Agent {
  struct Agent {
    uint idAgent;
    address direction;
    uint[] preferences;
}
Agent[] agents;

uint256 public numAgents;
mapping(address=>bool) _isRegistered;


/// @notice Registra a un nuevo agente a la subasta
/// @param _preferences preferencias del agente
function regAgent(uint[] memory _preferences) public{
    require(!_isRegistered[msg.sender],"sender is already registered");
    Agent memory newAgent = Agent(numAgents, msg.sender, _preferences);
    agents.push(newAgent);
    _isRegistered[msg.sender]=true;
    numAgents++;
}

}

We do two important things :

  • agent Id unicity

The state variable numAgents starts from 0 and is incremented in the regAgent function after each new registration. It is passed as the idAgent parameter of the struct Agent, so each agent is guaranteed to have a unique identifier.

  • agent direction address unicity

For each agent registration, we stored the sender address in the mapping _isRegistered with true as the value. The condition require(!_isRegistered[msg.sender],"sender is already registered"); checks if the sender address has already been registered in the mapping, and reverts the transaction if it's the case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.