solidity – Is Gas Fee Refunded if Transaction Fails?

dapp-developmentethereum-wallet-dappsolidity

I'm confusing the rule of paying gas fee when caller makes a transaction.

The gas fee is needed when the transaction is made and I know that the require() is the guard function that returns all the gas fee to the caller.

Is the gas fee paid after all operations in the function in the smart contract?

Then, if the require() function is placed at the start of the function and the codes aren't operated at all, does that mean no gas fee is needed?

And what if the value in that require() statement is false condition and the transaction therefore fails?

Is the gas fee 100% refunded to the caller or does the caller have to pay a remaining gas fee after some operations in the function worked?

Can the caller be refunded all gas?

function burn(uint256 _value) public returns (bool success) {
    require(balances[msg.sender] >= _value);
    balances[msg.sender] = balances[msg.sender].sub(_value);
    totalSupply = totalSupply.sub(_value);
    Burn(msg.sender, _value);
    return true;
}

If the gas fee has to be paid after the code has been executed, what happens if caller(msg.sender) can not pay the gas fee because caller's account has no balance after the require () conditional pass?

I doubt that I know right.

Best Answer

The gas has to be supplied with the signed transaction. The contract function cannot be called unless gas is supplied. There is no way to overdraw the account. It's like the fuel in your car. You need some to get started, and if there is enough, you will make it to your destination. If there is not enough, everything stops.

Source code is compiled into assembly code and any time something is happening, OPCODES are being used. Gas is charged for the OPCODES, as it's used, so even if the first line is a require() and it's false, it still took a lot of OPCODES to unpack the transaction data and evaluate the require() - so some gas got burned.

If gas is returned to the signer, it's the remaining gas. This is like filling your tank, then aborting your trip. You maybe burned some while the engine was running but you still have most of it.

If a lot of processing unfolds before the abortive operation that reverts everything, it's possible most of the gas was used up.

Hope it helps.

Related Topic