In UniswapV2Pair.sol(https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2Pair.sol), modifier lock() seems to be used to get lock and release lock. And it is used in almost all the external functions of UniswapV2Pair.sol.

    uint private unlocked = 1;
    modifier lock() {
        require(unlocked == 1, 'UniswapV2: LOCKED');
        unlocked = 0;
        unlocked = 1;

But I don't know why lock is needed in solidity smart contract. Is it used to execute function in sequence , just like "synchronized" in java? In my understanding, in the context of Ethereum, transactions in a block are executed one by one, which means that they are executed in sequence natively. Since they are impossible to be executed in parallel, why lock is needed?

Hopefully some expert can help me understand this. Thanks in advance.


Without knowing the intent of the person who coded this, or going through the contract in depth, it looks like a simple re-entrancy guard in the form of a mutex.

As such, it will prevent the protected functions from re-entered in the same transaction (which would presumably be bad for these functions).

More on re-entrancy, and mitigating strategies, here -> https://consensys.github.io/smart-contract-best-practices/known_attacks/

Good answer to "What is a re-entrancy attack" here: Reentrancy Attack in a Smart contract

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.