SushiSwap Explained!
Looking at the implementation details of SushiSwap
You've probably heard of SushiSwap by now. The Uniswap fork brought new features like staking and governance to the exchange. But how exactly are the contracts behind it working?
It's actually not too difficult. Knowing how this works in detail will be a great way to learn about Solidity and Defi.
The contracts in detail
1. Uniswap v2
At its core SushiSwap is just a Uniswap v2 fork. The contract code was copied 1:1 except for a few small differences. If you are curious about how Uniswap v2 works, check out my previous post here. And also keep an eye out for a deep dive into Uniswap v3 in the near future.
In particular SushiSwap is making use of liquidity pool tokens (LP tokens). Check out https://uniswap.org/docs/v2/core-concepts/pools/ under 'Pool tokens' for all details. Essentially LPs are for receiving pro-rata fees accrued in the pool. So you provide liquidity in a pool and get LP tokens minted in return. When the pool is now collecting fees over time, they are evenly distributed to all LP holders at the time of the trade. When you burn your LP tokens, you will receive your share of the pool + the collected fees.
Two changes to the Uniswap code where made by SushiSwap:
- The function setFeeTo was called in the deployment and the fee recipient was set to the SushiMaker contract (see below). Once the fee recipient is set, 1/6th of the LP supply growth due to the current trade are minted as protocol fee in the form of pool tokens. Since the trade fee on Uniswap is 0.3%, this will result in a 0.05% fee of every trade going towards the SushiMaker.
- A migrator functionality was added (see SushiRoll below).
You can see the full diff between Uniswap's core contracts and how SushiSwap changed them here.
2. SushiMaker

The SushiMaker will receive LP tokens from people trading on SushiSwap. It mostly consists of a convert
function which does the following:
- Burn the LP tokens for the provided token pair. The result will be receiving proportional amounts of both
token0
andtoken1
. - Inside
convertStep
trade both received tokens into SUSHI. This may require additional steps if there's no direct pool to trade into SUSHI.
The swap itself is performed on the SushiSwap pools itself. Let's see how this is done by examining the _swap
function.
function convert(address token0, address token1) external {
UniV2Pair pair = UniV2Pair(factory.getPair(token0, token1));
require(address(pair) != address(0), "Invalid pair");
IERC20(address(pair)).safeTransfer(
address(pair),
pair.balanceOf(address(this))
);
(uint256 amount0, uint256 amount1) = pair.burn(address(this));
if (token0 != pair.token0()) {
(amount0, amount1) = (amount1, amount0);
}
_convertStep(token0, token1, amount0, amount1)
}
function _swap(
address fromToken,
address toToken,
uint256 amountIn,
address to
) internal returns (uint256 amountOut) {
UniV2Pair pair =
UniV2Pair(factory.getPair(fromToken, toToken));
require(address(pair) != address(0), "Cannot convert");
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountInWithFee = amountIn.mul(997);
if (fromToken == pair.token0()) {
amountOut =
amountInWithFee.mul(reserve1) /
reserve0.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(0, amountOut, to, new bytes(0));
} else {
amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(amountOut, 0, to, new bytes(0));
}
}
The swap itself is performed on the SushiSwap pools itself. For the trade we are using the low-level Uniswap swap function.
- Get the current reserves of both tokens in the pool.
- Compute the receiving amount from the reserves and token amount being swapped minus the fees. Calculation is based on the x * y = k curve.
Once the amount out is computed, we can perform the swap. The last step to convert into SUSHI will always call the _swap
function by passing the SUSHI token address and sending it to the bar:
_swap(token, sushi, amountIn, bar)
That's it, now we converted all LP tokens into SUSHI. All converted SUSHI are sent to the SushiBar, see next contract.
3. SushiBar

