Reserves with Ganache

You are referring to the Legacy version of KyberSwap docs.

For the most updated information, please refer to:

Ganache enables you to create a private Ethereum blockchain on your local machine for running tests, executing commands, and inspecting its state while controlling how the chain operates. You can also refer to the Workshop repository for the same instructions.

Prerequisites

  1. Node and NPM latest LTS versions. Download from nodejs.org

  2. Ganache

Install the Ganache AppImage by downloading here https://truffleframework.com/ganache. To use the provided Ganache snapshot, install ganache-cli.

sudo npm install -g ganache-cli
  1. Truffle

Install the latest Truffle v5.

sudo npm install -g truffle@latest

Truffle v5.0 is needed in order to take advantage of new features, such as using async/await in the migration scripts. You can read more about the new features in the Truffle release page

  1. Install the rest of the NPM packages

npm install
  1. Clone the Kyber Workshop repository

Visit https://github.com/KyberNetwork/workshop and clone the repository to your local machine.

git clone git@github.com:KyberNetwork/workshop.git

Workshop Repository

Overview

workshop ├── config │ ├── network.json │ └── tokens.json ├── contracts │ ├── ConversionRatesInterface.sol │ ├── ConversionRates.sol │ ├── ERC20Interface.sol │ ├── examples │ │ ├── SwapEtherToToken.sol │ │ ├── SwapTokenToEther.sol │ │ └── SwapTokenToToken.sol │ │ └── Trade.sol │ ├── ExpectedRateInterface.sol │ ├── ExpectedRate.sol │ ├── FeeBurnerInterface.sol │ ├── FeeBurner.sol │ ├── KyberAutomatedReserve.sol │ ├── KyberNetworkInterface.sol │ ├── KyberNetworkProxyInterface.sol │ ├── KyberNetworkProxy.sol │ ├── KyberNetwork.sol │ ├── KyberOrderbookReserve.sol │ ├── KyberReserveInterface.sol │ ├── KyberReserve.sol │ ├── LiquidityConversionRates.sol │ ├── LiquidityFormula.sol │ ├── Migrations.sol │ ├── mockTokens │ │ ├── KyberGenesisToken.sol │ │ ├── KyberNetworkCrystal.sol │ │ ├── Mana.sol │ │ ├── OmiseGo.sol │ │ ├── Polymath.sol │ │ ├── Salt.sol │ │ ├── Status.sol │ │ └── Zilliqa.sol │ ├── PermissionGroups.sol │ ├── permissionless │ │ ├── OrderbookReserveInterface.sol │ │ ├── OrderbookReserve.sol │ │ ├── OrderIdManager.sol │ │ ├── OrderListFactoryInterface.sol │ │ ├── OrderListFactory.sol │ │ ├── OrderListInterface.sol │ │ ├── OrderList.sol │ │ └── PermissionlessOrderbookReserveLister.sol │ ├── SanityRatesInterface.sol │ ├── SanityRates.sol │ ├── SimpleNetworkInterface.sol │ ├── Utils2.sol │ ├── Utils.sol │ ├── VolumeImbalanceRecorder.sol │ ├── WhiteListInterface.sol │ ├── WhiteList.sol │ └── Withdrawable.sol ├── db ├── examples │ ├── solidity │ │ ├── SwapEtherToToken.sol -> ../../contracts/examples/SwapEtherToToken.sol │ │ ├── SwapTokenToEther.sol -> ../../contracts/examples/SwapTokenToEther.sol │ │ └── SwapTokenToToken.sol -> ../../contracts/examples/SwapTokenToToken.sol │ │ └── Trade.sol -> ../../contracts/examples/Trade.sol │ ├── truffle │ │ ├── getExpectedRate.js │ │ ├── swapEtherToToken.js │ │ ├── swapTokenToEther.js │ │ ├── swapTokenToToken.js │ │ └── trade.js │ └── web3 │ ├── abi │ │ ├── KyberNetworkProxy.abi │ │ ├── KNC.abi │ │ ├── OMG.abi │ │ ├── MANA.abi │ │ ├── SALT.abi │ │ └── ZIL.abi │ ├── getExpectedRate.js │ ├── swapEtherToToken.js │ ├── swapTokenToEther.js │ └── swapTokenToToken.js ├── LICENSE ├── migrations │ ├── 1_initial_migration.js │ ├── 2_deploy_tokens.js │ ├── 3_deploy_contracts.js │ ├── 4_setup_permissions.js │ ├── 5_setup_KyberNetworkProxy.js │ ├── 6_setup_KyberReserve.js │ ├── 7_setup_KyberAutomatedReserve.js │ ├── 8_setup_KyberOrderbookReserve.js │ ├── 9_setup_FeeBurner.js │ ├── 10_setup_ExpectedRate.js │ ├── 11_setup_ConversionRates.js │ ├── 12_setup_LiquidityConversionRates.js │ ├── 13_setup_SanityRates.js │ ├── 14_setup_WhiteList.js │ ├── 15_setup_KyberNetwork.js │ ├── 16_add_PermissionlessOrderbookReserve.js │ ├── 17_transfer_tokens.js │ └── 18_deployment_summary.js ├── package.json ├── README.md ├── scripts │ ├── get_liquidity_params.py │ └── liquidity_input_params.json └── truffle.js

