MasterChef interpretation of SushiSwap -- reprint

Posted by kazil on Mon, 07 Feb 2022 11:03:42 +0100

MasterChef interpretation of SushiSwap

biakia0610 Issued at 14:22:31, April 13, 2021 412
Category column: Blockchain Article label: Blockchain
Blockchain The column contains this content
11 articles 1 subscription

1. Data structure of MasterChef

MasterChef is at the core of SushiSwap, through which users can conduct mobile mining. MasterChef contains two main data structures: UserInfo and PoolInfo

1.1,UserInfo

     
  1. struct UserInfo {
  2. uint256 amount; // How many LP tokens the user has provided.
  3. uint256 rewardDebt; // Reward debt. See explanation below.
  4. //
  5. // We do some fancy math here. Basically, any point in time, the amount of SUSHIs
  6. // entitled to a user but is pending to be distributed is:
  7. //
  8. // pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
  9. //
  10. // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
  11. // 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
  12. // 2. User receives the pending reward sent to his/her address.
  13. // 3. User's `amount` gets updated.
  14. // 4. User's `rewardDebt` gets updated.
  15. }

amount is the number of lptokens pledged by the user, and rewardDebt represents the number of rewards the user has received.

1.2,PoolInfo

     
  1. struct PoolInfo {
  2. IERC20 lpToken; // Address of LP token contract.
  3. uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.
  4. uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.
  5. uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
  6. }

Lptoken is ERC20 standard token. The initial lptoken of SushiSwap is the liquidity of Uniswap. The liquidity generated after Uniswap pledge is actually the token of UniswapPair. SushiSwap can pledge the liquidity of Uniswap by setting the address of UniswapPair to pool. Later, SushiSwap completed a migration, and lptoken changed from the liquidity token of Uniswap to the liquidity token of SushiSwap.

allocPoint is the allocation proportion of pledge pool, and lastRewardBlock is the number of blocks allocated with rewards last time.

accSushiPerShare is the global income of pledging an LPToken. The user relies on this to calculate the actual income. The principle is very simple. When pledging an LPToken, the user will write down the current accSushiPerShare as the starting point. When the pledge is released, the user's actual income can be obtained by subtracting the starting point from the latest accSushiPerShare.

1.3 other data structures

     
  1. SushiToken public sushi;
  2. // Dev address.
  3. address public devaddr;
  4. // Block number when bonus SUSHI period ends.
  5. uint256 public bonusEndBlock;
  6. // SUSHI tokens created per block.
  7. uint256 public sushiPerBlock;
  8. // Bonus muliplier for early sushi makers.
  9. uint256 public constant BONUS_MULTIPLIER = 10;
  10. // The migrator contract. It has a lot of power. Can only be set through governance (owner).
  11. IMigratorChef public migrator;
  12. // Info of each pool.
  13. PoolInfo[] public poolInfo;
  14. // Info of each user that stakes LP tokens.
  15. mapping(uint256 => mapping(address => UserInfo)) public userInfo;
  16. // Total allocation poitns. Must be the sum of all allocation points in all pools.
  17. uint256 public totalAllocPoint = 0;
  18. // The block number when SUSHI mining starts.
  19. uint256 public startBlock;

sushi is an ERC20 token, which is the token reward obtained by pledging liquidity.

devaddr is the developer's address, which is used to allocate the handling fee of sushi reward

bonusEndBlock. At first, sushi was pledged by the liquidity of Uniswap. In order to attract users, a bonus multiplier bonus was set_ Multiplier and a bonus deadline block, bonusEndBlock, the number of rewards obtained before bonusEndBlock will be multiplied by 10. After this block is migrated, there will be no double reward after migration, and the subsequent value will not be used.

sushiPerBlock, the number of sushi excavated in each block

As like as two peas, migrator, the migration tool class implements the principle of creating a SushiSwapPair identical to UniswapPair, then redeeming the transaction pair (such as USDT/DAI) with the UniswapPair liquidity of the user, then adding the transaction to SushiSwapPair, obtaining the SushiSwapPair mobile token, and finally pledge the SushiSwapPair's mobile token.

totalAllocPoint is the total number of points allocated

startBlock is the start block

 

2. Constructor

     
  1. constructor(
  2. SushiToken _sushi,
  3. address _devaddr,
  4. uint256 _sushiPerBlock,
  5. uint256 _startBlock,
  6. uint256 _bonusEndBlock
  7. ) public {
  8. sushi = _sushi;
  9. devaddr = _devaddr;
  10. sushiPerBlock = _sushiPerBlock;
  11. bonusEndBlock = _bonusEndBlock;
  12. startBlock = _startBlock;
  13. }

MasterChef initializes the address of the incoming sushi token (value: 0x6b3595068778dd592e39a122f4f5a5cf09c90fe2 ), developer address (value: 0xe94b5eec1fa96ceecbd33ef5baa8d00e4493f4f3 , the number of sushi allocated to each block (value is) 100 *1e18), reward end block (value 10850000) and start block (value 10750000)

 

