Reputation: 75
Hello Everything is fine?
I'm now starting to study Solidity, I'm making a centralized game, and after some successful missions, I want to give the user the option of "Claim tokens", where I would transfer from the game wallet to him, and the amount is the backend that define, how would I go about implementing this? (My question is how to create a function in the contract where the amount is authorized by the backend somehow)
Upvotes: 0
Views: 1156
Reputation: 75
After a lot of searching I found the answer in Solidity's documentation, what I wanted is item 3.3.4 (Micropayment channel) of the documentation (readthedocs.org/projects/solidity/downloads/pdf/v0.5.12), there it explains how to authorize a person to withdraw from the my wallet with signatures and hash, without me needing to call even a method of the contract
Upvotes: 1
Reputation: 43571
You can create a function executable by the user (so that they pay the gas fees) that makes use of the ERC-20 transfer()
function (assuming your tokens are going to be ERC-20).
In this example, anytime the user executes the claimToken()
function, they are going to receive claimAmount
of tokens from the MyGame
contract address.
For the authorization, I used the Ownable pattern, where only an authorized address can execute the function (in this case setClaimAmount()
).
pragma solidity ^0.8;
interface ITokenContract {
function transfer(address _receiver, uint256 _amount) external returns (bool);
}
contract MyGame {
ITokenContract tokenContract = ITokenContract(address(0x123));
uint256 public claimAmount;
address public owner;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function claimTokens() external {
// send `claimAmount` of tokens from this contract address
// to the user executing the `claimTokens()` function
bool success = tokenContract.transfer(msg.sender, claimAmount);
require(success);
}
function setClaimAmount(uint256 _claimAmount) external onlyOwner {
claimAmount = _claimAmount;
}
}
Also, you'll might want to implement some validation to the claimTokens()
function, so that they don't perform the transfer more often than you'd like to.
Upvotes: 1