Directory Details

config - contains JSON files that hold configuration details of the Kyber contracts used for migrations contracts - contains all the Kyber contracts, plus some mock tokens and solidity examples for testing examples - contains truffle and web3 example scripts to interact with Kyber's smart contracts, and also contains solidity examples for Kyber contract interactions migrations - contains the truffle migration scripts to deploy and setup the Kyber contracts in a test environment

Interacting with the Kyber contracts locally

1A. Run Ganache with local snapshot

A Ganache snapshot has already been pre-made with the Kyber contracts deployed. You can immediately interact with the contracts without having to do migrations. The snapshot is stored in db folder.

We use the mnemonic gesture rather obey video awake genuine patient base soon parrot upset lounge for the accounts. The user wallet (0x47a793D7D0AA5727095c3Fe132a6c1A46804c8D2) already contains some ETH and test ERC20 tokens.

NOTE: The mnemonic provided is used only for testing. DO NOT use the accounts generated for your own personal use in mainnet, as you can potentially lose those funds.

To run the snapshot locally, run the command:

cd <PATH>/workshop
ganache-cli --db db --accounts 10 --defaultBalanceEther 1000 --mnemonic 'gesture rather obey video awake genuine patient base soon parrot upset lounge' --networkId 5777 --debug

1B. Run Ganache and deploy the Kyber contracts from scratch

If you wish to deploy the Kyber contracts yourself, you can run the following commands:

Run ganache-cli in one terminal session

ganache-cli --accounts 10 --defaultBalanceEther 1000 --mnemonic 'gesture rather obey video awake genuine patient base soon parrot upset lounge' --networkId 5777 --debug

In a new terminal session, connect to the ganache network, and run the truffle migration scripts

truffle migrate --network development

2. Running the example scripts

You can directly interact with the Kyber contracts on the Ganache network. We have provided some example scripts in the example directory.

For the Truffle examples:

truffle exec examples/truffle/<SCRIPT>

e.g.

truffle exec examples/truffle/swapEtherToToken.js

For the Web3 examples:

cd examples/web3
node <SCRIPT>

e.g.

cd examples/web3/
node swapEtherToToken.js

For the Solidity examples, they are already deployed in the Ganache network using the Truffle migration scripts. You can interact with the Solidity examples using truffle console, or write your own Truffle/Web3 scripts to interact with the Solidity example contracts.

Ganache network details

Network

development

Permissions

Wallets

Tokens

Contracts

NOTE: The KyberReserve and KyberAutomatedReserve as well as the KyberOrderbookReserve and OrderbookReserve are the same contracts. A duplicate was made as a workaround due to a limitation of Truffle where only one instance of a contract can be migrated. Kyber has three types of reserves, the Fed Price Reserve, Automated Price Reserve, and Orderbook Reserve, which you can read more about here.

How to add a new ERC20 token with rates for initial migration

Fed Price Reserve

1. Create your ERC20 token contract

Create your ERC20 token contract in contracts/mockTokens. You can duplicate any of the existing mock tokens and modify the token name, symbol, and total supply

2. Set the minimalRecordResolution, maxPerBlockImbalance, and maxTotalImbalance of each defined token in the tokens.json config file

In config/tokens.json, under the FedPriceReserve section, define the minimalRecordResolution, maxPerBlockImbalance and maxTotalImbalance of each defined token (replace NEW with the token symbol).