3. Add pool pledge

     
  1. function add(
  2. uint256 _allocPoint,
  3. IERC20 _lpToken,
  4. bool _withUpdate
  5. ) public onlyOwner {
  6. if (_withUpdate) {
  7. massUpdatePools();
  8. }
  9. uint256 lastRewardBlock =
  10. block.number > startBlock ? block.number : startBlock;
  11. totalAllocPoint = totalAllocPoint.add(_allocPoint);
  12. poolInfo.push(
  13. PoolInfo({
  14. lpToken: _lpToken,
  15. allocPoint: _allocPoint,
  16. lastRewardBlock: lastRewardBlock,
  17. accSushiPerShare: 0
  18. })
  19. );
  20. }

The code is very simple. Generate a poolInfo, add it to the array, and then update totalAllocPoint, where_ allocPoint refers to the proportion of mining in this pool. For example, totalAllocPoint is 10000_ allocPoint is 100, and each block digs a total of 100, so the pool allocated to each block is 100 * (100 / 10000) = 1

This method can only be executed by the administrator because there is an onlyOwner modifier

 

4. Modify pledge pool parameters

     
  1. function set(
  2. uint256 _pid,
  3. uint256 _allocPoint,
  4. bool _withUpdate
  5. ) public onlyOwner {
  6. if (_withUpdate) {
  7. massUpdatePools();
  8. }
  9. totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
  10. _allocPoint
  11. );
  12. poolInfo[_pid].allocPoint = _allocPoint;
  13. }

At present, only the allocation proportion of pledged mining can be modified, and only administrators can implement it.

 

5. Perform migration

     
  1. function setMigrator(IMigratorChef _migrator) public onlyOwner {
  2. migrator = _migrator;
  3. }
  4. function migrate(uint256 _pid) public {
  5. require(address(migrator) != address( 0), "migrate: no migrator");
  6. PoolInfo storage pool = poolInfo[_pid];
  7. IERC20 lpToken = pool.lpToken;
  8. uint256 bal = lpToken.balanceOf(address(this));
  9. lpToken.safeApprove(address(migrator), bal);
  10. IERC20 newLpToken = migrator.migrate(lpToken);
  11. require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
  12. pool.lpToken = newLpToken;
  13. }

The administrator will first set the migrator and then migrate for a single pledge pool. The migration process first authorizes the migrator (safeApprove), and then is controlled by the migrator. The migrator will return a new LPToken, and then reset the pledge pool. Let's see how sushi's migrator operates:

     
  1. function migrate(IUniswapV2Pair orig) public returns (IUniswapV2Pair) {
  2. require(msg.sender == chef, "not from master chef");
  3. require(block.number >= notBeforeBlock, "too early to migrate");
  4. require(orig.factory() == oldFactory, "not from old factory");
  5. address token0 = orig.token0();
  6. address token1 = orig.token1();
  7. IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(token0, token1));
  8. if (pair == IUniswapV2Pair(address( 0))) {
  9. pair = IUniswapV2Pair(factory.createPair(token0, token1));
  10. }
  11. uint256 lp = orig.balanceOf(msg.sender);
  12. if (lp == 0) return pair;
  13. desiredLiquidity = lp;
  14. //User mobility is also supported by Uniswap
  15. orig.transferFrom(msg.sender, address(orig), lp);
  16. //Uniswap gives the pledged token transaction pair to the pair of sushiswap
  17. orig.burn(address(pair));
  18. //sushiswap issues liquidity to users
  19. pair.mint(msg.sender);
  20. desiredLiquidity = uint256( -1);
  21. return pair;
  22. }

As mentioned above, sushiswap initially relies on the liquidity of uniswap, so the lpToken above is actually UniswapPair. Then, get the two tokens in the specific transaction pair through UniswapPair, and then create sushiswappair in sushi (both implementation classes of IUniswapV2Pair interface), Then redemption of user's liquidity in Uniswap (first transfer to Uniswap, then call burn, note that the object of burn here is pair, so Uniswap will return the two pledged token to SushiSwapPair's address), and finally call Mint mint to give users the additional mobility of the SushiSwapPair, thus completing the migration of user mobility.

6. Update pledge pool income

     
  1. function updatePool(uint256 _pid) public {
  2. PoolInfo storage pool = poolInfo[_pid];
  3. if (block.number <= pool.lastRewardBlock) {
  4. return;
  5. }
  6. uint256 lpSupply = pool.lpToken.balanceOf(address(this));
  7. if (lpSupply == 0) {
  8. pool.lastRewardBlock = block.number;
  9. return;
  10. }
  11. uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
  12. uint256 sushiReward =
  13. multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(
  14. totalAllocPoint
  15. );
  16. sushi.mint(devaddr, sushiReward.div( 10));
  17. sushi.mint(address(this), sushiReward);
  18. pool.accSushiPerShare = pool.accSushiPerShare.add(
  19. sushiReward.mul( 1e12).div(lpSupply)
  20. );
  21. pool.lastRewardBlock = block.number;
  22. }

