I have designed a lottery contract which allows users to purchase tickets from a ticket pool of a given size. Once all the tickets have been allocated, the lottery is carried out and the winner obtains the funds. The issue is that my code triggers the lottery when the final user purchases the tickets, therefore the gas used by the final purchase is 30% higher than the gas used by all other purchases, due to the additional code being executed. For the purpose of fairness, is there a way I could optimise this so that all users pay the same amount of gas. I was thinking of periodically checking if all the tickets have been issued and if so, carrying out the lottery. I am not sure how to do this though.


There are a few options really.

  1. Don't calculate the winner in the last ticket's tx, just have a node monitoring the blockchain and when it sees the last ticket is sold, create a tx. Alternatively, just let the "calculateWinner" function be an open function that anyone can create a tx to call.

  2. Do calculate the winner in the last ticket's tx, but refund the extra gas that the user spent. Track msg.gas (the remaining gas) just before starting the win calculation, then subtract msg.gas from that at the end of the calculation. Do gasSpentToCalculateWinner*tx.gasprice and send this amount from the contract to tx.origin. You may want to set a max gasprice, e.g. if they send 50 gwei gas price, you say "ehhh...you didn't need to pay so much, so we're just gonna pretend you did a 5 gwei gas price".

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.