Inside the SushiBar people can enter with SUSHI, receive xSUSHI and later leave with even more SUSHI. Remember that all SUSHI from the SushiMaker are sent here. So over time the bar will accumulate more and more SUSHI.
Who will receive this SUSHI?
Anyone who entered the bar. For entering a user receives xSUSHI which are kind of like the LP tokens for Uniswap. They represent ownership of the SUSHI token in the bar.
The amount of xSUSHI you receive is your transferred SUSHI * total xSUSHI supply / current balance of SUSHI. So if you send 10 SUSHI to the bar which already has 100 SUSHI in it and 200 xSUSHI total supply, you will receive 10 * 200 / 100 = 20 xSUSHI.
function enter(uint256 _amount) external {
uint256 totalSushi = sushi.balanceOf(address(this));
uint256 totalShares = totalSupply();
uint256 mintAmount =
totalShares == 0 || totalSushi == 0
? _amount
: _amount.mul(totalShares).div(totalSushi);
_mint(msg.sender, mintAmount);
sushi.transferFrom(
msg.sender,
address(this),
_amount
);
}
function leave(uint256 _share) external {
uint256 totalShares = totalSupply();
uint256 transferAmount = _share
.mul(sushi.balanceOf(address(this)))
.div(totalShares);
_burn(msg.sender, _share);
sushi.transfer(msg.sender, transferAmount);
}
Now when you leave again, you get your equal share of SUSHI back. This will be at the minimum what you paid in, but considering the bar will accumulate SUSHI over time, it should be more than what you put originally in.
The amount of SUSHI you receive is your transferred xSUSHI * current balance of SUSHI / total xSUSHI supply. So if you send 20 xSUSHI to the bar which has 100 SUSHI in it and 200 xSUSHI total supply, you will receive 20 * 100 / 200 = 10 SUSHI.
3. SushiToken
Of course you have the SUSHI token contract itself. There's nothing special to it other than being a regular ERC-20 with delegation functionality identical to the COMP token. We've previously discussed COMP governance here. The mentioned Timelock contract is also included in SushiSwap.
The token allows delegating your voting power to some other trusted address. This address can then vote with increased power. Any time you may choose to re-delegate somewhere else.
4. SushiRoll (Migrator)

In the SushiRoll contract a migrator is provided, so people can easily move liquidity from Uniswap to SushiSwap.
With the migrate function, you essentially
- Remove liquidity from Uniswap.
- Add liquidity in SushiSwap.
Any potential leftover tokens from the token pair will be returned to the user.
function migrate(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
uint256 deadline
) external {
require(deadline >= block.timestamp, 'SushiSwap: EXPIRED');
// Remove liquidity from the old router with permit
(uint256 amountA, uint256 amountB) = removeLiquidity(
tokenA,
tokenB,
liquidity,
amountAMin,
amountBMin,
deadline
);
(uint256 pooledAmountA, uint256 pooledAmountB)
= addLiquidity(tokenA, tokenB, amountA, amountB);
if (amountA > pooledAmountA) {
IERC20(tokenA).safeTransfer(msg.sender, amountA - pooledAmountA);
}
if (amountB > pooledAmountB) {
IERC20(tokenB).safeTransfer(msg.sender, amountB - pooledAmountB);
}
}
5. MasterChef