These 3 fields are explained below:

"FedPriceReserve": {
  "NEW": {
    "minimalRecordResolution" : "1000000000000000",
    "maxPerBlockImbalance" : "9078768104330450960384",
    "maxTotalImbalance" : "57896044618658097711785492504343953926634992332820282019728792003956564819968"
  }
}

Next, add the desired conversion rates of each defined token with respect to ETH, defined with baseBuy and baseSell. Conversion rate sets the basic rate per token, and is set separately for buy and sell values.

For bytes14Buy and bytes14Sell, for simplicity, assume that we want to modify the base buy rates. The logic for modifying base sell rates is the same.

Suppose the reserve supports 3 tokens: DAI, BAT, and DGX. We want to make the following modifications to their base buy rates:

  • +2.5% (+25 pts) to DAI_BASE_BUY_RATE

  • +1% (+10 pts) to BAT_BASE_BUY_RATE

  • -3% (-30 pts) to DGX_BASE_BUY_RATE

Note:

One pt here means a 0.1% change, as compared to basis points used in step functions where 1 basis point = 0.01%. The range which compact data can handle is from -12.8% to 12.7%. This gives us the buy array [25,10,-30]. Encoding this to hex yields [0x190ae2]. But for simplicity sake, we can set this to 0x0000000000000000000000000000.

"FedPriceReserve": {
  "NEW": {
    "minimalRecordResolution" : "1000000000000000",
    "maxPerBlockImbalance" : "9078768104330450960384",
    "maxTotalImbalance" : "57896044618658097711785492504343953926634992332820282019728792003956564819968",
    "baseBuy": "549000000000000000000",
    "baseSell": "1813123931381047",
    "bytes14Buy": "0x0000000000000000000000000000",
    "bytes14Sell": "0x0000000000000000000000000000"
  }
}

Lastly, add the sanity rate for each token you define. The sanity rates defined protect your reserve from large inconsistencies between the sanity rates and the actual rates.

You should have the final definition of a token below:

"FedPriceReserve": {
  "NEW": {
    "minimalRecordResolution" : "1000000000000000",
    "maxPerBlockImbalance" : "9078768104330450960384",
    "maxTotalImbalance" : "57896044618658097711785492504343953926634992332820282019728792003956564819968",
    "baseBuy": "549000000000000000000",
    "baseSell": "1813123931381047",
    "bytes14Buy": "0x0000000000000000000000000000",
    "bytes14Sell": "0x0000000000000000000000000000",
    "sanityRate": "1840144285714286"
  }
}

You can read more about these fields in the Fed Price Reserve guide.

3. Run the Truffle migration

With Ganache running, execute:

truffle migrate --network development --reset

Automated Price Reserve

1. Create your ERC20 token contract

Create your ERC20 token contract in contracts/mockTokens. You can duplicate any of the existing mock tokens and modify the token name, symbol, and total supply.

2. Defining the liquidity parameters of the token

Modify the file config/tokens.json and add the new token section (replace NEW with the token symbol) for the different properties.

{
  "AutomatedReserve": {
    "NEW": {
      "_rInFp": "10995116277",
      "_pMinInFp": "27487790",
      "_numFpBits": "40",
      "_maxCapBuyInWei": "5000000000000000000",
      "_maxCapSellInWei": "5000000000000000000",
      "_feeInBps": "25",
      "_maxTokenToEthRateInPrecision": "100000000000000",
      "_minTokenToEthRateInPrecision": "25000000000000",
      "Ether": "100",
      "Tokens": "2000000"
    }
  }
}

AutomatedReserve.Token

The function that will be invoked to set liquidity parameters is:

function setLiquidityParams(uint _rInFp, uint _pMinInFp, uint _numFpBits, uint _maxCapBuyInWei, uint _maxCapSellInWei, uint _feeInBps, uint _maxTokenToEthRateInPrecision, uint _minTokenToEthRateInPrecision) public onlyAdmin

The reserve manager needs to only decide on the initial liquidity parameters of the automated reserve. Specifically, the following information need to be considered and to calculate the parameters above:

  1. Liquidity Rate

  2. Initial Token Price

  3. Initial Ether Amount

  4. Initial Token Amount

  5. Minimum and Maximum Supported Price Factor

  6. Maximum Buy and Maximum Sell Amount in a Trade

  7. Fee Percentage

