您好,感谢您阅读我的问题。
我正在尝试创建一个质押农场来学习 Solidity,我意识到这个农场允许用户质押他们的代币,然后我需要运行代码来发放他们的奖励,但我还需要自己支付 gas 费。
我想要做的是添加一个 Harvest 按钮,这样我就可以将奖励作为津贴发放,而无需将其发送给用户,这样他们就可以随时通过支付 gas 费来收获它们。任何提示表示赞赏。
pragma solidity ^0.5.0;
import "./DappToken.sol";
import "./DaiToken.sol";
contract TokenFarm {
string public name = "Dapp Token Farm";
address public owner;
DappToken public dappToken;
DaiToken public daiToken;
address[] public stakers;
mapping(address => uint) public stakingBalance;
mapping(address => bool) public hasStaked;
mapping(address => bool) public isStaking;
constructor(DappToken _dappToken, DaiToken _daiToken) public {
dappToken = _dappToken;
daiToken = _daiToken;
owner = msg.sender;
}
// 1. stakes tokens (deposit)
function stakeTokens(uint _amount) public {
require(_amount > 0, "amount cannot be 0");
daiToken.transferFrom(msg.sender, address(this), _amount);
stakingBalance[msg.sender] = stakingBalance[msg.sender] + _amount;
if(!hasStaked[msg.sender]) {
stakers.push(msg.sender);
}
isStaking[msg.sender] = true;
hasStaked[msg.sender] = true;
}
// 2.issuing tokens
function issueTokens() public {
require(msg.sender == owner, "caller must be the owner");
for (uint i=0; i<stakers.length; i++) {
address recipient = stakers[i];
uint balance = stakingBalance[recipient];
if(balance > 0) {
dappToken.transfer(recipient, balance);
}
}
}
// 3. unstake
function unstakeTokens() public {
uint balance = stakingBalance[msg.sender];
require(balance > 0, "staking balance cannot be 0");
daiToken.transfer(msg.sender, balance);
stakingBalance[msg.sender] = 0;
isStaking[msg.sender] = false;
}
}