i'm studyng ethereum and i have a question, how can ethereum, during the transaction, verify that my balance is enough for execute the transaction? It is the current smart contract that doeas this check, of is the EVM, that in some way, retrieve data from the world state tree? Thank you in adavance!
ETH balance:
The blockchain stores state changes, which are used to calculate the current ETH balance of an address.
You can theoretically create and broadcast a transaction that spends more than your current balance. But the tx is going to revert.
Validation whether the sender has enough balance to cover the gas fee and tx value
, is performed on the EVM level. You can find its implementation for example in the go-ethereum
source code. It first checks if the sender can buy enough gas (preCheck() calls buyGas()
that errors if the balance is not sufficient), and then checks if the sender has enough balance to cover the value
(
canTransfer()
reference and definition).
Token balance:
The token balance is stored in the token contract storage. (In some cases, the balances might be stored in another contract, but it's still some contract's storage.)
Most token contracts' logic contains validation whether the sender has enough token balance to send the tokens. If they don't have enough token balance, the contract creates an invalid EVM opcode, that results in reverting the transaction (so the token balance is not changed). Or sometimes the contract just lets the Ethereum transaction pass, but it doesn't update any token balance.
Example code of the validation on OpenZeppelin's implementation of ERC-20 token: GitHub link (the require()
statement in the _transfer()
function)
Only few token contracts are faulty and don't have this validation. But a faulty implementation might allow the sender to send more tokens than they currently own.