1

consider this as an smart contract which check your eligiblity and i am creating multiple instances of the contract. require validation is done. but how can i make that minimum age value dynamic in the require statement. If user passed 30 age as minimum then in require error it should be "Minimum age should be 30 years". i dont want to hardcode that minimum age in reuqire, how can i achieve that?

contract checkMyEligibility {
    uint requiredAge;
constructor(uint _requiredAge) {
    requiredAge = _requiredAge;
}

function checkAge(uint _age) public view {
    require(_age > requiredAge, "Minimum age should be 20 years");
    /*
    // like below line.
    require(_age > requiredAge,"Minimum age should be ${requiredAge} years");
    */
} 

}

2 Answers2

2

If you want to add parameters to the error message you have to use custom errors. For a detailed explanation see this post on Solidity Blog.

Basically you can add a custom error like this:

contract checkMyEligibility {
    error Underaged(uint256 givenAge, uint256 requiredAge);
uint requiredAge;

constructor(uint _requiredAge) {
   requiredAge = _requiredAge;
}

function checkAge(uint _age) public view {
  if (_age < requiredAge){
     revert Underaged({
         givenAge: _age,
         requiredAge: requiredAge
      });
    }
}

}

Rachain
  • 71
  • 3
0

I took a look in Solidity Documentation.

It is currently not possible to use custom errors in combination with require. Please use if (!condition) revert CustomError(); instead.

You can read more about it here:

Sky
  • 2,282
  • 2
  • 7
  • 26