How to get transaction cost in smart contract - Solidity, Ethereum
Asked Answered
M

1

5

How would I get the transaction cost inside of my contract? Would it just be: tx.gasprice ? And will this always be a value in gwei or will it be wei ?

Misguide answered 13/1, 2018 at 22:54 Comment(0)
E
7

The cost of a transaction isn't really known until execution completes. In an extreme example, perhaps your function which is computing this is being called by another function, and after you return, that function throws, consuming all remaining gas. There's no way for you to know in advance that this will happen.

To calculate the cost of the transaction, you'd need two pieces of information:

  1. The gas price.
  2. How much gas will be consumed.

If you knew both, you could multiple them together and get the total cost. tx.gasprice tells you (1), but as explained above, you can't really know (2). The best you can do is probably to use msg.gas at the top and bottom of a function to tell you roughly how much gas that function consumes.

Etsukoetta answered 13/1, 2018 at 23:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.