I have a game where, the more time users spend playing, interacting with the environment, etc they earn a number of tokens. As this is happening in real-time, this is currently just an incremented number in a database. I want to allow players to transfer out their tokens into their wallet and I'm wondering which is the most correct way to do this. So far, I see 2 options, both have limitations...
API initiated
- User clicks on transfer
- Transfer request sent to API
- API decrements the token amount in the database, creates a transaction for the transfer of X tokens, signs it and serializes it
- Serialized transaction is sent to the client
- Client signs the transaction and the transfer happens.
The problem I see here is, say the client doesn't sign the tx, there's a network problem, or any other reason for the tx to fail; Then the tokens have been decremented from the database and the tx didn't happen so the user looses out.
Client initiated
- User clicks on transfer
- Client creates a transaction for the transfer of X tokens, signs it and serializes it
- Serialized transaction with client signature is sent to the API
- API deserializes the transaction, validates the transaction is correct (valid number of tokens compared to the quantity in the database) and signs the transaction
- API decrements the token in the database, executes the transaction and monitors the response
- If the response is not successful then the API re-increments the tokens in the database.
Problem here is its a bit long winded, the latest block hash can expire and thus transactions are not reliable.
Can anyone shed some light as to what is the best way of handling this please?