The MasterChef enables the minting of new SUSHI token. It's the only way that SUSHI tokens are created. This is possible by staking LP tokens inside the MasterChef. The MasterChef is controlled by the owner which originally used to be Chef Nomi, but is since controlled by a 9 person multi-sig belonging to:
- SBF_Alameda (FTX CEO)
- Rleshner (Compound founder)
- 0xMaki (Sushiswap GM)
- Lawmaster (head of Research at The Block)
- CMsholdings (CMS Holdings)
- Mattysino (CEO of Sino Global Capital)
- mickhagen(Genesis Block founde)
- AdamScochran (partner at Cinneamhain Ventures)
- zippoxer (Zippo)
Eventually the plan is to move control of the MasterChef to governance. The owner has the power to control the allocations points from pools. What this means is the higher the allocation points of a liquidity pool, the more SUSHI one receives for staking its LP tokens. In the future this might create powerful control to create incentives for participating in special liquidity pools.
The owner can control pool allocations via the add
function:
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner;
updatePool
Ongoing pools can be updated and then mint SUSHI to the people staking the LP tokens using updatePool
.
The newly minted SUSHI amount per pool depends on the passed blocks since the last update and the set allocation points for the pool. (plus some extra multiplier left out for simplicity in the example on the right)
The calculated sushiReward is then distributed in 10% towards the dev address and the other 90% towards the pool LP stakers.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 sushiReward = sushiPerBlock
.mul(pool.allocPoint)
.div(totalAllocPoint);
sushi.mint(devaddr, sushiReward.div(10));
sushi.mint(address(this), sushiReward);
pool.accSushiPerShare = pool.accSushiPerShare.add(
sushiReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = block.number;
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount
.mul(pool.accSushiPerShare)
.div(1e12)
.sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount
.mul(pool.accSushiPerShare)
.div(1e12);
}
deposit
Using the deposit function users can stake their LP tokens for the provided pool. This will put the user's LP token into the MasterChef contract.
withdraw
Using the withdraw function users can unstake their LP tokens for the provided pool. In return they will
- receive their original LP tokens
- get their share of newly minted SUSHI tokens
The amount of minted SUSHI depends on the accSushiPerShare
computed previously (see updatePool).
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending =
user.amount
.mul(pool.accSushiPerShare)
.div(1e12)
.sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount
.mul(pool.accSushiPerShare)
.div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
The Sushi Future
Since the SushiSwap creator has since left the field, its future remains uncertain. The token itself maintained a very high market cap and future developments towards decentralized governance may drive SushiSwap further. On the other hand Uniswap v3 is on the horizon and that's certainly not the only competition for SushiSwap.
Solidity Developer
More great blog posts from Markus Waas
How to use ChatGPT with Solidity
Using the Solidity Scholar and other GPT tips
How to integrate Uniswap 4 and create custom hooks
Let's dive into Uniswap v4's new features and integration
How to integrate Wormhole in your smart contracts
Entering a New Era of Blockchain Interoperability
Solidity Deep Dive: New Opcode 'Prevrandao'
All you need to know about the latest opcode addition
How Ethereum scales with Arbitrum Nitro and how to use it
A blockchain on a blockchain deep dive
The Ultimate Merkle Tree Guide in Solidity
Everything you need to know about Merkle trees and their future
The New Decentralized The Graph Network
What are the new features and how to use it
zkSync Guide - The future of Ethereum scaling
How the zero-knowledge tech works and how to use it
Exploring the Openzeppelin CrossChain Functionality
What is the new CrossChain support and how can you use it.
Deploying Solidity Contracts in Hedera
What is Hedera and how can you use it.
Writing ERC-20 Tests in Solidity with Foundry
Blazing fast tests, no more BigNumber.js, only Solidity
ERC-4626: Extending ERC-20 for Interest Management
How the newly finalized standard works and can help you with Defi
Advancing the NFT standard: ERC721-Permit
And how to avoid the two step approve + transferFrom with ERC721-Permit (EIP-4494)
Moonbeam: The EVM of Polkadot
Deploying and onboarding users to Moonbeam or Moonriver
Advanced MultiSwap: How to better arbitrage with Solidity
Making multiple swaps across different decentralized exchanges in a single transaction
Deploying Solidity Smart Contracts to Solana
What is Solana and how can you deploy Solidity smart contracts to it?
Smock 2: The powerful mocking tool for Hardhat
Features of smock v2 and how to use them with examples
How to deploy on Evmos: The first EVM chain on Cosmos
Deploying and onboarding users to Evmos
EIP-2535: A standard for organizing and upgrading a modular smart contract system.
Multi-Facet Proxies for full control over your upgrades
MultiSwap: How to arbitrage with Solidity
Making multiple swaps across different decentralized exchanges in a single transaction
The latest tech for scaling your contracts: Optimism
How the blockchain on a blockchain works and how to use it
Ultimate Performance: The Aurora Layer2 Network
Deploying and onboarding users to the Aurora Network powered by NEAR Protocol
What is ecrecover in Solidity?
A dive into the waters of signatures for smart contracts
How to use Binance Smart Chain in your Dapp
Deploying and onboarding users to the Binance Smart Chain (BSC)
Using the new Uniswap v3 in your contracts
What's new in Uniswap v3 and how to integrate Uniswap v3
What's coming in the London Hardfork?
Looking at all the details of the upcoming fork
Welcome to the Matrix of blockchain
How to get alerted *before* getting hacked and prevent it
The Ultimate Ethereum Mainnet Deployment Guide
All you need to know to deploy to the Ethereum mainnet
Solidity Fast Track 2: Continue Learning Solidity Fast
Continuing to learn Solidity fast with the advanced basics
What's coming in the Berlin Hardfork?
Looking at all the details of the upcoming fork
Using 1inch ChiGas tokens to reduce transaction costs
What are gas tokens and example usage for Uniswap v2
Openzeppelin Contracts v4 in Review
Taking a look at the new Openzeppelin v4 Release
EIP-3156: Creating a standard for Flash Loans
A new standard for flash loans unifying the interface + wrappers for existing ecosystems
Tornado.cash: A story of anonymity and zk-SNARKs
What is Tornado.cash, how to use it and the future
High Stakes Roulette on Ethereum
Learn by Example: Building a secure High Stakes Roulette
How to implement generalized meta transactions
We'll explore a powerful design for meta transactions based on 0x
Utilizing Bitmaps to dramatically save on Gas
A simple pattern which can save you a lot of money
Using the new Uniswap v2 as oracle in your contracts
How does the Uniswap v2 oracle function and how to integrate with it
Smock: The powerful mocking tool for Hardhat
Features of smock and how to use them with examples
How to build and use ERC-721 tokens in 2021
An intro for devs to the uniquely identifying token standard and its future
Trustless token management with Set Protocol
How to integrate token sets in your contracts
Exploring the new Solidity 0.8 Release
And how to upgrade your contracts to Solidity 0.8
How to build and use ERC-1155 tokens
An intro to the new standard for having many tokens in one
Leveraging the power of Bitcoins with RSK
Learn how RSK works and how to deploy your smart contracts to it
Solidity Fast Track: Learn Solidity Fast
'Learn X in Y minutes' this time with X = Solidity 0.7 and Y = 20
Sourcify: The future of a Decentralized Etherscan
Learn how to use the new Sourcify infrastructure today
Integrating the 0x API into your contracts
How to automatically get the best prices via 0x
How to build and use ERC-777 tokens
An intro to the new upgraded standard for ERC-20 tokens
COMP Governance Explained
How Compound's Decentralized Governance is working under the hood
How to prevent stuck tokens in contracts
And other use cases for the popular EIP-165
Understanding the World of Automated Smart Contract Analyzers
What are the best tools today and how can you use them?
A Long Way To Go: On Gasless Tokens and ERC20-Permit
And how to avoid the two step approve + transferFrom with ERC20-Permit (EIP-2612)!
Smart Contract Testing with Waffle 3
What are the features of Waffle and how to use them.
How to use xDai in your Dapp
Deploying and onboarding users to xDai to avoid the high gas costs
Stack Too Deep
Three words of horror
Integrating the new Chainlink contracts
How to use the new price feeder oracles
TheGraph: Fixing the Web3 data querying
Why we need TheGraph and how to use it
Adding Typescript to Truffle and Buidler
How to use TypeChain to utilize the powers of Typescript in your project
Integrating Balancer in your contracts
What is Balancer and how to use it
Navigating the pitfalls of securely interacting with ERC20 tokens
Figuring out how to securely interact might be harder than you think
Why you should automatically generate interests from user funds
How to integrate Aave and similar systems in your contracts
How to use Polygon (Matic) in your Dapp
Deploying and onboarding users to Polygon to avoid the high gas costs
Migrating from Truffle to Buidler
And why you should probably keep both.
Contract factories and clones
How to deploy contracts within contracts as easily and gas-efficient as possible
How to use IPFS in your Dapp?
Using the interplanetary file system in your frontend and contracts
Downsizing contracts to fight the contract size limit
What can you do to prevent your contracts from getting too large?
Using EXTCODEHASH to secure your systems
How to safely integrate anyone's smart contract
Solidity and Truffle Continuous Integration Setup
How to setup Travis or Circle CI for Truffle testing along with useful plugins.
Upcoming Devcon 2021 and other events
The Ethereum Foundation just announced the next Devcon in 2021 in Colombia
The Year of the 20: Creating an ERC20 in 2020
How to use the latest and best tools to create an ERC-20 token contract
How to get a Solidity developer job?
There are many ways to get a Solidity job and it might be easier than you think!
Design Pattern Solidity: Mock contracts for testing
Why you should make fun of your contracts
Kickstart your Dapp frontend development with create-eth-app
An overview on how to use the app and its features
The big picture of Solidity and Blockchain development in 2020
Overview of the most important technologies, services and tools that you need to know
Design Pattern Solidity: Free up unused storage
Why you should clean up after yourself
How to setup Solidity Developer Environment on Windows
What you need to know about developing on Windows
Avoiding out of gas for Truffle tests
How you do not have to worry about gas in tests anymore
Design Pattern Solidity: Stages
How you can design stages in your contract
Web3 1.2.5: Revert reason strings
How to use the new feature
Gaining back control of the internet
How Ocelot is decentralizing cloud computing
Devcon 5 - Review
Impressions from the conference
Devcon 5 - Information, Events, Links, Telegram
What you need to know
Design Pattern Solidity: Off-chain beats on-chain
Why you should do as much as possible off-chain
Design Pattern Solidity: Initialize Contract after Deployment
How to use the Initializable pattern
Consensys Blockchain Jobs Report
What the current blockchain job market looks like
Provable — Randomness Oracle
How the Oraclize random number generator works
Solidity Design Patterns: Multiply before Dividing
Why the correct order matters!
Devcon 5 Applications closing in one week
Devcon 5 Applications closing
Randomness and the Blockchain
How to achieve secure randomness for Solidity smart contracts?