Skip to content

Commit 117f6ff

Browse files
manhlx3006AnyhowclickilanDoron
committed
Kyber Bancor bridge reserve (#546)
* Shifted arbitrage check to FeeBurner * Shifted relevant tests from expectedRate to feeBurner * Modified failing test, as it requires less gas to fail * Removed redundan >0 rate check, test for feeBurner * Added test for src==dest token * Istanbul fix, zero rate handling * Arbitrage check shifted to FeeBurner (#433) * Shifted arbitrage check to FeeBurner * Shifted relevant tests from expectedRate to feeBurner * Modified failing test, as it requires less gas to fail * Removed redundan >0 rate check, test for feeBurner * Added test for src==dest token * Revert "Merge branch 'clicky/zero_rate' into development" This reverts commit 795d2f1, reversing changes made to 80af391. * Clicky/buidl integration (#459) * Pulling stuff from KN/clicky/buidl-integration branch * Pull changes from expected rate and fee burner * Update kyberNetwork test file * Update kyberNetwork.js * Merge Mike's PR on enhanced step functions (#458) * [WIP] Add new conversion rate contract with step function enhancement (#416) * [WIP] Add new conversion rate contract with step function enhancement * Add more tests to kyberReserve for testing new conversion rate contract * Add more tests for kybetNetwork with new conversion rate contract * Add verify qty and imbalance step function amounts must be increasing * Add case set qty and balance step func with only one or zero element * Check for qty step function all amounts are non negative * Update conversion rate contract and kyber network tests * Fallback to old logics when qty is 0 * Update new conversion rate with inherite from old one, update logics for some edge cases and tests * Fixed typo * Add check for empty step function before executing step function * Fix issue when qty is negative and greater than all step qty * Fix issue with executing step func with 0 as qty (#417) * Remove unnecessary tests in conversionRate2, add more cases to test for new execute step function * Fix issue with execute step func for 0 qty * expose getImbalance function in conversionRate2.sol file (#419) * Update conversion rate contract 2 with new logics for executing step function * Resolve some comments, change name new conversion rates contract to EnhancedStepFunctions * Remove qty step function, compress data for imbalance steps * Resolve solhint max line length * Avoid modifying function params in execute step func * Update comments for each test case of getting correct bps for step func * Update with some comments, add more tests * Add await keyword * Update some comments, fix some old tests in kyber reserve * Fix wrong calculate imbalance of token in reserve test * Change default max imbalance to return when overflow, fix some tests with missing await keyword * Blocking setting qty step function in new conversion rate * Update execute step func with blocking rate, remove updatedRateBlock in getImbalance * Remove redundant stepX value in last step * Add check data when encoding step func, using MAX_VAL as default for last step X * Add checking for max value of step X and tests * Add check for max bps adjustment, check max_imbalance value test * Fixed Failing Tests (#462) * Istanbul fix * Fixed failing tests as per Ilan's feedback * Fixed failing tests * Minor fixes * Minor fixes * Sync enhanced step functions test file * Reduce getDecimals call in findBestRateTokenToToken in network contract (#467) * Reduce getDecimals call in findBestRateTokenToToken in network contract * Fix new line end file * Remove some tests in utils3 * Avoid decimals call when calling handleFees on FeeBurner (#468) * Ilan/merge master (#460) * reserve deployment scripts (#233) * reserve deployment scripts * read valid block duration from config file. (#423) * Weth Reserve Implementation (#304) * Weth Reserve Implementation Includes testing. Also includes an addition in helper to make throw catching more neat. * Add weth reserve test * Add deploy script for oasis reserve * Organize folder structure and update WrapConversionRate.sol #441 && #452 (#453) * Organize folder structure according to issue #441 this includes organizing audit folder and organizing reserves. Remove multisig support from WrapConversionRate.sol according to issue #452 * enable admin to call transfer admin of base contract * enable wrapConversionRate to control all adminOnly functions in conversionRate (#461) * Ilan/modify wrap conversion rate (#466) * enable wrapConversionRate to control all adminOnly functions in conversionRate * enable wrap conversion rate to control all admin functions in conversion rate contract * set admin as msg.sender. to follow base contract logic * remove redundant test. adopt to chainge in admin logic * add CR LF * rename folders. (#469) * rename folders. (remove contract from folder name.) * reset package - lock * move new mock contracts to mock folder. * create web3 object * Upgraded to ganache-cli@istanbul * Removed header * Istanbul fix (#457) * Return zero rate for same src and dest token (#475) * Return zero rate for same src & dest token * Removed unnecessary tests * Echo fork choice, fix broken logic * Try committing new package-lock.json * Added more info * Bumped to node v12.13.0 * Update package fix npm (#474) * Update package fix npm * Update package-lock file * Remove unused packages * Removed eslint * Add colour for better readability of fork choice * Add spacing between example commands * Resolve package-lock conflict * Revert "Bumped to node v12.13.0" This reverts commit 85cb734. * Fixed conflicting files * Revert "Merge branch 'clicky/ganacheIstanbul' into development" This reverts commit 654a1c3, reversing changes made to 6c0a21c. * Upgrade to ganache-cli@istanbul for testing with Istanbul fork (#482) * Added colour and newline to fork choice * Add node and npm version used * Removed eslint * Removed eslint * Got latest changes from Mike's PR * added colour and newline to fork choice * Fix coloring (I hope) * Changed BG to make text stand out * handle zero qty in get rate permission less reserve (#472) * handle zero qty in get rate permission less reserve * undo wrong change * Increase gas limit for 1 test due to Istanbul (#487) * [455] Enable unlist orderbook permissionless reserve (#485) * Add comments in FeeBurner for KNC decimals (#489) * Revert "Arbitrage check shifted to FeeBurner" (#488) * Revert "Arbitrage check shifted to FeeBurner (#433)" This reverts commit 80af391. * reverse un needed test changes for kyber NEtwork * Zero Src Qty Handling (#483) * Initial commit for zero rate handling. Need to rewrite tests * Improved comment to code * Modified getConversionRate function to require srcAmt > 0 * Removed tests, added one * Updated contracts as per feedback * Updated comment in test file * Added fix to expectedRateSmallQty * Remove extra = * Add additional section to check network.getExpectedRate doesn't revert as well * Removed redundant tests due to zero rate handling in network contract (#494) * update solidity coverage version (#491) * Added new deployment script and input files (#495) * Ilan/add rates getter (#493) * update solidity coverage version * add getter function for rates * update getter API and return values, add tests * Clicky/rename compile file (#496) * renamed compileOutput.js to compileContracts.js, added more contracts for reserveDeployer * Renamed compileOutput -> compileContracts * Minor spelling edit * update addresses for deployment (#497) * remove multi sig support. add admin functionality (#498) * remove multi sig support. add admin functionality * refactor wrapper contracts, update tests * update tests according to PR comments, add one missing check * Add some comments * Revert "[455] Enable unlist orderbook permissionless reserve (#485)" (#504) This reverts commit 8b63c0e. * Fix deployment script after staging deployment (#505) * Added new deployment script and input files * Remove old file * Added contract instantiation if deployer script breaks halfway through * avoid query to uniswap with zero rate (#510) * avoid query to uniswap with zero rate * test situation where trade result is 0 * enable setting min record resultion in conversion rates using wrapper (#513) * enable setting min record resultion in conversion rates using wrapper * linting, and add missing test * fix uniswap bridge for small amounts src qty (1) (#518) * fix uniswap bridge for smal amounts src qty (1) * avoid reading fee twice * fix uniswap deployer script * Ilan/deployment helper (#516) * some deployment changes, and helper contract" " * add kyber uniswap bridge to compilation. remove wrap conversion rate * small fixes in deployer * Add CR LF * Ilan/merge master (#519) * update some packages. fix solc version to 0.4.18 (#503) * fixed FPR deployment script (#508) * add smartdec audit for APR * use correct package-lock * Ilan/master to development (#525) * Development to Master. Istanbul changes. buidl. (#471) * Shifted arbitrage check to FeeBurner * Shifted relevant tests from expectedRate to feeBurner * Modified failing test, as it requires less gas to fail * Removed redundan >0 rate check, test for feeBurner * Added test for src==dest token * Istanbul fix, zero rate handling * Arbitrage check shifted to FeeBurner (#433) * Shifted arbitrage check to FeeBurner * Shifted relevant tests from expectedRate to feeBurner * Modified failing test, as it requires less gas to fail * Removed redundan >0 rate check, test for feeBurner * Added test for src==dest token * Revert "Merge branch 'clicky/zero_rate' into development" This reverts commit 795d2f1, reversing changes made to 80af391. * Clicky/buidl integration (#459) * Pulling stuff from KN/clicky/buidl-integration branch * Pull changes from expected rate and fee burner * Update kyberNetwork test file * Update kyberNetwork.js * Merge Mike's PR on enhanced step functions (#458) * [WIP] Add new conversion rate contract with step function enhancement (#416) * [WIP] Add new conversion rate contract with step function enhancement * Add more tests to kyberReserve for testing new conversion rate contract * Add more tests for kybetNetwork with new conversion rate contract * Add verify qty and imbalance step function amounts must be increasing * Add case set qty and balance step func with only one or zero element * Check for qty step function all amounts are non negative * Update conversion rate contract and kyber network tests * Fallback to old logics when qty is 0 * Update new conversion rate with inherite from old one, update logics for some edge cases and tests * Fixed typo * Add check for empty step function before executing step function * Fix issue when qty is negative and greater than all step qty * Fix issue with executing step func with 0 as qty (#417) * Remove unnecessary tests in conversionRate2, add more cases to test for new execute step function * Fix issue with execute step func for 0 qty * expose getImbalance function in conversionRate2.sol file (#419) * Update conversion rate contract 2 with new logics for executing step function * Resolve some comments, change name new conversion rates contract to EnhancedStepFunctions * Remove qty step function, compress data for imbalance steps * Resolve solhint max line length * Avoid modifying function params in execute step func * Update comments for each test case of getting correct bps for step func * Update with some comments, add more tests * Add await keyword * Update some comments, fix some old tests in kyber reserve * Fix wrong calculate imbalance of token in reserve test * Change default max imbalance to return when overflow, fix some tests with missing await keyword * Blocking setting qty step function in new conversion rate * Update execute step func with blocking rate, remove updatedRateBlock in getImbalance * Remove redundant stepX value in last step * Add check data when encoding step func, using MAX_VAL as default for last step X * Add checking for max value of step X and tests * Add check for max bps adjustment, check max_imbalance value test * Fixed Failing Tests (#462) * Istanbul fix * Fixed failing tests as per Ilan's feedback * Fixed failing tests * Minor fixes * Minor fixes * Sync enhanced step functions test file * Reduce getDecimals call in findBestRateTokenToToken in network contract (#467) * Reduce getDecimals call in findBestRateTokenToToken in network contract * Fix new line end file * Remove some tests in utils3 * Avoid decimals call when calling handleFees on FeeBurner (#468) * Ilan/merge master (#460) * reserve deployment scripts (#233) * reserve deployment scripts * read valid block duration from config file. (#423) * Weth Reserve Implementation (#304) * Weth Reserve Implementation Includes testing. Also includes an addition in helper to make throw catching more neat. * Add weth reserve test * Add deploy script for oasis reserve * Organize folder structure and update WrapConversionRate.sol #441 && #452 (#453) * Organize folder structure according to issue #441 this includes organizing audit folder and organizing reserves. Remove multisig support from WrapConversionRate.sol according to issue #452 * enable admin to call transfer admin of base contract * enable wrapConversionRate to control all adminOnly functions in conversionRate (#461) * Ilan/modify wrap conversion rate (#466) * enable wrapConversionRate to control all adminOnly functions in conversionRate * enable wrap conversion rate to control all admin functions in conversion rate contract * set admin as msg.sender. to follow base contract logic * remove redundant test. adopt to chainge in admin logic * add CR LF * rename folders. (#469) * rename folders. (remove contract from folder name.) * reset package - lock * move new mock contracts to mock folder. * create web3 object * Upgraded to ganache-cli@istanbul * Removed header * Istanbul fix (#457) * Return zero rate for same src and dest token (#475) * Return zero rate for same src & dest token * Removed unnecessary tests * Echo fork choice, fix broken logic * Try committing new package-lock.json * Added more info * Bumped to node v12.13.0 * Update package fix npm (#474) * Update package fix npm * Update package-lock file * Remove unused packages * Removed eslint * Add colour for better readability of fork choice * Add spacing between example commands * Resolve package-lock conflict * Revert "Bumped to node v12.13.0" This reverts commit 85cb734. * Fixed conflicting files * Revert "Merge branch 'clicky/ganacheIstanbul' into development" This reverts commit 654a1c3, reversing changes made to 6c0a21c. * Upgrade to ganache-cli@istanbul for testing with Istanbul fork (#482) * Added colour and newline to fork choice * Add node and npm version used * Removed eslint * Removed eslint * Got latest changes from Mike's PR * added colour and newline to fork choice * Fix coloring (I hope) * Changed BG to make text stand out * handle zero qty in get rate permission less reserve (#472) * handle zero qty in get rate permission less reserve * undo wrong change * Increase gas limit for 1 test due to Istanbul (#487) * [455] Enable unlist orderbook permissionless reserve (#485) * Add comments in FeeBurner for KNC decimals (#489) * Revert "Arbitrage check shifted to FeeBurner" (#488) * Revert "Arbitrage check shifted to FeeBurner (#433)" This reverts commit 80af391. * reverse un needed test changes for kyber NEtwork * Zero Src Qty Handling (#483) * Initial commit for zero rate handling. Need to rewrite tests * Improved comment to code * Modified getConversionRate function to require srcAmt > 0 * Removed tests, added one * Updated contracts as per feedback * Updated comment in test file * Added fix to expectedRateSmallQty * Remove extra = * Add additional section to check network.getExpectedRate doesn't revert as well * Removed redundant tests due to zero rate handling in network contract (#494) * update solidity coverage version (#491) * Added new deployment script and input files (#495) * Ilan/add rates getter (#493) * update solidity coverage version * add getter function for rates * update getter API and return values, add tests * Clicky/rename compile file (#496) * renamed compileOutput.js to compileContracts.js, added more contracts for reserveDeployer * Renamed compileOutput -> compileContracts * Minor spelling edit * update addresses for deployment (#497) * remove multi sig support. add admin functionality (#498) * remove multi sig support. add admin functionality * refactor wrapper contracts, update tests * update tests according to PR comments, add one missing check * Add some comments * Revert "[455] Enable unlist orderbook permissionless reserve (#485)" (#504) This reverts commit 8b63c0e. * Fix deployment script after staging deployment (#505) * Added new deployment script and input files * Remove old file * Added contract instantiation if deployer script breaks halfway through * avoid query to uniswap with zero rate (#510) * avoid query to uniswap with zero rate * test situation where trade result is 0 * enable setting min record resultion in conversion rates using wrapper (#513) * enable setting min record resultion in conversion rates using wrapper * linting, and add missing test * fix uniswap bridge for small amounts src qty (1) (#518) * fix uniswap bridge for smal amounts src qty (1) * avoid reading fee twice * fix uniswap deployer script * Ilan/deployment helper (#516) * some deployment changes, and helper contract" " * add kyber uniswap bridge to compilation. remove wrap conversion rate * small fixes in deployer * Add CR LF * Ilan/merge master (#519) * update some packages. fix solc version to 0.4.18 (#503) * fixed FPR deployment script (#508) * add smartdec audit for APR * use correct package-lock * Add Eth2Dai reserve and test (#523) * [WIP] Eth2Dai Reserve enhancement (#449) * Add eth2dai contract * Update Eth2Dai reserve * Update Eth2DaiReserve contract and tests * Update trade function tests for eth2dai reserve * Make single test can run on its own * Separate source codes, add some v5 contracts * Update contracts fixed some review comments, remove some unused functions * Update eth2dai contract with enable/disable internal inventory for token * Add test for set internal inventory enable/disable * Put enable/disable internal inventory into internal inventory data * Add internal inventory tests * Change overlow to out of range * Update v5 contracts * Update file name and folder structure * Update folder structure * Fix can not find artifacts for WethTokenV5 * Update test folder structure * Remove KyberOasisReserve source code + test, change WethTokenV5 to WethToken (#524) * remove duplicate files and v5 example * Add KyberBancorReserve and test * Fix some tests for kyber bancor reserve * Add more tests for kyber bancor reserve * Remove default value for bnt and bancor eth token * Add end of file line * Update contracts from review comments * Fix contract and test based on comments * Return 0 for rate and revert in trade when srcQty is 0 * Remove v5 example test file' Co-authored-by: Desmond <[email protected]> Co-authored-by: Ilan Doron <[email protected]>
1 parent 5c4c244 commit 117f6ff

File tree

4 files changed

+937
-0
lines changed

4 files changed

+937
-0
lines changed
Lines changed: 234 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,234 @@
1+
pragma solidity 0.5.11;
2+
3+
import "../../IERC20.sol";
4+
import "../../IKyberReserve.sol";
5+
import "../../WithdrawableV5.sol";
6+
import "../../UtilsV5.sol";
7+
import "./mock/IBancorNetwork.sol";
8+
9+
contract KyberBancorReserve is IKyberReserve, Withdrawable, Utils {
10+
11+
uint constant internal BPS = 10000; // 10^4
12+
uint constant ETH_BNT_DECIMALS = 18;
13+
14+
address public kyberNetwork;
15+
bool public tradeEnabled;
16+
uint public feeBps;
17+
18+
IBancorNetwork public bancorNetwork; // 0x0e936B11c2e7b601055e58c7E32417187aF4de4a
19+
20+
IERC20 public bancorEth; // 0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315
21+
IERC20 public bancorToken; // 0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C
22+
23+
constructor(
24+
address _bancorNetwork,
25+
address _kyberNetwork,
26+
uint _feeBps,
27+
address _bancorEth,
28+
address _bancorToken,
29+
address _admin
30+
)
31+
public
32+
{
33+
require(_bancorNetwork != address(0), "constructor: bancorNetwork address is missing");
34+
require(_kyberNetwork != address(0), "constructor: kyberNetwork address is missing");
35+
require(_bancorEth != address(0), "constructor: bancorEth address is missing");
36+
require(_bancorToken != address(0), "constructor: bancorToken address is missing");
37+
require(_admin != address(0), "constructor: admin address is missing");
38+
require(_feeBps < BPS, "constructor: fee is too big");
39+
40+
bancorNetwork = IBancorNetwork(_bancorNetwork);
41+
bancorToken = IERC20(_bancorToken);
42+
bancorEth = IERC20(_bancorEth);
43+
44+
kyberNetwork = _kyberNetwork;
45+
feeBps = _feeBps;
46+
admin = _admin;
47+
tradeEnabled = true;
48+
49+
require(bancorToken.approve(address(bancorNetwork), 2 ** 255));
50+
}
51+
52+
function() external payable { }
53+
54+
function getConversionRate(IERC20 src, IERC20 dest, uint srcQty, uint) public view returns(uint) {
55+
if (!tradeEnabled) { return 0; }
56+
if (srcQty == 0) { return 0; }
57+
58+
if (src != ETH_TOKEN_ADDRESS && dest != ETH_TOKEN_ADDRESS) {
59+
return 0; // either src or dest must be ETH
60+
}
61+
IERC20 token = src == ETH_TOKEN_ADDRESS ? dest : src;
62+
if (token != bancorToken) { return 0; } // not BNT token
63+
64+
IERC20[] memory path = getConversionPath(src, dest);
65+
66+
uint destQty;
67+
(destQty, ) = bancorNetwork.getReturnByPath(path, srcQty);
68+
69+
// src and dest can be only BNT or ETH
70+
uint rate = calcRateFromQty(srcQty, destQty, ETH_BNT_DECIMALS, ETH_BNT_DECIMALS);
71+
72+
rate = valueAfterReducingFee(rate);
73+
74+
return rate;
75+
}
76+
77+
event TradeExecute(
78+
address indexed sender,
79+
address src,
80+
uint srcAmount,
81+
address destToken,
82+
uint destAmount,
83+
address payable destAddress
84+
);
85+
86+
function trade(
87+
IERC20 srcToken,
88+
uint srcAmount,
89+
IERC20 destToken,
90+
address payable destAddress,
91+
uint conversionRate,
92+
bool validate
93+
)
94+
public
95+
payable
96+
returns(bool)
97+
{
98+
99+
require(tradeEnabled, "trade: trade is not enabled");
100+
require(msg.sender == kyberNetwork, "trade: sender is not network");
101+
require(srcAmount > 0, "trade: src amount must be greater than 0");
102+
require(srcToken == ETH_TOKEN_ADDRESS || destToken == ETH_TOKEN_ADDRESS, "trade: src or dest must be ETH");
103+
require(srcToken == bancorToken || destToken == bancorToken, "trade: src or dest must be BNT");
104+
105+
require(doTrade(srcToken, srcAmount, destToken, destAddress, conversionRate, validate), "trade: doTrade function returns false");
106+
107+
return true;
108+
}
109+
110+
event KyberNetworkSet(address kyberNetwork);
111+
112+
function setKyberNetwork(address _kyberNetwork) public onlyAdmin {
113+
require(_kyberNetwork != address(0), "setKyberNetwork: kyberNetwork address is missing");
114+
115+
kyberNetwork = _kyberNetwork;
116+
emit KyberNetworkSet(_kyberNetwork);
117+
}
118+
119+
event BancorNetworkSet(address _bancorNetwork);
120+
121+
function setBancorContract(address _bancorNetwork) public onlyAdmin {
122+
require(_bancorNetwork != address(0), "setBancorContract: bancorNetwork address is missing");
123+
124+
if (address(bancorNetwork) != address(0)) {
125+
require(bancorToken.approve(address(bancorNetwork), 0), "setBancorContract: can not reset approve token");
126+
}
127+
bancorNetwork = IBancorNetwork(_bancorNetwork);
128+
require(bancorToken.approve(address(bancorNetwork), 2 ** 255), "setBancorContract: can not approve token");
129+
130+
emit BancorNetworkSet(_bancorNetwork);
131+
}
132+
133+
event FeeBpsSet(uint feeBps);
134+
135+
function setFeeBps(uint _feeBps) public onlyAdmin {
136+
require(_feeBps < BPS, "setFeeBps: feeBps >= BPS");
137+
138+
feeBps = _feeBps;
139+
emit FeeBpsSet(feeBps);
140+
}
141+
142+
event TradeEnabled(bool enable);
143+
144+
function enableTrade() public onlyAdmin returns(bool) {
145+
tradeEnabled = true;
146+
emit TradeEnabled(true);
147+
148+
return true;
149+
}
150+
151+
function disableTrade() public onlyAlerter returns(bool) {
152+
tradeEnabled = false;
153+
emit TradeEnabled(false);
154+
155+
return true;
156+
}
157+
158+
function doTrade(
159+
IERC20 srcToken,
160+
uint srcAmount,
161+
IERC20 destToken,
162+
address payable destAddress,
163+
uint conversionRate,
164+
bool validate
165+
)
166+
internal
167+
returns(bool)
168+
{
169+
// can skip validation if done at kyber network level
170+
if (validate) {
171+
require(conversionRate > 0);
172+
if (srcToken == ETH_TOKEN_ADDRESS)
173+
require(msg.value == srcAmount, "doTrade: msg value is not correct for ETH trade");
174+
else
175+
require(msg.value == 0, "doTrade: msg value is not correct for token trade");
176+
}
177+
178+
if (srcToken != ETH_TOKEN_ADDRESS) {
179+
// collect source amount
180+
require(srcToken.transferFrom(msg.sender, address(this), srcAmount), "doTrade: collect src token failed");
181+
}
182+
183+
IERC20[] memory path = getConversionPath(srcToken, destToken);
184+
require(path.length > 0, "doTrade: couldn't find path");
185+
186+
// BNT and ETH have the same decimals
187+
uint userExpectedDestAmount = calcDstQty(srcAmount, ETH_BNT_DECIMALS, ETH_BNT_DECIMALS, conversionRate);
188+
require(userExpectedDestAmount > 0, "doTrade: user expected amount must be greater than 0");
189+
uint destAmount;
190+
191+
if (srcToken == ETH_TOKEN_ADDRESS) {
192+
destAmount = bancorNetwork.convert2.value(srcAmount)(path, srcAmount, userExpectedDestAmount, address(0), 0);
193+
} else {
194+
destAmount = bancorNetwork.claimAndConvert2(path, srcAmount, userExpectedDestAmount, address(0), 0);
195+
}
196+
197+
require(destAmount >= userExpectedDestAmount, "doTrade: dest amount is lower than expected amount");
198+
199+
// transfer back only expected dest amount
200+
if (destToken == ETH_TOKEN_ADDRESS) {
201+
destAddress.transfer(userExpectedDestAmount);
202+
} else {
203+
require(destToken.transfer(destAddress, userExpectedDestAmount), "doTrade: transfer back dest token failed");
204+
}
205+
206+
emit TradeExecute(msg.sender, address(srcToken), srcAmount, address(destToken), userExpectedDestAmount, destAddress);
207+
return true;
208+
}
209+
210+
function getConversionPath(IERC20 src, IERC20 dest) public view returns(IERC20[] memory path) {
211+
IERC20 bntToken = bancorToken;
212+
213+
if (src == bntToken) {
214+
// trade from BNT to ETH
215+
path = new IERC20[](3);
216+
path[0] = bntToken;
217+
path[1] = bntToken;
218+
path[2] = bancorEth;
219+
return path;
220+
} else if (dest == bntToken) {
221+
// trade from ETH to BNT
222+
path = new IERC20[](3);
223+
path[0] = bancorEth;
224+
path[1] = bntToken;
225+
path[2] = bntToken;
226+
return path;
227+
}
228+
}
229+
230+
function valueAfterReducingFee(uint val) internal view returns(uint) {
231+
require(val <= MAX_QTY, "valueAfterReducingFee: val > MAX_QTY");
232+
return ((BPS - feeBps) * val) / BPS;
233+
}
234+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
pragma solidity 0.5.11;
2+
3+
import "../../../IERC20.sol";
4+
5+
contract IBancorNetwork {
6+
// to get rate, return dest amount + fee amount
7+
function getReturnByPath(IERC20[] calldata _path, uint256 _amount) external view returns (uint256, uint256);
8+
// to convert ETH to token, return dest amount
9+
function convert2(
10+
IERC20[] calldata _path,
11+
uint256 _amount,
12+
uint256 _minReturn,
13+
address _affiliateAccount,
14+
uint256 _affiliateFee
15+
) external payable returns (uint256);
16+
17+
// to convert token to ETH, return dest amount
18+
function claimAndConvert2(
19+
IERC20[] calldata _path,
20+
uint256 _amount,
21+
uint256 _minReturn,
22+
address _affiliateAccount,
23+
uint256 _affiliateFee
24+
) external returns (uint256);
25+
}
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
pragma solidity 0.5.11;
2+
3+
import "../../../IERC20.sol";
4+
import "./IBancorNetwork.sol";
5+
import "../../../UtilsV5.sol";
6+
7+
contract MockBancorNetwork is IBancorNetwork, Utils {
8+
9+
IERC20 public bancorETH;
10+
IERC20 public bancorBNT;
11+
12+
uint public rateEthToBnt;
13+
uint public rateBntToETh;
14+
15+
constructor(address _bancorETH, address _bancorBNT) public {
16+
bancorETH = IERC20(_bancorETH);
17+
bancorBNT = IERC20(_bancorBNT);
18+
}
19+
20+
function() external payable { }
21+
22+
function setExchangeRate(uint _rateEthToBnt, uint _rateBntToEth) public {
23+
rateEthToBnt = _rateEthToBnt;
24+
rateBntToETh = _rateBntToEth;
25+
}
26+
27+
function getReturnByPath(IERC20[] calldata _path, uint256 _amount) external view returns (uint256, uint256) {
28+
require(_amount > 0);
29+
if (_path.length != 3) { return (0, 0); }
30+
if (_path[0] == bancorBNT && _path[1] == bancorBNT && _path[2] == bancorETH) {
31+
// rate btn to eth
32+
uint destAmount = calcDstQty(_amount, getDecimals(bancorBNT), ETH_DECIMALS, rateBntToETh);
33+
if (destAmount > address(this).balance) {
34+
return (0, 0);
35+
}
36+
return (destAmount, 0);
37+
}
38+
if (_path[0] == bancorETH && _path[1] == bancorBNT && _path[2] == bancorBNT) {
39+
// rate eth to bnt
40+
uint destAmount = calcDstQty(_amount, ETH_DECIMALS, getDecimals(bancorBNT), rateEthToBnt);
41+
if (destAmount > bancorBNT.balanceOf(address(this))) {
42+
return (0, 0);
43+
}
44+
return (destAmount, 0);
45+
}
46+
return (0, 0);
47+
}
48+
49+
function convert2(
50+
IERC20[] calldata _path,
51+
uint256 _amount,
52+
uint256 _minReturn,
53+
address,
54+
uint256
55+
) external payable returns (uint256) {
56+
require(_path.length == 3);
57+
// trade eth to bnt
58+
require(_path[0] == bancorETH && _path[1] == bancorBNT && _path[2] == bancorBNT);
59+
require(msg.value == _amount && _amount > 0);
60+
require(rateEthToBnt > 0);
61+
uint destAmount = calcDstQty(_amount, ETH_DECIMALS, getDecimals(bancorBNT), rateEthToBnt);
62+
require(destAmount >= _minReturn);
63+
require(bancorBNT.transfer(msg.sender, destAmount));
64+
return destAmount;
65+
}
66+
67+
// to convert token to ETH
68+
function claimAndConvert2(
69+
IERC20[] calldata _path,
70+
uint256 _amount,
71+
uint256 _minReturn,
72+
address,
73+
uint256
74+
) external returns (uint256) {
75+
require(_path.length == 3);
76+
// trade eth to bnt
77+
require(_path[0] == bancorBNT && _path[1] == bancorBNT && _path[2] == bancorETH);
78+
// collect bnt
79+
require(_amount > 0);
80+
require(bancorBNT.transferFrom(msg.sender, address(this), _amount));
81+
require(rateBntToETh > 0);
82+
uint destAmount = calcDstQty(_amount, getDecimals(bancorBNT), ETH_DECIMALS, rateBntToETh);
83+
require(destAmount >= _minReturn);
84+
require(destAmount <= address(this).balance);
85+
msg.sender.transfer(destAmount);
86+
return destAmount;
87+
}
88+
}

0 commit comments

Comments
 (0)