[Ethereum] How does a Smart Contract know the gas/fees needed to execute a transaction

consensusgasout-of-gassolidity

I installed recently Solidity for Visual Studio and they have this Smart Contract sample there:

contract Payout {
address Victor;
address Jim;
address Kieren;

mapping (address => uint) ownershipDistribution; 

function Setup() {
  Victor = 0xaabb;
  Jim    = 0xccdd;
  Kieren = 0xeeff;

  ownershipDistribution[Victor] = 35;
  ownershipDistribution[Jim]  = 35;
  ownershipDistribution[Kieren] = 30;
}

function Dividend() {
  uint bal= this.balance;
  Victor.send(bal * ownershipDistribution[Victor] / 100); 
  Jim.send(bal * ownershipDistribution[Jim] / 100);
  Kieren.send(bal * ownershipDistribution[Kieren] / 100);
}
}

Basically it is supposed to send the ethers it receives to 3 addresses.

But I believe the code as it is won't work, as the last transaction won't have enough gas, right? Only the first 2 would execute.

Imagine there's 10 ETH in the contract, 3.5 Eth + fees / gas will be sent to address A, 3.5 Eth + fees / gas will be sent to address B, now we dont have the remaining needed 3 Eth for the third address…

So how can the Smart Contract know in the advance the gas/fees needed for the transactions?

Best Answer

Basically, miners and contracts do not know in advance the gas/fees needed for a transaction: they have to run the code in the transaction to find out. This is why the gas specified in a transaction, is the maximum amount that the transaction is willing to consume.


To answer the intended question, fees are paid from the balance of the sender account (the account that calls Dividend), which is different from the balance of the Payout contract which is divided between Victor et al.

Related Topic