There are several things to take note of in the list of parameters.

First, notice that some parameters will have the InFp suffix. InFp refers to formula precision. While this is configurable, 2^40 is the recommended value.

Second, r is liquidity the rate in basis points or units of 100 which the price should move each time the ETH/token inventory changes in 1 ETH worth of quantity. For an r of 0.01, the price will move 1%. r is calculated taking into account the amount of initial ETH and tokens deposited into the contract, and the desired minimum/maximum price factor ratio. A smaller r also means more ETH and token inventory is needed to facilitate the liquidity.

For the minimum/maximum supported price factor ratio, it is recommended to start with a ratio of 0.5:2.0. This indicates that the inventory will suffice for up to 100% increase or 50% decrease in token price with respect to ETH.

Example

Now, Let's assume we want to list a token with the following considerations:

  1. Liquidity Rate – 0.01 (1%)

  2. Initial Token Price – 1 token = 0.00005 ETH

  3. Initial Ether Amount – 100 ETH

  4. Initial Token Amount – 2,000,000 tokens (100 ETH worth)

  5. Minimum (pMin) and Maximum (pMax) Supported Price Factor – 0.5:2.0

  6. Maximum Buy and Maximum Sell Amount in a Trade – 5 ETH max buy and sell cap

  7. Fee Percentage – 0.25%

Below, we will calculate the different parameters.

Using get_liquidity_params.py Python script

A Python script, located in scripts/get_liquidity_params.py in the smart-contracts repository, will help you calculate the liquidity parameters. Edit the input file liquidity_input_params.json, and specify the inputs similar to the considerations in the example above.

{
  "liquidity_rate": 0.01,
  "initial_ether_amount": 100.0,
  "initial_token_amount": 2000000,
  "initial_price": 0.00005,
  "min_supported_price_factor": 0.5,
  "max_supported_price_factor": 2.0,
  "max_tx_buy_amount_eth": 5.0,
  "max_tx_sell_amount_eth": 5.0,
  "fee_percent": 0.25,
  "formula_precision_bits": 40
}

Please note that the formula_precision_bits refers to _numFpBits, which the recommended value is 40.

Afterwards, just execute the Python script, using the following command:

python3 get_liquidity_params.py --input liquidity_input_params.json --get params

It should give the following output:

_rInFp: 10995116277
_pMinInFp: 27487790
_numFpBits: 40
_maxCapBuyInWei: 5000000000000000000
_maxCapSellInWei: 5000000000000000000
_feeInBps: 25
_maxTokenToEthRateInPrecision: 100000000000000
_minTokenToEthRateInPrecision: 25000000000000

3. Run the Truffle migration

With Ganache running, execute:

truffle migrate --network development --reset

Orderbook Reserve

1. Create your ERC20 token contract

Create your ERC20 token contract in contracts/mockTokens. You can duplicate any of the existing mock tokens and modify the token name, symbol, and total supply.

2. Set the price of USD per ETH

In config/network.json, under the MockMedianizer section, add the USD price per ETH.

"MockMedianizer": {
  "DollarPerETH": 150
}

3. Set the minimum USD price for new orders, maximum orders to traverse per trade, and fees

In config/tokens.json, under the PermissionedOrderbookReserve section, add the new token section (replace NEW with the token symbol) for the different properties.

"PermissionedOrderbookReserve": {
  "NEW": {
    "minNewOrderUsd": 1000,
    "maxOrdersPerTrade": 5,
    "burnFeeBps": 25,
    (...)
  }
}

These 3 fields are explained below:

3. Set the initial limit order to the Orderbook Reserve

In config/tokens.json, under the PermissionedOrderbookReserve section, modify the new token section (replace NEW with the token symbol), as specified in Step 2 above, and indicate the different properties.

"PermissionedOrderbookReserve": {
  "NEW": {
    (...)
    "KNCStake": "1000",
    "ETHDeposit": "25",
    "TokenDeposit": "150000",
    "ETHSell": "10",
    "TokenBuy": "12450",
    "ETHBuy": "10",
    "TokenSell": "12400"
  }
}

These 7 fields are explained below:

4. Run the Truffle migration

With Ganache running, execute:

truffle migrate --network development --reset

Disclaimer

Code snippets in this guide are just examples and you should always do your own testing. If you have questions, visit our https://t.me/KyberDeveloper.

Last updated