First, calculate the number of lptokens in the pledge pool. If it is 0, only lastRewardBlock will be updated. Otherwise, a multiplier multiplier will be calculated first

     
  1. // Return reward multiplier over the given _from to _to block.
  2. function getMultiplier(uint256 _from, uint256 _to)
  3. public
  4. view
  5. returns (uint256)
  6. {
  7. if (_to <= bonusEndBlock) {
  8. return _to.sub(_from).mul(BONUS_MULTIPLIER);
  9. } else if (_from >= bonusEndBlock) {
  10. return _to.sub(_from);
  11. } else {
  12. return
  13. bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
  14. _to.sub(bonusEndBlock)
  15. );
  16. }
  17. }

The calculation here is to be compatible with bonusEndBlock. If to is less than bonusEndBlock, it means that the pledge pool is completely in the reward mining stage and will be multiplied by a multiple of BONUS_MULTIPLIER, if from is greater than bonusEndBlock, it means that the pledge pool has not participated in the reward mining at all, so it is OK to simply use to-from. The last else is to deal with the pledge pool, part of which participates in the reward mining, and part of which is the conventional mining after the end.

The calculation of multiplier is the number of reward blocks from lastRewardBlock to the current block. After obtaining the multiplier, calculate the sushi reward for this period of time

     
  1. uint256 sushiReward =
  2. multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(
  3. totalAllocPoint
  4. );

multiplier*sushiPerBlock is the total sushi reward, pool Allocpoint / totalallocpoint is the allocation proportion of the current pledge pool.

Next, 10% sushiReward is allocated to the developer address as the handling fee, and then the total sushiReward is allocated to the current pledge pool.

Then calculate accSushiPerShare to accumulate.

Finally, update lastRewardBlock.

7. View user pledge income

     
  1. function pendingSushi(uint256 _pid, address _user)
  2. external
  3. view
  4. returns (uint256)
  5. {
  6. PoolInfo storage pool = poolInfo[_pid];
  7. UserInfo storage user = userInfo[_pid][_user];
  8. uint256 accSushiPerShare = pool.accSushiPerShare;
  9. uint256 lpSupply = pool.lpToken.balanceOf(address(this));
  10. if (block.number > pool.lastRewardBlock && lpSupply != 0) {
  11. uint256 multiplier =
  12. getMultiplier(pool.lastRewardBlock, block.number);
  13. uint256 sushiReward =
  14. multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(
  15. totalAllocPoint
  16. );
  17. accSushiPerShare = accSushiPerShare.add(
  18. sushiReward.mul( 1e12).div(lpSupply)
  19. );
  20. }
  21. return user.amount.mul(accSushiPerShare).div( 1e12).sub(user.rewardDebt);
  22. }

All the previous logics are updating the latest income of the current pledge pool. The logic is similar to that of updatePool, but does not execute mint, but only performs logical calculation. In the last line, multiply the amount pledged by the user by accSushiPerShare to obtain the total number of sushi obtained by the user in theory, and then subtract the number of sushi actually obtained by the user, rewardDebt, which is the remaining data that has not been obtained.

8. Users pledge LPToken for mining

     
  1. function deposit(uint256 _pid, uint256 _amount) public {
  2. PoolInfo storage pool = poolInfo[_pid];
  3. UserInfo storage user = userInfo[_pid][msg.sender];
  4. updatePool(_pid);
  5. if (user.amount > 0) {
  6. uint256 pending =
  7. user.amount.mul(pool.accSushiPerShare).div( 1e12).sub(
  8. user.rewardDebt
  9. );
  10. safeSushiTransfer(msg.sender, pending);
  11. }
  12. pool.lpToken.safeTransferFrom(
  13. address(msg.sender),
  14. address(this),
  15. _amount
  16. );
  17. user.amount = user.amount.add(_amount);
  18. user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div( 1e12);
  19. emit Deposit(msg.sender, _pid, _amount);
  20. }

First update the pledge pool income, then calculate the sushi income not obtained by the user (if the user has pledged before), and transfer these income to the user account. Then transfer the user's LPToken to the pledge pool, and finally update the number of lptokens pledged by the user, and set the latest amount*accSushiPerShare to rewardDebt. This step is actually to set a starting point for user reward, which is exactly the starting point for the above calculation of pendingSushi.

9. Release pledge

     
  1. function withdraw(uint256 _pid, uint256 _amount) public {
  2. PoolInfo storage pool = poolInfo[_pid];
  3. UserInfo storage user = userInfo[_pid][msg.sender];
  4. require(user.amount >= _amount, "withdraw: not good");
  5. updatePool(_pid);
  6. uint256 pending =
  7. user.amount.mul(pool.accSushiPerShare).div( 1e12).sub(
  8. user.rewardDebt
  9. );
  10. safeSushiTransfer(msg.sender, pending);
  11. user.amount = user.amount.sub(_amount);
  12. user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div( 1e12);
  13. pool.lpToken.safeTransfer(address(msg.sender), _amount);
  14. emit Withdraw(msg.sender, _pid, _amount);
  15. }

First update the pledge pool income, then calculate the sushi income not obtained by the user, transfer these income to the user account, then update the rewardDebt, and finally return the LPToken to the user.

</article>

Topics: Blockchain Ethereum