0

I'm pretty sure there're similar questions here, but I just couldn't find them with the correct keywords.

I found the following code in the Uniswap V2 core contracts, and I'm not sure why both functions couldn't just have been combined together under approve(). Is it for security reasons? If it is, how does it prevent attackers from exploiting its vulnerability?

function approve(address spender, uint value) external returns (bool) {
    _approve(msg.sender, spender, value); // executes the function below
    return true;
}

function _approve(address owner, address spender, uint value) private {
    allowance[owner][spender] = value;
    emit Approval(owner, spender, value);
}

1 Answer 1

1

It's more like a design preference. One of the most important principles in CS is DRY (Don't Repeat Yourself). One of the goals from that is to have less duplicate lines as possible, and thus less chance of a bug slipping into the written code. In your example above, you could possible have more than one implementation for approve with different signatures and variations.

E.g.,

function approve(address spender, uint value) external returns (bool) {
...
}
function approve(address owner, address spender, uint value) external returns (bool) {
...
}
function approveInf(address owner, address spender) external returns (bool) {
...
}

They would all call _approve(...) internally, but with different params for each implementation. And thus by keeping the bulk of the logic in _approve, we minimize the chances of having a bug, while also making it so much easier to change the implementation if needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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