in

learning solidity – architectural question to reduce gas usage

Hi, I’m just starting to learn solidity. As a practice project, I’m taking a basic game, say tic tac toe, and adding an option to bet and win (or lose) ETH. The process looks like this:

1) On the front end, call a startGame function in which 1ETH is sent to the smart contract and a log is created (gameID, address, amount, timestamp).

2) Smart contract receives 1 ETH and logs the game. Emit an OK-to-start event.

3) Once the event is heard, load the game in the front end

4) When the game is complete, if the user achieves a certain score, the user should be paid 2 ETH.

Step 4 is where I’m stuck. What is the best way to implement this? I could add a function in which the user can retrieve his winnings at the end of a winning game, but that requires another transaction and a gas fee. Is there a way to do this part without gas?

What do you think?

10 Points
Upvote Downvote

Leave a Reply

Your email address will not be published. Required fields are marked *

GIPHY App Key not set. Please check settings

2 Comments

  1. The best way to solve this problem is to let users initiate a withdrawal which was pre-approved by you. The ERC-20 token standard has methods to implement this functionality (just look for `approve`, `transfer` and `transferFrom`).

    If you want to use ETH you can use WETH (Wrapped ETH) to get a 1:1 ETH representation as an ERC-20.

    That way the burden of paying gas etc. is on the users and you don’t need to e.g. loop through an array to distribute the winnings which can be super expensive (if not infeasible).

    Since you’re new to Solidity / Smart Contract development you might want to check out the CryptoDevHub Wiki’s “Getting Started” guide which has a step-by-step curriculum you can follow to get from complete beginner to proficient Smart Contract developer: https://cryptodevhub.io/wiki/blockchain-development-tutorial

    In fact, the CryptoZombies course in the “Getting Started” guide covers exactly the situation you described above (if I remember correctly).

    The Wiki also has a list with useful Tutorials and Tools you can browse through:

    https://cryptodevhub.io/wiki/ethereum-virtual-machine-tutorials
    https://cryptodevhub.io/wiki/ethereum-virtual-machine-tools

    And there’s also the Discord you can join to meet fellow devs and ask further questions: https://cryptodevhub.io/discord

  2. Not a solidity expert but—a transfer is a transaction, yes? If so, unclear that you can avoid the second transaction unless you have the user prepay an estimated amount, and then roll the balance (along with winnings when relevant) back to the player at the end of the game session.

How (Not) To React When Your Cryptocurrency Is Stolen | by CipherBlade

What Are Your Moves Tomorrow, July 07, 2021