1

If 2 persons call the function deposit in my smart contract at the same time, sending 100 USDC each, and in my deposit function I use balanceOf(address(this)) to check the balance of my contract in the deposit function, Is it possible for the balance be 200? note that after checking balanceOf(address(this)) I'll transfer the amount, I'm afraid of transferring 200 USDC for one user instead of 100

2 Answers 2

1

Imagine Ethereum like a bank with one teller. Even if two people try to deposit money at the same time (like calling your deposit function), they still have to wait in line (the network) one by one.

This means:

  1. User A calls deposit (gets in line).
  2. The teller (miner) checks the account balance (initially 0).
  3. User B calls deposit (gets in line behind A).
  4. User A finishes their transaction, so the balance reflects their deposit.
  5. User B's turn comes, and the teller sees the updated balance (including A's deposit).

This ensures each user's deposit is handled correctly, and you won't accidentally transfer the wrong amount.

4
  • explain front-running then Commented May 5 at 5:44
  • Sure, Imagine a race track for transactions: When we talk about concurrency think of it like cars taking turns on the track. Each car goes one at a time, following the order they arrived. This ensures everything is processed fairly. And when we talk about front-running this is like someone sneaking onto the track before their turn. They might see a really fast car coming (a big transaction) and try to get there first (with a smaller transaction) to benefit from the situation. It's not playing by the rules! Commented May 5 at 10:16
  • 1
    I have another example extending bank situation above :) More users come to the bank and wait for their turn. User Z enters the bank, travels all the line inspecting all the operation intentions of the users in the queue, notices a trade opportunity, and offers 1000$ to the teller to skip the line. The teller finishes with the current customer, asks if anyone wants to pay more than 1000$ to skip the line before User Z. If nobody answers, he makes User Z pass, so he can execute his operation before all the other people in the line. Commented May 7 at 15:15
  • Correct @GiuseppeBertone Commented May 7 at 15:40
0

Transactions are executed serially, their execution cannot interfere with each other.

If you have two transactions T1 y T2. Any modification to a contract state made by T1 will be persisted before T2 is executed. It functions like a lock.

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.