如何建立一個(gè)staking機(jī)制
當(dāng)某人投資某些資產(chǎn)以換取某種程度的控制,影響力或參與其活動(dòng)時(shí),就會(huì)有人持有該企業(yè)的股份。
在加密貨幣世界中,這被理解為只要他們不轉(zhuǎn)讓他們擁有的某些代幣,就會(huì)給予用戶某種權(quán)利或獎(jiǎng)勵(lì)。staking機(jī)制通常鼓勵(lì)對(duì)代幣交易進(jìn)行代幣持有,而代幣交易又有望推動(dòng)代幣估值。
要建立這種staking機(jī)制,我們需要:
1. staking代幣
2. 跟蹤stakes、權(quán)益持有者和回報(bào)的數(shù)據(jù)結(jié)構(gòu)
3. 創(chuàng)建和刪除stakes的方法
4. 獎(jiǎng)勵(lì)機(jī)制
我們繼續(xù)吧。
staking代幣
為我們的staking代幣創(chuàng)建ERC20代幣。稍后我將需要SafeMash和Ownable,所以讓我們導(dǎo)入并使用它們。
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);
}
就這樣,不需要?jiǎng)e的了。
權(quán)益持有者
在這個(gè)實(shí)施過程中,我們將跟蹤權(quán)益持有者,以便日后有效地分配激勵(lì)措施。理論上,可能無法像普通的erc20代幣那樣跟蹤它們,但在實(shí)踐中,很難確保權(quán)益持有者不會(huì)在不跟蹤它們的情況下與分發(fā)系統(tǒng)進(jìn)行博弈。
為了實(shí)現(xiàn),我們將使用一個(gè)權(quán)益持有者地址的動(dòng)態(tài)數(shù)組。
/**
* @notice We usually require to know who are all the stakeholders.
*/
address[] internal stakeholders;
以下方法添加權(quán)益持有者,刪除權(quán)益持有者,并驗(yàn)證地址是否屬于權(quán)益持有者。 其他更有效的實(shí)現(xiàn)肯定是可能的,但我喜歡這個(gè)可讀性。
/**
* @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();
}
}
抵押
最簡(jiǎn)單形式的抵押將需要記錄抵押規(guī)模和權(quán)益持有者。 一個(gè)非常簡(jiǎn)單的實(shí)現(xiàn)可能只是從權(quán)益持有者的地址到抵押大小的映射。
/**
* @notice The stakes for each stakeholder.
*/
mapping(address =》 uint256) internal stakes;
我將遵循erc20中的函數(shù)名,并創(chuàng)建等價(jià)物以從抵押映射中獲取數(shù)據(jù)。
/**
* @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;
}
我們現(xiàn)在將給予STK持有者創(chuàng)建和移除抵押的能力。我們將銷毀這些令牌,因?yàn)樗鼈儽?u>標(biāo)記,以防止用戶在移除標(biāo)記之前轉(zhuǎn)移它們。
請(qǐng)注意,在創(chuàng)建抵押時(shí),如果用戶試圖放置比他擁有的更多的令牌時(shí),_burn將會(huì)恢復(fù)。在移除抵押時(shí),如果試圖移除更多的已持有的代幣,則將恢復(fù)對(duì)抵押映射的更新。
最后,我們使用addStakeholder和removeStakeholder來記錄誰有抵押,以便稍后在獎(jiǎng)勵(lì)系統(tǒng)中使用。
/**
* @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);
}
獎(jiǎng)勵(lì)
獎(jiǎng)勵(lì)機(jī)制可以有許多不同的實(shí)現(xiàn),并且運(yùn)行起來相當(dāng)繁重。對(duì)于本合同,我們將實(shí)施一個(gè)非常簡(jiǎn)單的版本,其中權(quán)益持有者定期獲得相當(dāng)于其個(gè)人抵押1%的STK代幣獎(jiǎng)勵(lì)。
在更復(fù)雜的合同中,當(dāng)滿足某些條件時(shí),將自動(dòng)觸發(fā)獎(jiǎng)勵(lì)的分配,但在這種情況下,我們將讓所有者手動(dòng)觸發(fā)它。按照最佳實(shí)踐,我們還將跟蹤獎(jiǎng)勵(lì)并實(shí)施一種撤銷方法。
和以前一樣,為了使代碼可讀,我們遵循ERC20.sol合同的命名約定,首先是數(shù)據(jù)結(jié)構(gòu)和數(shù)據(jù)管理方法:
/**
* @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;
}
接下來是計(jì)算,分配和取消獎(jiǎng)勵(lì)的方法:
/**
* @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);
}
測(cè)試
沒有一套全面的測(cè)試,任何合同都不能完成。我傾向于至少為每個(gè)函數(shù)生成一個(gè)bug,但通常情況下不會(huì)發(fā)生這樣的事情。
除了允許您生成有效的代碼之外,測(cè)試在開發(fā)設(shè)置和使用智能合約的過程中也非常有用。
下面介紹如何設(shè)置和使用測(cè)試環(huán)境。我們將制作1000個(gè)STK令牌并將其交給用戶使用該系統(tǒng)。我們使用truffle進(jìn)行測(cè)試,這使我們可以使用帳戶。
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)
);
});
在創(chuàng)建測(cè)試時(shí),我總是編寫使代碼恢復(fù)的測(cè)試,但這些測(cè)試并不是很有趣。 對(duì)createStake的測(cè)試顯示了創(chuàng)建賭注需要做些什么,以及之后應(yīng)該改變什么。
重要的是要注意在這個(gè)抵押合約中我們有兩個(gè)平行的數(shù)據(jù)結(jié)構(gòu),一個(gè)用于STK余額,一個(gè)用于抵押以及它們的總和如何通過創(chuàng)建和刪除抵押數(shù)量保持不變。在這個(gè)例子中,我們給用戶3個(gè)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);
});
對(duì)于獎(jiǎng)勵(lì),下面的測(cè)試顯示了所有者如何激發(fā)費(fèi)用分配,用戶獲得了1%的份額獎(jiǎng)勵(lì)。
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);
});
當(dāng)獎(jiǎng)勵(lì)分配時(shí),STK的總供應(yīng)量會(huì)增加,這個(gè)測(cè)試顯示了三個(gè)數(shù)據(jù)結(jié)構(gòu)(余額、抵押和獎(jiǎng)勵(lì))是如何相互關(guān)聯(lián)的。現(xiàn)有和承諾的STK金額將始終是創(chuàng)建時(shí)的金額加上獎(jiǎng)勵(lì)中分配的金額,這些金額可能會(huì)或可能不會(huì)被鑄造。。創(chuàng)建時(shí)生成的STK數(shù)量將等于余額和抵押的總和,直到完成分配。
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);
});
結(jié)論
抵押和獎(jiǎng)勵(lì)機(jī)制是一種強(qiáng)大的激勵(lì)工具,復(fù)雜程度根據(jù)我們自身設(shè)計(jì)相關(guān)。 erc20標(biāo)準(zhǔn)和safemath中提供的方法允許我們用大約200行代碼對(duì)其進(jìn)行編碼。
文章來源:區(qū)塊鏈研究實(shí)驗(yàn)室?