so I got a code which I suspect is prone to frontrunning at least theoretically.

function deposit(uint _amount) public {
        uint256 _pool = balance();
        uint256 _before = token.balanceOf(address(this));
        token.safeTransferFrom(msg.sender, address(this), _amount);
        uint256 _after = token.balanceOf(address(this));
        _amount = _after.sub(_before); // Additional check for deflationary tokens
        uint256 shares = 0;
        if (totalSupply() == 0) {
            shares = _amount;
        } else {
            shares = (_amount.mul(totalSupply())).div(_pool);
        _mint(msg.sender, shares);


Here is a test case which I'm considering:

Consider there are two users, User A and B User A called deposit() with amount as 100, at that time, the contract balance was let's say 100. Now, variable _before will be initialised with 100. But the transaction for the transfer of token from user A to contract address is still pending. Meanwhile User B called deposit() with amount as 400, as contract balance is still not updated. The contract balance is still 100 and so as _before variable for B will also be 100, user B deposits 400, a new balance that is _after variable will be 400 + 100 that is 500. Now the _amount variable will be _after - _before that 500 -100 that is 400.

Now, the pending transaction of User A is succeeded, it deposits its 100 amount. But now the _after variable calculated will be the new balance(as user B has already deposited prior to A's pending transaction, for eg, by giving a higher gas price) Now, _amount calculated for A will be _after - before that is 600 - 100 that is 500. and now User A’s shares will be affected even though User A has deposited his 100 tokens legitimately

Is it possible?

1 Answer 1


No, what you are describing is not possible with that function.

Transactions are always executed entirely before another transaction starts to be executed (transactions are executed synchronously). That means that the deposit() function would need to be done up to the end, including the transfer of tokens, before another deposit() transaction would be initiated.

  • Thanks for the help @Undead8. Can you help with some supporting references to learn about transaction executions? Jul 4, 2021 at 16:41

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.