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.


2 Answers 2


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


It is a reentrancy attack guard. If you check the source code, this modifier is used for mint and burn where you transfer funds.

This modifier adds the require statement first

 require(unlocked == 1, 'UniswapV2: LOCKED');

then it sets unlocked=0 and executes the function code with this _ placeholder. At this point, if the attacker wants to re-execute the function code before the first execution is completed, lock modifier will run, and require statement will fail because we previously set unlocked=0.

In a reentrancy attack, after funds are withdrawn, fallback function gets executed and another withdraw operation is executed inside fallback before the balance of the contract is updated. So attacker keeps withdrawing before function is completed. With this lock modifier, attacker cannot withdraw again till the function is completed.

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.