1

Example:

uint public createPostCost = 0.0003 ether;

function createPost(bytes32 _post) 
    public payable {
        require(msg.value >= createPostCost);
        Post memory newPost;
        newPost.post = _post;
    }

Within a discussion forum dapp, the current implementation charges users a set fee per post created. I would like the charge to be dynamic, say 10% of the gas cost of the transaction. Is this possible to implement in the contract? Or is this something for front-end web3 to handle?

3

Yes, you can let the charge be a function of the gas of the transaction. You would do something like this:

uint256 charge = gasleft() / 10;

This is sensitive and you should know that gasleft() returns the amount of gas available at that point in the execution. Therefore, if you call gasleft() at the beginning of a function, the number will be higher than at the end of the function.

Additionally, someone may send a lot of unnecessary gas, so they could end up paying a lot.

My opinion is that it is best to handle this on the front-end.

Edit

If you are trying to take into account the gasPrice, you can use tx.gasprice. See here for more information.

  • 3
    Psst, msg.gas has been removed and replaced by gasleft as per solidity.readthedocs.io/en/latest/… – Lauri Peltonen Apr 22 at 20:06
  • Ahh yes. Thank you. – shane Apr 22 at 20:06
  • Ah that makes sense. If I made a require to check the msg.value >= 10% of tx.gasprice, would that work? Would there be discrepancies between generating the web3 function call price + value and the contract value? – Jaren L Apr 22 at 22:55
  • I have tried to implement this and can't get it to work. Would you perhaps know of an implementation? – Jaren L Aug 5 at 23:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.