区块链
当某人投资某些资产以换取某种程度的控制,影响力或参与其活动时,就会有人持有该企业的股份。
在加密货币世界中,这被理解为只要他们不转让他们拥有的某些代币,就会给予用户某种权利或奖励。staking机制通常鼓励对代币交易进行代币持有,而代币交易又有望推动代币估值。
要建立这种staking机制,我们需要:
1. staking代币
2. 跟踪stakes、权益持有者和回报的数据结构
3. 创建和删除stakes的方法
4. 奖励机制
我们继续吧。
staking代币
为我们的staking代币创建ERC20代币。稍后我将需要SafeMash和Ownable,所以让我们导入并使用它们。
pragma solidity ^0.5.0;
import “openzeppelin-solidity/contracts/token/ERC20/ERC20.sol”;
import “openzeppelin-solidity/contracts/math/SafeMath.sol”;
import “openzeppelin-solidity/contracts/ownership/Ownable.sol”;
/**
* @title Staking Token (STK)
* @author Alberto Cuesta Canada
* @notice Implements a basic ERC20 staking token with incentive distribution.
*/
contract StakingToken is ERC20, Ownable {
using SafeMath for uint256;
/**
* @notice The constructor for the Staking Token.
* @param _owner The address to receive all tokens on construction.
* @param _supply The amount of tokens to mint on construction.
*/
constructor(address _owner, uint256 _supply)
public
{
_mint(_owner, _supply);
}
就这样,不需要别的了。
权益持有者
在这个实施过程中,我们将跟踪权益持有者,以便日后有效地分配激励措施。理论上,可能无法像普通的erc20代币那样跟踪它们,但在实践中,很难确保权益持有者不会在不跟踪它们的情况下与分发系统进行博弈。
为了实现,我们将使用一个权益持有者地址的动态数组。
/**
* @notice We usually require to know who are all the stakeholders.
*/
address[] internal stakeholders;
以下方法添加权益持有者,删除权益持有者,并验证地址是否属于权益持有者。 其他更有效的实现肯定是可能的,但我喜欢这个可读性。
/**
* @notice A method to check if an address is a stakeholder.
* @param _address The address to verify.
* @return bool, uint256 Whether the address is a stakeholder,
* and if so its position in the stakeholders array.
*/
function isStakeholder(address _address)
public
view
returns(bool, uint256)
{
for (uint256 s = 0; s 《 stakeholders.length; s += 1){
if (_address == stakeholders[s]) return (true, s);
}
return (false, 0);
}
/**
* @notice A method to add a stakeholder.
* @param _stakeholder The stakeholder to add.
*/
function addStakeholder(address _stakeholder)
public
{
(bool _isStakeholder, ) = isStakeholder(_stakeholder);
if(!_isStakeholder) stakeholders.push(_stakeholder);
}
/**
* @notice A method to remove a stakeholder.
* @param _stakeholder The stakeholder to remove.
*/
function removeStakeholder(address _stakeholder)
public
{
(bool _isStakeholder, uint256 s) = isStakeholder(_stakeholder);
if(_isStakeholder){
stakeholders[s] = stakeholders[stakeholders.length - 1];
stakeholders.pop();
}
}
抵押
最简单形式的抵押将需要记录抵押规模和权益持有者。 一个非常简单的实现可能只是从权益持有者的地址到抵押大小的映射。
/**
* @notice The stakes for each stakeholder.
*/
mapping(address =》 uint256) internal stakes;
我将遵循erc20中的函数名,并创建等价物以从抵押映射中获取数据。
/**
* @notice A method to retrieve the stake for a stakeholder.
* @param _stakeholder The stakeholder to retrieve the stake for.
* @return uint256 The amount of wei staked.
*/
function stakeOf(address _stakeholder)
public
view
returns(uint256)
{
return stakes[_stakeholder];
}
/**
* @notice A method to the aggregated stakes from all stakeholders.
* @return uint256 The aggregated stakes from all stakeholders.
*/
function totalStakes()
public
view
returns(uint256)
{
uint256 _totalStakes = 0;
for (uint256 s = 0; s 《 stakeholders.length; s += 1){
_totalStakes = _totalStakes.add(stakes[stakeholders[s]]);
}
return _totalStakes;
}
我们现在将给予STK持有者创建和移除抵押的能力。我们将销毁这些令牌,因为它们被标记,以防止用户在移除标记之前转移它们。
请注意,在创建抵押时,如果用户试图放置比他拥有的更多的令牌时,_burn将会恢复。在移除抵押时,如果试图移除更多的已持有的代币,则将恢复对抵押映射的更新。
最后,我们使用addStakeholder和removeStakeholder来记录谁有抵押,以便稍后在奖励系统中使用。
/**
* @notice A method for a stakeholder to create a stake.
* @param _stake The size of the stake to be created.
*/
function createStake(uint256 _stake)
public
{
_burn(msg.sender, _stake);
if(stakes[msg.sender] == 0) addStakeholder(msg.sender);
stakes[msg.sender] = stakes[msg.sender].add(_stake);
}
/**
* @notice A method for a stakeholder to remove a stake.
* @param _stake The size of the stake to be removed.
*/
function removeStake(uint256 _stake)
public
{
stakes[msg.sender] = stakes[msg.sender].sub(_stake);
if(stakes[msg.sender] == 0) removeStakeholder(msg.sender);
_mint(msg.sender, _stake);
}
奖励
奖励机制可以有许多不同的实现,并且运行起来相当繁重。对于本合同,我们将实施一个非常简单的版本,其中权益持有者定期获得相当于其个人抵押1%的STK代币奖励。
在更复杂的合同中,当满足某些条件时,将自动触发奖励的分配,但在这种情况下,我们将让所有者手动触发它。按照最佳实践,我们还将跟踪奖励并实施一种撤销方法。
和以前一样,为了使代码可读,我们遵循ERC20.sol合同的命名约定,首先是数据结构和数据管理方法:
/**
* @notice The accumulated rewards for each stakeholder.
*/
mapping(address =》 uint256) internal rewards;
/**
* @notice A method to allow a stakeholder to check his rewards.
* @param _stakeholder The stakeholder to check rewards for.
*/
function rewardOf(address _stakeholder)
public
view
returns(uint256)
{
return rewards[_stakeholder];
}
/**
* @notice A method to the aggregated rewards from all stakeholders.
* @return uint256 The aggregated rewards from all stakeholders.
*/
function totalRewards()
public
view
returns(uint256)
{
uint256 _totalRewards = 0;
for (uint256 s = 0; s 《 stakeholders.length; s += 1){
_totalRewards = _totalRewards.add(rewards[stakeholders[s]]);
}
return _totalRewards;
}
接下来是计算,分配和取消奖励的方法:
/**
* @notice A simple method that calculates the rewards for each stakeholder.
* @param _stakeholder The stakeholder to calculate rewards for.
*/
function calculateReward(address _stakeholder)
public
view
returns(uint256)
{
return stakes[_stakeholder] / 100;
}
/**
* @notice A method to distribute rewards to all stakeholders.
*/
function distributeRewards()
public
onlyOwner
{
for (uint256 s = 0; s 《 stakeholders.length; s += 1){
address stakeholder = stakeholders[s];
uint256 reward = calculateReward(stakeholder);
rewards[stakeholder] = rewards[stakeholder].add(reward);
}
}
/**
* @notice A method to allow a stakeholder to withdraw his rewards.
*/
function withdrawReward()
public
{
uint256 reward = rewards[msg.sender];
rewards[msg.sender] = 0;
_mint(msg.sender, reward);
}
测试
没有一套全面的测试,任何合同都不能完成。我倾向于至少为每个函数生成一个bug,但通常情况下不会发生这样的事情。
除了允许您生成有效的代码之外,测试在开发设置和使用智能合约的过程中也非常有用。
下面介绍如何设置和使用测试环境。我们将制作1000个STK令牌并将其交给用户使用该系统。我们使用truffle进行测试,这使我们可以使用帐户。
contract(‘StakingToken’, (accounts) =》 {
let stakingToken;
const manyTokens = BigNumber(10).pow(18).multipliedBy(1000);
const owner = accounts[0];
const user = accounts[1];
before(async () =》 {
stakingToken = await StakingToken.deployed();
});
describe(‘Staking’, () =》 {
beforeEach(async () =》 {
stakingToken = await StakingToken.new(
owner,
manyTokens.toString(10)
);
});
在创建测试时,我总是编写使代码恢复的测试,但这些测试并不是很有趣。 对createStake的测试显示了创建赌注需要做些什么,以及之后应该改变什么。
重要的是要注意在这个抵押合约中我们有两个平行的数据结构,一个用于STK余额,一个用于抵押以及它们的总和如何通过创建和删除抵押数量保持不变。在这个例子中,我们给用户3个STK wei,该用户的余额加抵押总和将始终为3。
it(‘createStake creates a stake.’, async () =》 {
await stakingToken.transfer(user, 3, { from: owner });
await stakingToken.createStake(1, { from: user });
assert.equal(await stakingToken.balanceOf(user), 2);
assert.equal(await stakingToken.stakeOf(user), 1);
assert.equal(
await stakingToken.totalSupply(),
manyTokens.minus(1).toString(10),
);
assert.equal(await stakingToken.totalStakes(), 1);
});
对于奖励,下面的测试显示了所有者如何激发费用分配,用户获得了1%的份额奖励。
it(‘rewards are distributed.’, async () =》 {
await stakingToken.transfer(user, 100, { from: owner });
await stakingToken.createStake(100, { from: user });
await stakingToken.distributeRewards({ from: owner });
assert.equal(await stakingToken.rewardOf(user), 1);
assert.equal(await stakingToken.totalRewards(), 1);
});
当奖励分配时,STK的总供应量会增加,这个测试显示了三个数据结构(余额、抵押和奖励)是如何相互关联的。现有和承诺的STK金额将始终是创建时的金额加上奖励中分配的金额,这些金额可能会或可能不会被铸造。。创建时生成的STK数量将等于余额和抵押的总和,直到完成分配。
it(‘rewards can be withdrawn.’, async () =》 {
await stakingToken.transfer(user, 100, { from: owner });
await stakingToken.createStake(100, { from: user });
await stakingToken.distributeRewards({ from: owner });
await stakingToken.withdrawReward({ from: user });
const initialSupply = manyTokens;
const existingStakes = 100;
const mintedAndWithdrawn = 1;
assert.equal(await stakingToken.balanceOf(user), 1);
assert.equal(await stakingToken.stakeOf(user), 100);
assert.equal(await stakingToken.rewardOf(user), 0);
assert.equal(
await stakingToken.totalSupply(),
initialSupply
.minus(existingStakes)
.plus(mintedAndWithdrawn)
.toString(10)
);
assert.equal(await stakingToken.totalStakes(), 100);
assert.equal(await stakingToken.totalRewards(), 0);
});
结论
抵押和奖励机制是一种强大的激励工具,复杂程度根据我们自身设计相关。 erc20标准和safemath中提供的方法允许我们用大约200行代码对其进行编码。
文章来源:区块链研究实验室
全部0条评论
快来发表一下你的评论吧 !