Compare commits

..

27 Commits

Author SHA1 Message Date
Github Actions
b10cfc50d3 Publish
- @0x/contracts-erc20@3.3.31
 - @0x/contracts-test-utils@5.4.22
 - @0x/contracts-treasury@1.4.14
 - @0x/contracts-utils@4.8.12
 - @0x/contracts-zero-ex@0.34.0
 - @0x/asset-swapper@16.61.0
 - @0x/contract-addresses@6.15.0
 - @0x/contract-wrappers@13.20.3
 - @0x/protocol-utils@11.14.0
2022-06-03 19:20:52 +00:00
Github Actions
2e6317b01e Updated CHANGELOGS & MD docs 2022-06-03 19:20:49 +00:00
Noah Khamliche
50e99e6eac address comments 2022-06-03 15:03:00 -04:00
Noah Khamliche
8f2f4554eb fix linting 2022-06-03 15:03:00 -04:00
Noah Khamliche
67d9678a3a fix linting 2022-06-03 15:03:00 -04:00
Noah Khamliche
f70341fb48 rebase development 2022-06-03 15:03:00 -04:00
Megan
14cd24ea47 feat/add MeshSwap on Polygon [TKR-374] (#491)
* Added MeshSwap on Polygon

* Updated changelog
2022-06-03 15:03:00 -04:00
Noah Khamliche
78328056d7 Added BancorV3 to fqt, and added support in asset-swapper 2022-06-03 15:03:00 -04:00
Noah Khamliche
0045a60b0f updated contract-addresses with new ethereum fqt 2022-06-03 15:03:00 -04:00
Noah Khamliche
e4e71c76e1 add weth/eth wrap/unwrap support for bancorv3 2022-06-03 15:03:00 -04:00
Megan
ca8127545f feat/add MeshSwap on Polygon [TKR-374] (#491)
* Added MeshSwap on Polygon

* Updated changelog
2022-06-03 15:03:00 -04:00
Noah Khamliche
7b709089ce fix versioning issue on protocol-utils 2022-06-03 15:03:00 -04:00
Noah Khamliche
190f7e45f2 final changes 2022-06-03 15:03:00 -04:00
Noah Khamliche
0dcc3a6fc3 nitpicks 2022-06-03 15:03:00 -04:00
Noah Khamliche
c2e8cae293 added changelog entries 2022-06-03 15:03:00 -04:00
Noah Khamliche
83da7caab4 fixed bancor sell quotes 2022-06-03 15:03:00 -04:00
Noah Khamliche
fd69a0c273 added weth/eth support to sampler 2022-06-03 15:03:00 -04:00
Noah Khamliche
9b131199ad add weth/eth wrap/unwrap support for bancorv3 2022-06-03 15:03:00 -04:00
Noah Khamliche
f5c486050b added bancor mixin/sampler and started linking up with asset-swapper 2022-06-03 15:03:00 -04:00
Megan
1f41fe6a20 feat/add MeshSwap on Polygon [TKR-374] (#491)
* Added MeshSwap on Polygon

* Updated changelog
2022-06-02 19:11:25 +02:00
Kyu
7f4080e0a2 Delete packages/migrations (#488)
* Delete packages/migrations

* Remove 0x/migrations from asset-swapper dev dependency

* Remove 0x/migrations references
2022-06-02 10:00:50 -07:00
Kyu
db76da58d7 Add stETH wrap/unwrap support [TKR-377] (#476)
* Update MixinLido to support stETH wrapping/unwrapping

* Update LidoSampler and asset-swapper

* Re-use token address constants in LIDO_INFO_BY_CHAIN

* Update CHANGELOG.json

* Add stETH <-> wstETH to TokenAdjacencyGraph

* Change lido gas schedule code style

* Move allowance approval inside the wrap branch

* Refactor LidoSampler to reduce its bytecode size
2022-05-31 09:58:44 -07:00
mzhu25
cf8fc0ff8e Split up BridgeAdapter by chain [TKR-402] (#487)
* Split up BridgeAdapter by chain

* Fix BridgeProtocols enum

* Add isSupportedSource to bridge adapter contracts

* Add bridge adapter tests

* Fix FQT test
2022-05-25 14:18:24 -04:00
Kyu
2d16f83e37 Offboard/clean up Oasis, CoFix, and legacy Kyber [TKR-405] (#482)
* Remove Oasis

* Remove CoFix code

* Remove MixinKyber

* Remove Kyber from asset-swapper

* Delete unused imports, interface, and etc.

* Fix the test failure issue when it's run with neon-router

* Update CHANGELOG.json
2022-05-19 17:39:02 -07:00
Github Actions
4057bdab91 Publish
- @0x/asset-swapper@16.60.1
2022-05-19 03:40:00 +00:00
Github Actions
1cd10f0ac9 Updated CHANGELOGS & MD docs 2022-05-19 03:39:57 +00:00
Jacob Evans
68f87b2432 fix: BalancerV2 sor alias (#481)
* Install both Balancer sor and rename early version to v1

* yarn.lock

* CHANGELOG
2022-05-19 13:19:25 +10:00
110 changed files with 2108 additions and 5659 deletions

View File

@@ -110,7 +110,7 @@ jobs:
- image: node:16
working_directory: ~/repo
environment:
RUST_ROUTER: "true"
RUST_ROUTER: 'true'
steps:
- restore_cache:
keys:
@@ -118,7 +118,6 @@ jobs:
- run: yarn wsrun -p @0x/contracts-test-utils -m --serial -c test:circleci
- run: yarn wsrun -p @0x/contract-artifacts -m --serial -c test:circleci
- run: yarn wsrun -p @0x/contract-wrappers-test -m --serial -c test:circleci
- run: yarn wsrun -p @0x/migrations -m --serial -c test:circleci
- run: yarn wsrun -p @0x/order-utils -m --serial -c test:circleci
- run: yarn wsrun -p @0x/asset-swapper -m --serial -c test:circleci
- save_cache:

View File

@@ -1,7 +1,6 @@
python: ['python-packages']
contracts: ['contracts']
@0x/contract-addresses: ['packages/contract-addresses']
@0x/migrations: ['packages/migrations']
@0x/order-utils: ['packages/order-utils']
@0x/contract-artifacts: ['packages/contract-artifacts']
@0x/contract-wrappers: ['packages/contract-wrappers']

View File

@@ -38,7 +38,6 @@ These packages are all under development. See [/contracts/README.md](/contracts/
| [`@0x/protocol-utils`](/packages/protocol-utils) | [![npm](https://img.shields.io/npm/v/@0x/protocol-utils.svg)](https://www.npmjs.com/package/@0x/protocol-utils) | A set of utilities for generating, parsing, signing and validating 0x orders |
| [`@0x/contract-addresses`](/packages/contract-addresses) | [![npm](https://img.shields.io/npm/v/@0x/contract-addresses.svg)](https://www.npmjs.com/package/@0x/contract-addresses) | A tiny utility library for getting known deployed contract addresses for a particular network. |
| [`@0x/contract-wrappers`](/packages/contract-wrappers) | [![npm](https://img.shields.io/npm/v/@0x/contract-wrappers.svg)](https://www.npmjs.com/package/@0x/contract-wrappers) | JS/TS wrappers for interacting with the 0x smart contracts |
| [`@0x/migrations`](/packages/migrations) | [![npm](https://img.shields.io/npm/v/@0x/migrations.svg)](https://www.npmjs.com/package/@0x/migrations) | Migration tool for deploying 0x smart contracts on private testnets |
| [`@0x/contract-artifacts`](/packages/contract-artifacts) | [![npm](https://img.shields.io/npm/v/@0x/contract-artifacts.svg)](https://www.npmjs.com/package/@0x/contract-artifacts) | 0x smart contract compilation artifacts | |
## Usage

View File

@@ -1,4 +1,13 @@
[
{
"timestamp": 1654284040,
"version": "3.3.31",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1652919697,
"version": "3.3.30",

View File

@@ -5,6 +5,10 @@ Edit the package's CHANGELOG.json file only.
CHANGELOG
## v3.3.31 - _June 3, 2022_
* Dependencies updated
## v3.3.30 - _May 19, 2022_
* Dependencies updated

View File

@@ -1,6 +1,6 @@
{
"name": "@0x/contracts-erc20",
"version": "3.3.30",
"version": "3.3.31",
"engines": {
"node": ">=6.12"
},
@@ -53,8 +53,8 @@
"devDependencies": {
"@0x/abi-gen": "^5.8.0",
"@0x/contracts-gen": "^2.0.46",
"@0x/contracts-test-utils": "^5.4.21",
"@0x/contracts-utils": "^4.8.11",
"@0x/contracts-test-utils": "^5.4.22",
"@0x/contracts-utils": "^4.8.12",
"@0x/dev-utils": "^4.2.14",
"@0x/sol-compiler": "^4.8.1",
"@0x/ts-doc-gen": "^0.0.28",

View File

@@ -1,4 +1,13 @@
[
{
"timestamp": 1654284040,
"version": "5.4.22",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1652919697,
"version": "5.4.21",

View File

@@ -5,6 +5,10 @@ Edit the package's CHANGELOG.json file only.
CHANGELOG
## v5.4.22 - _June 3, 2022_
* Dependencies updated
## v5.4.21 - _May 19, 2022_
* Dependencies updated

View File

@@ -1,6 +1,6 @@
{
"name": "@0x/contracts-test-utils",
"version": "5.4.21",
"version": "5.4.22",
"engines": {
"node": ">=6.12"
},
@@ -44,7 +44,7 @@
"dependencies": {
"@0x/assert": "^3.0.34",
"@0x/base-contract": "^6.5.0",
"@0x/contract-addresses": "^6.14.0",
"@0x/contract-addresses": "^6.15.0",
"@0x/dev-utils": "^4.2.14",
"@0x/json-schemas": "^6.4.4",
"@0x/order-utils": "^10.4.28",

View File

@@ -1,4 +1,13 @@
[
{
"timestamp": 1654284040,
"version": "1.4.14",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1652919697,
"version": "1.4.13",

View File

@@ -5,6 +5,10 @@ Edit the package's CHANGELOG.json file only.
CHANGELOG
## v1.4.14 - _June 3, 2022_
* Dependencies updated
## v1.4.13 - _May 19, 2022_
* Dependencies updated

View File

@@ -1,6 +1,6 @@
{
"name": "@0x/contracts-treasury",
"version": "1.4.13",
"version": "1.4.14",
"engines": {
"node": ">=6.12"
},
@@ -47,12 +47,12 @@
"homepage": "https://github.com/0xProject/protocol/tree/main/contracts/treasury",
"devDependencies": {
"@0x/abi-gen": "^5.8.0",
"@0x/contract-addresses": "^6.14.0",
"@0x/contract-addresses": "^6.15.0",
"@0x/contracts-asset-proxy": "^3.7.19",
"@0x/contracts-erc20": "^3.3.30",
"@0x/contracts-erc20": "^3.3.31",
"@0x/contracts-gen": "^2.0.46",
"@0x/contracts-staking": "^2.0.45",
"@0x/contracts-test-utils": "^5.4.21",
"@0x/contracts-test-utils": "^5.4.22",
"@0x/sol-compiler": "^4.8.1",
"@0x/ts-doc-gen": "^0.0.28",
"@0x/tslint-config": "^4.1.4",
@@ -73,7 +73,7 @@
},
"dependencies": {
"@0x/base-contract": "^6.5.0",
"@0x/protocol-utils": "^11.13.0",
"@0x/protocol-utils": "^11.14.0",
"@0x/subproviders": "^6.6.5",
"@0x/types": "^3.3.6",
"@0x/typescript-typings": "^5.3.1",

View File

@@ -1,4 +1,13 @@
[
{
"timestamp": 1654284040,
"version": "4.8.12",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1652919697,
"version": "4.8.11",

View File

@@ -5,6 +5,10 @@ Edit the package's CHANGELOG.json file only.
CHANGELOG
## v4.8.12 - _June 3, 2022_
* Dependencies updated
## v4.8.11 - _May 19, 2022_
* Dependencies updated

View File

@@ -1,6 +1,6 @@
{
"name": "@0x/contracts-utils",
"version": "4.8.11",
"version": "4.8.12",
"engines": {
"node": ">=6.12"
},
@@ -52,7 +52,7 @@
"devDependencies": {
"@0x/abi-gen": "^5.8.0",
"@0x/contracts-gen": "^2.0.46",
"@0x/contracts-test-utils": "^5.4.21",
"@0x/contracts-test-utils": "^5.4.22",
"@0x/dev-utils": "^4.2.14",
"@0x/order-utils": "^10.4.28",
"@0x/sol-compiler": "^4.8.1",

View File

@@ -1,4 +1,22 @@
[
{
"version": "0.34.0",
"changes": [
{
"note": "Splits BridgeAdapter up by chain",
"pr": 487
},
{
"note": "Add stETH wrap/unwrap support",
"pr": 476
},
{
"note": "Adds support for BancorV3 to EthereumBridgeAdapter",
"pr": 492
}
],
"timestamp": 1654284040
},
{
"version": "0.33.0",
"changes": [

View File

@@ -5,6 +5,12 @@ Edit the package's CHANGELOG.json file only.
CHANGELOG
## v0.34.0 - _June 3, 2022_
* Splits BridgeAdapter up by chain (#487)
* Add stETH wrap/unwrap support (#476)
* Adds support for BancorV3 to EthereumBridgeAdapter (#492)
## v0.33.0 - _May 19, 2022_
* Add support for GMX and Platypus to bridge adapter (#478)

View File

@@ -0,0 +1,88 @@
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2022 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6;
pragma experimental ABIEncoderV2;
import "./IBridgeAdapter.sol";
abstract contract AbstractBridgeAdapter is IBridgeAdapter {
constructor(
uint256 expectedChainId,
string memory expectedChainName
)
public
{
uint256 chainId;
assembly { chainId := chainid() }
// Allow testing on Ganache
if (chainId != expectedChainId && chainId != 1337) {
revert(string(abi.encodePacked(expectedChainName, "BridgeAdapter.constructor: wrong chain ID")));
}
}
function isSupportedSource(bytes32 source)
external
override
returns (bool isSupported)
{
BridgeOrder memory placeholderOrder;
placeholderOrder.source = source;
IERC20TokenV06 placeholderToken = IERC20TokenV06(address(0));
(, isSupported) = _trade(
placeholderOrder,
placeholderToken,
placeholderToken,
0,
true
);
}
function trade(
BridgeOrder memory order,
IERC20TokenV06 sellToken,
IERC20TokenV06 buyToken,
uint256 sellAmount
)
public
override
returns (uint256 boughtAmount)
{
(boughtAmount, ) = _trade(
order,
sellToken,
buyToken,
sellAmount,
false
);
}
function _trade(
BridgeOrder memory order,
IERC20TokenV06 sellToken,
IERC20TokenV06 buyToken,
uint256 sellAmount,
bool dryRun
)
internal
virtual
returns (uint256 boughtAmount, bool supportedSource);
}

View File

@@ -0,0 +1,141 @@
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2022 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "./AbstractBridgeAdapter.sol";
import "./BridgeProtocols.sol";
import "./mixins/MixinCurve.sol";
import "./mixins/MixinCurveV2.sol";
import "./mixins/MixinGMX.sol";
import "./mixins/MixinKyberDmm.sol";
import "./mixins/MixinAaveV2.sol";
import "./mixins/MixinNerve.sol";
import "./mixins/MixinPlatypus.sol";
import "./mixins/MixinUniswapV2.sol";
import "./mixins/MixinZeroExBridge.sol";
contract AvalancheBridgeAdapter is
AbstractBridgeAdapter(43114, "Avalanche"),
MixinCurve,
MixinCurveV2,
MixinGMX,
MixinKyberDmm,
MixinAaveV2,
MixinNerve,
MixinPlatypus,
MixinUniswapV2,
MixinZeroExBridge
{
constructor(IEtherTokenV06 weth)
public
MixinCurve(weth)
{}
function _trade(
BridgeOrder memory order,
IERC20TokenV06 sellToken,
IERC20TokenV06 buyToken,
uint256 sellAmount,
bool dryRun
)
internal
override
returns (uint256 boughtAmount, bool supportedSource)
{
uint128 protocolId = uint128(uint256(order.source) >> 128);
if (protocolId == BridgeProtocols.CURVE) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeCurve(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.CURVEV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeCurveV2(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.UNISWAPV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeUniswapV2(
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.NERVE) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeNerve(
sellToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.KYBERDMM) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeKyberDmm(
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.AAVEV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeAaveV2(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.GMX) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeGMX(
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.PLATYPUS) {
if (dryRun) { return (0, true); }
boughtAmount = _tradePlatypus(
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.UNKNOWN) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeZeroExBridge(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
}
emit BridgeFill(
order.source,
sellToken,
buyToken,
sellAmount,
boughtAmount
);
}
}

View File

@@ -0,0 +1,132 @@
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2022 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "./AbstractBridgeAdapter.sol";
import "./BridgeProtocols.sol";
import "./mixins/MixinCurve.sol";
import "./mixins/MixinDodo.sol";
import "./mixins/MixinDodoV2.sol";
import "./mixins/MixinKyberDmm.sol";
import "./mixins/MixinMooniswap.sol";
import "./mixins/MixinNerve.sol";
import "./mixins/MixinUniswapV2.sol";
import "./mixins/MixinZeroExBridge.sol";
contract BSCBridgeAdapter is
AbstractBridgeAdapter(56, "BSC"),
MixinCurve,
MixinDodo,
MixinDodoV2,
MixinKyberDmm,
MixinMooniswap,
MixinNerve,
MixinUniswapV2,
MixinZeroExBridge
{
constructor(IEtherTokenV06 weth)
public
MixinCurve(weth)
MixinMooniswap(weth)
{}
function _trade(
BridgeOrder memory order,
IERC20TokenV06 sellToken,
IERC20TokenV06 buyToken,
uint256 sellAmount,
bool dryRun
)
internal
override
returns (uint256 boughtAmount, bool supportedSource)
{
uint128 protocolId = uint128(uint256(order.source) >> 128);
if (protocolId == BridgeProtocols.CURVE) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeCurve(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.UNISWAPV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeUniswapV2(
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.MOONISWAP) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeMooniswap(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.DODO) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeDodo(
sellToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.DODOV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeDodoV2(
sellToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.NERVE) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeNerve(
sellToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.KYBERDMM) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeKyberDmm(
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.UNKNOWN) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeZeroExBridge(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
}
emit BridgeFill(
order.source,
sellToken,
buyToken,
sellAmount,
boughtAmount
);
}
}

View File

@@ -32,16 +32,16 @@ library BridgeProtocols {
uint128 internal constant UNISWAPV2 = 2;
uint128 internal constant UNISWAP = 3;
uint128 internal constant BALANCER = 4;
uint128 internal constant KYBER = 5;
uint128 internal constant KYBER = 5; // Not used: deprecated.
uint128 internal constant MOONISWAP = 6;
uint128 internal constant MSTABLE = 7;
uint128 internal constant OASIS = 8;
uint128 internal constant OASIS = 8; // Not used: deprecated.
uint128 internal constant SHELL = 9;
uint128 internal constant DODO = 10;
uint128 internal constant DODOV2 = 11;
uint128 internal constant CRYPTOCOM = 12;
uint128 internal constant BANCOR = 13;
uint128 internal constant COFIX = 14;
uint128 internal constant COFIX = 14; // Not used: deprecated.
uint128 internal constant NERVE = 15;
uint128 internal constant MAKERPSM = 16;
uint128 internal constant BALANCERV2 = 17;
@@ -55,4 +55,5 @@ library BridgeProtocols {
uint128 internal constant BALANCERV2BATCH = 25;
uint128 internal constant GMX = 26;
uint128 internal constant PLATYPUS = 27;
uint128 internal constant BANCORV3 = 28;
}

View File

@@ -0,0 +1,84 @@
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2022 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "./AbstractBridgeAdapter.sol";
import "./BridgeProtocols.sol";
import "./mixins/MixinNerve.sol";
import "./mixins/MixinUniswapV2.sol";
import "./mixins/MixinZeroExBridge.sol";
contract CeloBridgeAdapter is
AbstractBridgeAdapter(42220, "Celo"),
MixinNerve,
MixinUniswapV2,
MixinZeroExBridge
{
constructor(address _weth)
public
{}
function _trade(
BridgeOrder memory order,
IERC20TokenV06 sellToken,
IERC20TokenV06 buyToken,
uint256 sellAmount,
bool dryRun
)
internal
override
returns (uint256 boughtAmount, bool supportedSource)
{
uint128 protocolId = uint128(uint256(order.source) >> 128);
if (protocolId == BridgeProtocols.UNISWAPV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeUniswapV2(
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.NERVE) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeNerve(
sellToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.UNKNOWN) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeZeroExBridge(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
}
emit BridgeFill(
order.source,
sellToken,
buyToken,
sellAmount,
boughtAmount
);
}
}

View File

@@ -1,7 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2021 ZeroEx Intl.
Copyright 2022 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -20,56 +20,52 @@
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "./IBridgeAdapter.sol";
import "./AbstractBridgeAdapter.sol";
import "./BridgeProtocols.sol";
import "./mixins/MixinAaveV2.sol";
import "./mixins/MixinBalancer.sol";
import "./mixins/MixinBalancerV2.sol";
import "./mixins/MixinBalancerV2Batch.sol";
import "./mixins/MixinBancor.sol";
import "./mixins/MixinBancorV3.sol";
import "./mixins/MixinCompound.sol";
import "./mixins/MixinCurve.sol";
import "./mixins/MixinCurveV2.sol";
import "./mixins/MixinCryptoCom.sol";
import "./mixins/MixinDodo.sol";
import "./mixins/MixinDodoV2.sol";
import "./mixins/MixinGMX.sol";
import "./mixins/MixinKyberDmm.sol";
import "./mixins/MixinLido.sol";
import "./mixins/MixinMakerPSM.sol";
import "./mixins/MixinMooniswap.sol";
import "./mixins/MixinMStable.sol";
import "./mixins/MixinNerve.sol";
import "./mixins/MixinOasis.sol";
import "./mixins/MixinPlatypus.sol";
import "./mixins/MixinShell.sol";
import "./mixins/MixinUniswap.sol";
import "./mixins/MixinUniswapV2.sol";
import "./mixins/MixinUniswapV3.sol";
import "./mixins/MixinZeroExBridge.sol";
contract BridgeAdapter is
IBridgeAdapter,
contract EthereumBridgeAdapter is
AbstractBridgeAdapter(1, "Ethereum"),
MixinAaveV2,
MixinBalancer,
MixinBalancerV2,
MixinBalancerV2Batch,
MixinBancor,
MixinBancorV3,
MixinCompound,
MixinCurve,
MixinCurveV2,
MixinCryptoCom,
MixinDodo,
MixinDodoV2,
MixinGMX,
MixinKyberDmm,
MixinLido,
MixinMakerPSM,
MixinMooniswap,
MixinMStable,
MixinNerve,
MixinOasis,
MixinPlatypus,
MixinShell,
MixinUniswap,
MixinUniswapV2,
@@ -78,43 +74,29 @@ contract BridgeAdapter is
{
constructor(IEtherTokenV06 weth)
public
MixinAaveV2()
MixinBalancer()
MixinBalancerV2()
MixinBancor(weth)
MixinBancorV3(weth)
MixinCompound(weth)
MixinCurve(weth)
MixinCurveV2()
MixinCryptoCom()
MixinDodo()
MixinDodoV2()
MixinGMX()
MixinLido(weth)
MixinMakerPSM()
MixinMooniswap(weth)
MixinMStable()
MixinNerve()
MixinOasis()
MixinPlatypus()
MixinShell()
MixinUniswap(weth)
MixinUniswapV2()
MixinUniswapV3()
MixinZeroExBridge()
{}
function trade(
function _trade(
BridgeOrder memory order,
IERC20TokenV06 sellToken,
IERC20TokenV06 buyToken,
uint256 sellAmount
uint256 sellAmount,
bool dryRun
)
public
internal
override
returns (uint256 boughtAmount)
returns (uint256 boughtAmount, bool supportedSource)
{
uint128 protocolId = uint128(uint256(order.source) >> 128);
if (protocolId == BridgeProtocols.CURVE) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeCurve(
sellToken,
buyToken,
@@ -122,6 +104,7 @@ contract BridgeAdapter is
order.bridgeData
);
} else if (protocolId == BridgeProtocols.CURVEV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeCurveV2(
sellToken,
buyToken,
@@ -129,18 +112,21 @@ contract BridgeAdapter is
order.bridgeData
);
} else if (protocolId == BridgeProtocols.UNISWAPV3) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeUniswapV3(
sellToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.UNISWAPV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeUniswapV2(
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.UNISWAP) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeUniswap(
sellToken,
buyToken,
@@ -148,6 +134,7 @@ contract BridgeAdapter is
order.bridgeData
);
} else if (protocolId == BridgeProtocols.BALANCER) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeBalancer(
sellToken,
buyToken,
@@ -155,6 +142,7 @@ contract BridgeAdapter is
order.bridgeData
);
} else if (protocolId == BridgeProtocols.BALANCERV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeBalancerV2(
sellToken,
buyToken,
@@ -162,11 +150,13 @@ contract BridgeAdapter is
order.bridgeData
);
} else if (protocolId == BridgeProtocols.BALANCERV2BATCH) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeBalancerV2Batch(
sellAmount,
order.bridgeData
);
}else if (protocolId == BridgeProtocols.MAKERPSM) {
} else if (protocolId == BridgeProtocols.MAKERPSM) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeMakerPsm(
sellToken,
buyToken,
@@ -174,6 +164,7 @@ contract BridgeAdapter is
order.bridgeData
);
} else if (protocolId == BridgeProtocols.MOONISWAP) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeMooniswap(
sellToken,
buyToken,
@@ -181,20 +172,15 @@ contract BridgeAdapter is
order.bridgeData
);
} else if (protocolId == BridgeProtocols.MSTABLE) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeMStable(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.OASIS) {
boughtAmount = _tradeOasis(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.SHELL) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeShell(
sellToken,
buyToken,
@@ -202,42 +188,49 @@ contract BridgeAdapter is
order.bridgeData
);
} else if (protocolId == BridgeProtocols.DODO) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeDodo(
sellToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.DODOV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeDodoV2(
sellToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.CRYPTOCOM) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeCryptoCom(
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.BANCOR) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeBancor(
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.NERVE) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeNerve(
sellToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.KYBERDMM) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeKyberDmm(
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.LIDO) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeLido(
sellToken,
buyToken,
@@ -245,6 +238,7 @@ contract BridgeAdapter is
order.bridgeData
);
} else if (protocolId == BridgeProtocols.AAVEV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeAaveV2(
sellToken,
buyToken,
@@ -252,25 +246,22 @@ contract BridgeAdapter is
order.bridgeData
);
} else if (protocolId == BridgeProtocols.COMPOUND) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeCompound(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.GMX) {
boughtAmount = _tradeGMX(
} else if (protocolId == BridgeProtocols.BANCORV3) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeBancorV3(
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.PLATYPUS) {
boughtAmount = _tradePlatypus(
buyToken,
sellAmount,
order.bridgeData
);
} else {
} else if (protocolId == BridgeProtocols.UNKNOWN) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeZeroExBridge(
sellToken,
buyToken,

View File

@@ -0,0 +1,124 @@
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2022 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "./AbstractBridgeAdapter.sol";
import "./BridgeProtocols.sol";
import "./mixins/MixinAaveV2.sol";
import "./mixins/MixinBalancerV2.sol";
import "./mixins/MixinCurve.sol";
import "./mixins/MixinCurveV2.sol";
import "./mixins/MixinNerve.sol";
import "./mixins/MixinUniswapV2.sol";
import "./mixins/MixinZeroExBridge.sol";
contract FantomBridgeAdapter is
AbstractBridgeAdapter(250, "Fantom"),
MixinAaveV2,
MixinBalancerV2,
MixinCurve,
MixinCurveV2,
MixinNerve,
MixinUniswapV2,
MixinZeroExBridge
{
constructor(IEtherTokenV06 weth)
public
MixinCurve(weth)
{}
function _trade(
BridgeOrder memory order,
IERC20TokenV06 sellToken,
IERC20TokenV06 buyToken,
uint256 sellAmount,
bool dryRun
)
internal
override
returns (uint256 boughtAmount, bool supportedSource)
{
uint128 protocolId = uint128(uint256(order.source) >> 128);
if (protocolId == BridgeProtocols.CURVE) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeCurve(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.CURVEV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeCurveV2(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.UNISWAPV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeUniswapV2(
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.BALANCERV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeBalancerV2(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.NERVE) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeNerve(
sellToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.AAVEV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeAaveV2(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.UNKNOWN) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeZeroExBridge(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
}
emit BridgeFill(
order.source,
sellToken,
buyToken,
sellAmount,
boughtAmount
);
}
}

View File

@@ -50,6 +50,10 @@ interface IBridgeAdapter {
uint256 outputTokenAmount
);
function isSupportedSource(bytes32 source)
external
returns (bool isSupported);
function trade(
BridgeOrder calldata order,
IERC20TokenV06 sellToken,

View File

@@ -0,0 +1,104 @@
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2022 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "./AbstractBridgeAdapter.sol";
import "./BridgeProtocols.sol";
import "./mixins/MixinCurve.sol";
import "./mixins/MixinCurveV2.sol";
import "./mixins/MixinNerve.sol";
import "./mixins/MixinUniswapV3.sol";
import "./mixins/MixinZeroExBridge.sol";
contract OptimismBridgeAdapter is
AbstractBridgeAdapter(10, "Optimism"),
MixinCurve,
MixinCurveV2,
MixinNerve,
MixinUniswapV3,
MixinZeroExBridge
{
constructor(IEtherTokenV06 weth)
public
MixinCurve(weth)
{}
function _trade(
BridgeOrder memory order,
IERC20TokenV06 sellToken,
IERC20TokenV06 buyToken,
uint256 sellAmount,
bool dryRun
)
internal
override
returns (uint256 boughtAmount, bool supportedSource)
{
uint128 protocolId = uint128(uint256(order.source) >> 128);
if (protocolId == BridgeProtocols.CURVE) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeCurve(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.CURVEV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeCurveV2(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.UNISWAPV3) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeUniswapV3(
sellToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.NERVE) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeNerve(
sellToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.UNKNOWN) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeZeroExBridge(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
}
emit BridgeFill(
order.source,
sellToken,
buyToken,
sellAmount,
boughtAmount
);
}
}

View File

@@ -0,0 +1,178 @@
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2022 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "./AbstractBridgeAdapter.sol";
import "./BridgeProtocols.sol";
import "./mixins/MixinAaveV2.sol";
import "./mixins/MixinBalancerV2.sol";
import "./mixins/MixinBalancerV2Batch.sol";
import "./mixins/MixinCurve.sol";
import "./mixins/MixinCurveV2.sol";
import "./mixins/MixinDodo.sol";
import "./mixins/MixinDodoV2.sol";
import "./mixins/MixinKyberDmm.sol";
import "./mixins/MixinMStable.sol";
import "./mixins/MixinNerve.sol";
import "./mixins/MixinUniswapV2.sol";
import "./mixins/MixinUniswapV3.sol";
import "./mixins/MixinZeroExBridge.sol";
contract PolygonBridgeAdapter is
AbstractBridgeAdapter(137, "Polygon"),
MixinAaveV2,
MixinBalancerV2,
MixinBalancerV2Batch,
MixinCurve,
MixinCurveV2,
MixinDodo,
MixinDodoV2,
MixinKyberDmm,
MixinMStable,
MixinNerve,
MixinUniswapV2,
MixinUniswapV3,
MixinZeroExBridge
{
constructor(IEtherTokenV06 weth)
public
MixinCurve(weth)
{}
function _trade(
BridgeOrder memory order,
IERC20TokenV06 sellToken,
IERC20TokenV06 buyToken,
uint256 sellAmount,
bool dryRun
)
internal
override
returns (uint256 boughtAmount, bool supportedSource)
{
uint128 protocolId = uint128(uint256(order.source) >> 128);
if (protocolId == BridgeProtocols.CURVE) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeCurve(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.CURVEV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeCurveV2(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.UNISWAPV3) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeUniswapV3(
sellToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.UNISWAPV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeUniswapV2(
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.BALANCERV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeBalancerV2(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.BALANCERV2BATCH) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeBalancerV2Batch(
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.MSTABLE) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeMStable(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.DODO) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeDodo(
sellToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.DODOV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeDodoV2(
sellToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.NERVE) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeNerve(
sellToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.KYBERDMM) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeKyberDmm(
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.AAVEV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeAaveV2(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
} else if (protocolId == BridgeProtocols.UNKNOWN) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeZeroExBridge(
sellToken,
buyToken,
sellAmount,
order.bridgeData
);
}
emit BridgeFill(
order.source,
sellToken,
buyToken,
sellAmount,
boughtAmount
);
}
}

View File

@@ -0,0 +1,128 @@
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/IEtherTokenV06.sol";
/*
BancorV3
*/
interface IBancorV3 {
/**
* @dev performs a trade by providing the source amount and returns the target amount and the associated fee
*
* requirements:
*
* - the caller must be the network contract
*/
function tradeBySourceAmount(
address sourceToken,
address targetToken,
uint256 sourceAmount,
uint256 minReturnAmount,
uint256 deadline,
address beneficiary
) external payable returns (uint256 amount);
}
contract MixinBancorV3 {
using LibERC20TokenV06 for IERC20TokenV06;
IERC20TokenV06 constant public BANCORV3_ETH_ADDRESS =
IERC20TokenV06(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
IEtherTokenV06 private immutable WETH;
constructor(IEtherTokenV06 weth)
public
{
WETH = weth;
}
function _tradeBancorV3(
IERC20TokenV06 buyToken,
uint256 sellAmount,
bytes memory bridgeData
)
internal
returns (uint256 amountOut)
{
IBancorV3 router;
IERC20TokenV06[] memory path;
address[] memory _path;
uint256 payableAmount = 0;
{
(router, _path) = abi.decode(bridgeData, (IBancorV3, address[]));
// To get around `abi.decode()` not supporting interface array types.
assembly { path := _path }
}
require(path.length >= 2, "MixinBancorV3/PATH_LENGTH_MUST_BE_AT_LEAST_TWO");
require(
path[path.length - 1] == buyToken,
"MixinBancorV3/LAST_ELEMENT_OF_PATH_MUST_MATCH_OUTPUT_TOKEN"
);
//swap WETH->ETH as Bancor only deals in ETH
if(_path[0] == address(WETH)) {
//withdraw the sell amount of WETH for ETH
WETH.withdraw(sellAmount);
payableAmount = sellAmount;
// set _path[0] to the ETH address if WETH is our buy token
_path[0] = address(BANCORV3_ETH_ADDRESS);
} else {
// Grant the BancorV3 router an allowance to sell the first token.
path[0].approveIfBelow(address(router), sellAmount);
}
// if we are buying WETH we need to swap to ETH and deposit into WETH after the swap
if(_path[1] == address(WETH)){
_path[1] = address(BANCORV3_ETH_ADDRESS);
}
uint256 amountOut = router.tradeBySourceAmount{value: payableAmount}(
_path[0],
_path[1],
// Sell all tokens we hold.
sellAmount,
// Minimum buy amount.
1,
//deadline
block.timestamp + 1,
// address of the mixin
address(this)
);
// if we want to return WETH deposit the ETH amount we sold
if(buyToken == WETH){
WETH.deposit{value: amountOut}();
}
return amountOut;
}
}

View File

@@ -1,92 +0,0 @@
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/IEtherTokenV06.sol";
interface ICoFiXRouter {
// msg.value = fee
function swapExactTokensForETH(
address token,
uint amountIn,
uint amountOutMin,
address to,
address rewardTo,
uint deadline
) external payable returns (uint _amountIn, uint _amountOut);
// msg.value = amountIn + fee
function swapExactETHForTokens(
address token,
uint amountIn,
uint amountOutMin,
address to,
address rewardTo,
uint deadline
) external payable returns (uint _amountIn, uint _amountOut);
}
interface ICoFiXPair {
function swapWithExact(address outToken, address to)
external
payable
returns (
uint amountIn,
uint amountOut,
uint oracleFeeChange,
uint256[4] memory tradeInfo
);
}
contract MixinCoFiX {
using LibERC20TokenV06 for IERC20TokenV06;
function _tradeCoFiX(
IERC20TokenV06 sellToken,
IERC20TokenV06 buyToken,
uint256 sellAmount,
bytes memory bridgeData
)
internal
returns (uint256 boughtAmount)
{
(uint256 fee, ICoFiXPair pool) = abi.decode(bridgeData, (uint256, ICoFiXPair));
// Transfer tokens into the pool
LibERC20TokenV06.compatTransfer(
sellToken,
address(pool),
sellAmount
);
// Call the swap exact with the tokens now in the pool
// pay the NEST Oracle fee with ETH
(/* In */, boughtAmount, , ) = pool.swapWithExact{value: fee}(
address(buyToken),
address(this)
);
return boughtAmount;
}
}

View File

@@ -1,124 +0,0 @@
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/IEtherTokenV06.sol";
import "../IBridgeAdapter.sol";
interface IKyberNetworkProxy {
/// @dev Sells `sellTokenAddress` tokens for `buyTokenAddress` tokens
/// using a hint for the reserve.
/// @param sellToken Token to sell.
/// @param sellAmount Amount of tokens to sell.
/// @param buyToken Token to buy.
/// @param recipientAddress Address to send bought tokens to.
/// @param maxBuyTokenAmount A limit on the amount of tokens to buy.
/// @param minConversionRate The minimal conversion rate. If actual rate
/// is lower, trade is canceled.
/// @param walletId The wallet ID to send part of the fees
/// @param hint The hint for the selective inclusion (or exclusion) of reserves
/// @return boughtAmount Amount of tokens bought.
function tradeWithHint(
IERC20TokenV06 sellToken,
uint256 sellAmount,
IERC20TokenV06 buyToken,
address payable recipientAddress,
uint256 maxBuyTokenAmount,
uint256 minConversionRate,
address payable walletId,
bytes calldata hint
)
external
payable
returns (uint256 boughtAmount);
}
contract MixinKyber {
using LibERC20TokenV06 for IERC20TokenV06;
/// @dev Address indicating the trade is using ETH
IERC20TokenV06 private immutable KYBER_ETH_ADDRESS =
IERC20TokenV06(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
/// @dev Mainnet address of the WETH contract.
IEtherTokenV06 private immutable WETH;
constructor(IEtherTokenV06 weth)
public
{
WETH = weth;
}
function _tradeKyber(
IERC20TokenV06 sellToken,
IERC20TokenV06 buyToken,
uint256 sellAmount,
bytes memory bridgeData
)
internal
returns (uint256 boughtAmount)
{
(IKyberNetworkProxy kyber, bytes memory hint) =
abi.decode(bridgeData, (IKyberNetworkProxy, bytes));
uint256 payableAmount = 0;
if (sellToken != WETH) {
// If the input token is not WETH, grant an allowance to the exchange
// to spend them.
sellToken.approveIfBelow(
address(kyber),
sellAmount
);
} else {
// If the input token is WETH, unwrap it and attach it to the call.
payableAmount = sellAmount;
WETH.withdraw(payableAmount);
}
// Try to sell all of this contract's input token balance through
// `KyberNetworkProxy.trade()`.
boughtAmount = kyber.tradeWithHint{ value: payableAmount }(
// Input token.
sellToken == WETH ? KYBER_ETH_ADDRESS : sellToken,
// Sell amount.
sellAmount,
// Output token.
buyToken == WETH ? KYBER_ETH_ADDRESS : buyToken,
// Transfer to this contract
address(uint160(address(this))),
// Buy as much as possible.
uint256(-1),
// Lowest minimum conversion rate
1,
// No affiliate address.
address(0),
hint
);
// If receving ETH, wrap it to WETH.
if (buyToken == WETH) {
WETH.deposit{ value: boughtAmount }();
}
return boughtAmount;
}
}

View File

@@ -26,7 +26,7 @@ import "@0x/contracts-erc20/contracts/src/v06/IEtherTokenV06.sol";
/// @dev Minimal interface for minting StETH
interface ILido {
interface IStETH {
/// @dev Adds eth to the pool
/// @param _referral optional address for referrals
/// @return StETH Amount of shares generated
@@ -37,6 +37,33 @@ interface ILido {
function getPooledEthByShares(uint256 _sharesAmount) external view returns (uint256);
}
/// @dev Minimal interface for wrapping/unwrapping stETH.
interface IWstETH {
/**
* @notice Exchanges stETH to wstETH
* @param _stETHAmount amount of stETH to wrap in exchange for wstETH
* @dev Requirements:
* - `_stETHAmount` must be non-zero
* - msg.sender must approve at least `_stETHAmount` stETH to this
* contract.
* - msg.sender must have at least `_stETHAmount` of stETH.
* User should first approve _stETHAmount to the WstETH contract
* @return Amount of wstETH user receives after wrap
*/
function wrap(uint256 _stETHAmount) external returns (uint256);
/**
* @notice Exchanges wstETH to stETH
* @param _wstETHAmount amount of wstETH to uwrap in exchange for stETH
* @dev Requirements:
* - `_wstETHAmount` must be non-zero
* - msg.sender must have at least `_wstETHAmount` wstETH.
* @return Amount of stETH user receives after unwrap
*/
function unwrap(uint256 _wstETHAmount) external returns (uint256);
}
contract MixinLido {
using LibERC20TokenV06 for IERC20TokenV06;
@@ -59,12 +86,43 @@ contract MixinLido {
internal
returns (uint256 boughtAmount)
{
(ILido lido) = abi.decode(bridgeData, (ILido));
if (address(sellToken) == address(WETH) && address(buyToken) == address(lido)) {
if (address(sellToken) == address(WETH)) {
return _tradeStETH(buyToken, sellAmount, bridgeData);
}
return _tradeWstETH(sellToken, buyToken, sellAmount, bridgeData);
}
function _tradeStETH(
IERC20TokenV06 buyToken,
uint256 sellAmount,
bytes memory bridgeData
) private returns (uint256 boughtAmount) {
(IStETH stETH) = abi.decode(bridgeData, (IStETH));
if (address(buyToken) == address(stETH)) {
WETH.withdraw(sellAmount);
boughtAmount = lido.getPooledEthByShares(lido.submit{ value: sellAmount}(address(0)));
} else {
revert("MixinLido/UNSUPPORTED_TOKEN_PAIR");
return stETH.getPooledEthByShares(stETH.submit{ value: sellAmount}(address(0)));
}
revert("MixinLido/UNSUPPORTED_TOKEN_PAIR");
}
function _tradeWstETH(
IERC20TokenV06 sellToken,
IERC20TokenV06 buyToken,
uint256 sellAmount,
bytes memory bridgeData
) private returns(uint256 boughtAmount){
(IEtherTokenV06 stETH, IWstETH wstETH) = abi.decode(bridgeData, (IEtherTokenV06, IWstETH));
if (address(sellToken) == address(stETH) && address(buyToken) == address(wstETH) ) {
sellToken.approveIfBelow(address(wstETH), sellAmount);
return wstETH.wrap(sellAmount);
}
if (address(sellToken) == address(wstETH) && address(buyToken) == address(stETH) ) {
return wstETH.unwrap(sellAmount);
}
revert("MixinLido/UNSUPPORTED_TOKEN_PAIR");
}
}

View File

@@ -1,76 +0,0 @@
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "../IBridgeAdapter.sol";
interface IOasis {
/// @dev Sell `sellAmount` of `sellToken` token and receive `buyToken` token.
/// @param sellToken The token being sold.
/// @param sellAmount The amount of `sellToken` token being sold.
/// @param buyToken The token being bought.
/// @param minBoughtAmount Minimum amount of `buyToken` token to buy.
/// @return boughtAmount Amount of `buyToken` bought.
function sellAllAmount(
IERC20TokenV06 sellToken,
uint256 sellAmount,
IERC20TokenV06 buyToken,
uint256 minBoughtAmount
)
external
returns (uint256 boughtAmount);
}
contract MixinOasis {
using LibERC20TokenV06 for IERC20TokenV06;
function _tradeOasis(
IERC20TokenV06 sellToken,
IERC20TokenV06 buyToken,
uint256 sellAmount,
bytes memory bridgeData
)
internal
returns (uint256 boughtAmount)
{
(IOasis oasis) = abi.decode(bridgeData, (IOasis));
// Grant an allowance to the exchange to spend `sellToken` token.
sellToken.approveIfBelow(
address(oasis),
sellAmount
);
// Try to sell all of this contract's `sellToken` token balance.
boughtAmount = oasis.sellAllAmount(
sellToken,
sellAmount,
buyToken,
// min fill amount
1
);
return boughtAmount;
}
}

View File

@@ -1,3 +1,22 @@
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2022 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
@@ -58,7 +77,7 @@ contract MixinPlatypus {
//keep track of the previous balance to confirm amount out
uint256 beforeBalance = buyToken.balanceOf(address(this));
(uint256 amountOut, uint256 haircut) = router.swapTokensForTokens(
router.swapTokensForTokens(
// Convert to `buyToken` along this path.
_path,
// pool to swap on

View File

@@ -1,6 +1,6 @@
{
"name": "@0x/contracts-zero-ex",
"version": "0.33.0",
"version": "0.34.0",
"engines": {
"node": ">=6.12"
},
@@ -41,9 +41,9 @@
"rollback": "node ./lib/scripts/rollback.js"
},
"config": {
"publicInterfaceContracts": "IZeroEx,ZeroEx,FullMigration,InitialMigration,IFlashWallet,IERC20Transformer,IOwnableFeature,ISimpleFunctionRegistryFeature,ITransformERC20Feature,FillQuoteTransformer,PayTakerTransformer,PositiveSlippageFeeTransformer,WethTransformer,OwnableFeature,SimpleFunctionRegistryFeature,TransformERC20Feature,AffiliateFeeTransformer,MetaTransactionsFeature,LogMetadataTransformer,BridgeAdapter,LiquidityProviderFeature,ILiquidityProviderFeature,NativeOrdersFeature,INativeOrdersFeature,FeeCollectorController,FeeCollector,CurveLiquidityProvider,BatchFillNativeOrdersFeature,IBatchFillNativeOrdersFeature,MultiplexFeature,IMultiplexFeature,OtcOrdersFeature,IOtcOrdersFeature",
"publicInterfaceContracts": "IZeroEx,ZeroEx,FullMigration,InitialMigration,IFlashWallet,IERC20Transformer,IOwnableFeature,ISimpleFunctionRegistryFeature,ITransformERC20Feature,FillQuoteTransformer,PayTakerTransformer,PositiveSlippageFeeTransformer,WethTransformer,OwnableFeature,SimpleFunctionRegistryFeature,TransformERC20Feature,AffiliateFeeTransformer,MetaTransactionsFeature,LogMetadataTransformer,LiquidityProviderFeature,ILiquidityProviderFeature,NativeOrdersFeature,INativeOrdersFeature,FeeCollectorController,FeeCollector,CurveLiquidityProvider,BatchFillNativeOrdersFeature,IBatchFillNativeOrdersFeature,MultiplexFeature,IMultiplexFeature,OtcOrdersFeature,IOtcOrdersFeature,AvalancheBridgeAdapter,BSCBridgeAdapter,CeloBridgeAdapter,EthereumBridgeAdapter,FantomBridgeAdapter,OptimismBridgeAdapter,PolygonBridgeAdapter",
"abis:comment": "This list is auto-generated by contracts-gen. Don't edit manually.",
"abis": "./test/generated-artifacts/@(AffiliateFeeTransformer|BatchFillNativeOrdersFeature|BootstrapFeature|BridgeAdapter|BridgeProtocols|CurveLiquidityProvider|ERC1155OrdersFeature|ERC165Feature|ERC721OrdersFeature|FeeCollector|FeeCollectorController|FillQuoteTransformer|FixinCommon|FixinEIP712|FixinERC1155Spender|FixinERC721Spender|FixinProtocolFees|FixinReentrancyGuard|FixinTokenSpender|FlashWallet|FullMigration|FundRecoveryFeature|IBatchFillNativeOrdersFeature|IBootstrapFeature|IBridgeAdapter|IERC1155OrdersFeature|IERC1155Token|IERC165Feature|IERC20Bridge|IERC20Transformer|IERC721OrdersFeature|IERC721Token|IFeature|IFeeRecipient|IFlashWallet|IFundRecoveryFeature|ILiquidityProvider|ILiquidityProviderFeature|ILiquidityProviderSandbox|IMetaTransactionsFeature|IMooniswapPool|IMultiplexFeature|INativeOrdersEvents|INativeOrdersFeature|IOtcOrdersFeature|IOwnableFeature|IPancakeSwapFeature|IPropertyValidator|ISimpleFunctionRegistryFeature|IStaking|ITakerCallback|ITestSimpleFunctionRegistryFeature|ITokenSpenderFeature|ITransformERC20Feature|IUniswapFeature|IUniswapV2Pair|IUniswapV3Feature|IUniswapV3Pool|IZeroEx|InitialMigration|LibBootstrap|LibCommonRichErrors|LibERC1155OrdersStorage|LibERC20Transformer|LibERC721OrdersStorage|LibFeeCollector|LibLiquidityProviderRichErrors|LibMetaTransactionsRichErrors|LibMetaTransactionsStorage|LibMigrate|LibNFTOrder|LibNFTOrdersRichErrors|LibNativeOrder|LibNativeOrdersRichErrors|LibNativeOrdersStorage|LibOtcOrdersStorage|LibOwnableRichErrors|LibOwnableStorage|LibProxyRichErrors|LibProxyStorage|LibReentrancyGuardStorage|LibSignature|LibSignatureRichErrors|LibSimpleFunctionRegistryRichErrors|LibSimpleFunctionRegistryStorage|LibStorage|LibTransformERC20RichErrors|LibTransformERC20Storage|LibWalletRichErrors|LiquidityProviderFeature|LiquidityProviderSandbox|LogMetadataTransformer|MetaTransactionsFeature|MixinAaveV2|MixinBalancer|MixinBalancerV2|MixinBalancerV2Batch|MixinBancor|MixinCoFiX|MixinCompound|MixinCryptoCom|MixinCurve|MixinCurveV2|MixinDodo|MixinDodoV2|MixinGMX|MixinKyber|MixinKyberDmm|MixinLido|MixinMStable|MixinMakerPSM|MixinMooniswap|MixinNerve|MixinOasis|MixinPlatypus|MixinShell|MixinUniswap|MixinUniswapV2|MixinUniswapV3|MixinZeroExBridge|MooniswapLiquidityProvider|MultiplexFeature|MultiplexLiquidityProvider|MultiplexOtc|MultiplexRfq|MultiplexTransformERC20|MultiplexUniswapV2|MultiplexUniswapV3|NFTOrders|NativeOrdersCancellation|NativeOrdersFeature|NativeOrdersInfo|NativeOrdersProtocolFees|NativeOrdersSettlement|OtcOrdersFeature|OwnableFeature|PancakeSwapFeature|PayTakerTransformer|PermissionlessTransformerDeployer|PositiveSlippageFeeTransformer|SimpleFunctionRegistryFeature|TestBridge|TestCallTarget|TestCurve|TestDelegateCaller|TestFeeCollectorController|TestFeeRecipient|TestFillQuoteTransformerBridge|TestFillQuoteTransformerExchange|TestFillQuoteTransformerHost|TestFixinProtocolFees|TestFixinTokenSpender|TestFullMigration|TestInitialMigration|TestLibNativeOrder|TestLibSignature|TestLiquidityProvider|TestMetaTransactionsNativeOrdersFeature|TestMetaTransactionsTransformERC20Feature|TestMigrator|TestMintTokenERC20Transformer|TestMintableERC1155Token|TestMintableERC20Token|TestMintableERC721Token|TestMooniswap|TestNFTOrderPresigner|TestNativeOrdersFeature|TestNoEthRecipient|TestOrderSignerRegistryWithContractWallet|TestPermissionlessTransformerDeployerSuicidal|TestPermissionlessTransformerDeployerTransformer|TestPropertyValidator|TestRfqOriginRegistration|TestSimpleFunctionRegistryFeatureImpl1|TestSimpleFunctionRegistryFeatureImpl2|TestStaking|TestTokenSpenderERC20Token|TestTransformERC20|TestTransformerBase|TestTransformerDeployerTransformer|TestTransformerHost|TestUniswapV2Factory|TestUniswapV2Pool|TestUniswapV3Factory|TestUniswapV3Feature|TestUniswapV3Pool|TestWeth|TestWethTransformerHost|TestZeroExFeature|TransformERC20Feature|Transformer|TransformerDeployer|UniswapFeature|UniswapV3Feature|WethTransformer|ZeroEx|ZeroExOptimized).json"
"abis": "./test/generated-artifacts/@(AbstractBridgeAdapter|AffiliateFeeTransformer|AvalancheBridgeAdapter|BSCBridgeAdapter|BatchFillNativeOrdersFeature|BootstrapFeature|BridgeProtocols|CeloBridgeAdapter|CurveLiquidityProvider|ERC1155OrdersFeature|ERC165Feature|ERC721OrdersFeature|EthereumBridgeAdapter|FantomBridgeAdapter|FeeCollector|FeeCollectorController|FillQuoteTransformer|FixinCommon|FixinEIP712|FixinERC1155Spender|FixinERC721Spender|FixinProtocolFees|FixinReentrancyGuard|FixinTokenSpender|FlashWallet|FullMigration|FundRecoveryFeature|IBatchFillNativeOrdersFeature|IBootstrapFeature|IBridgeAdapter|IERC1155OrdersFeature|IERC1155Token|IERC165Feature|IERC20Bridge|IERC20Transformer|IERC721OrdersFeature|IERC721Token|IFeature|IFeeRecipient|IFlashWallet|IFundRecoveryFeature|ILiquidityProvider|ILiquidityProviderFeature|ILiquidityProviderSandbox|IMetaTransactionsFeature|IMooniswapPool|IMultiplexFeature|INativeOrdersEvents|INativeOrdersFeature|IOtcOrdersFeature|IOwnableFeature|IPancakeSwapFeature|IPropertyValidator|ISimpleFunctionRegistryFeature|IStaking|ITakerCallback|ITestSimpleFunctionRegistryFeature|ITokenSpenderFeature|ITransformERC20Feature|IUniswapFeature|IUniswapV2Pair|IUniswapV3Feature|IUniswapV3Pool|IZeroEx|InitialMigration|LibBootstrap|LibCommonRichErrors|LibERC1155OrdersStorage|LibERC20Transformer|LibERC721OrdersStorage|LibFeeCollector|LibLiquidityProviderRichErrors|LibMetaTransactionsRichErrors|LibMetaTransactionsStorage|LibMigrate|LibNFTOrder|LibNFTOrdersRichErrors|LibNativeOrder|LibNativeOrdersRichErrors|LibNativeOrdersStorage|LibOtcOrdersStorage|LibOwnableRichErrors|LibOwnableStorage|LibProxyRichErrors|LibProxyStorage|LibReentrancyGuardStorage|LibSignature|LibSignatureRichErrors|LibSimpleFunctionRegistryRichErrors|LibSimpleFunctionRegistryStorage|LibStorage|LibTransformERC20RichErrors|LibTransformERC20Storage|LibWalletRichErrors|LiquidityProviderFeature|LiquidityProviderSandbox|LogMetadataTransformer|MetaTransactionsFeature|MixinAaveV2|MixinBalancer|MixinBalancerV2|MixinBalancerV2Batch|MixinBancor|MixinBancorV3|MixinCompound|MixinCryptoCom|MixinCurve|MixinCurveV2|MixinDodo|MixinDodoV2|MixinGMX|MixinKyberDmm|MixinLido|MixinMStable|MixinMakerPSM|MixinMooniswap|MixinNerve|MixinPlatypus|MixinShell|MixinUniswap|MixinUniswapV2|MixinUniswapV3|MixinZeroExBridge|MooniswapLiquidityProvider|MultiplexFeature|MultiplexLiquidityProvider|MultiplexOtc|MultiplexRfq|MultiplexTransformERC20|MultiplexUniswapV2|MultiplexUniswapV3|NFTOrders|NativeOrdersCancellation|NativeOrdersFeature|NativeOrdersInfo|NativeOrdersProtocolFees|NativeOrdersSettlement|OptimismBridgeAdapter|OtcOrdersFeature|OwnableFeature|PancakeSwapFeature|PayTakerTransformer|PermissionlessTransformerDeployer|PolygonBridgeAdapter|PositiveSlippageFeeTransformer|SimpleFunctionRegistryFeature|TestBridge|TestCallTarget|TestCurve|TestDelegateCaller|TestFeeCollectorController|TestFeeRecipient|TestFillQuoteTransformerBridge|TestFillQuoteTransformerExchange|TestFillQuoteTransformerHost|TestFixinProtocolFees|TestFixinTokenSpender|TestFullMigration|TestInitialMigration|TestLibNativeOrder|TestLibSignature|TestLiquidityProvider|TestMetaTransactionsNativeOrdersFeature|TestMetaTransactionsTransformERC20Feature|TestMigrator|TestMintTokenERC20Transformer|TestMintableERC1155Token|TestMintableERC20Token|TestMintableERC721Token|TestMooniswap|TestNFTOrderPresigner|TestNativeOrdersFeature|TestNoEthRecipient|TestOrderSignerRegistryWithContractWallet|TestPermissionlessTransformerDeployerSuicidal|TestPermissionlessTransformerDeployerTransformer|TestPropertyValidator|TestRfqOriginRegistration|TestSimpleFunctionRegistryFeatureImpl1|TestSimpleFunctionRegistryFeatureImpl2|TestStaking|TestTokenSpenderERC20Token|TestTransformERC20|TestTransformerBase|TestTransformerDeployerTransformer|TestTransformerHost|TestUniswapV2Factory|TestUniswapV2Pool|TestUniswapV3Factory|TestUniswapV3Feature|TestUniswapV3Pool|TestWeth|TestWethTransformerHost|TestZeroExFeature|TransformERC20Feature|Transformer|TransformerDeployer|UniswapFeature|UniswapV3Feature|WethTransformer|ZeroEx|ZeroExOptimized).json"
},
"repository": {
"type": "git",
@@ -56,10 +56,10 @@
"homepage": "https://github.com/0xProject/protocol/tree/main/contracts/zero-ex",
"devDependencies": {
"@0x/abi-gen": "^5.8.0",
"@0x/contract-addresses": "^6.14.0",
"@0x/contracts-erc20": "^3.3.30",
"@0x/contract-addresses": "^6.15.0",
"@0x/contracts-erc20": "^3.3.31",
"@0x/contracts-gen": "^2.0.46",
"@0x/contracts-test-utils": "^5.4.21",
"@0x/contracts-test-utils": "^5.4.22",
"@0x/dev-utils": "^4.2.14",
"@0x/order-utils": "^10.4.28",
"@0x/sol-compiler": "^4.8.1",
@@ -83,7 +83,7 @@
},
"dependencies": {
"@0x/base-contract": "^6.5.0",
"@0x/protocol-utils": "^11.13.0",
"@0x/protocol-utils": "^11.14.0",
"@0x/subproviders": "^6.6.5",
"@0x/types": "^3.3.6",
"@0x/typescript-typings": "^5.3.1",

View File

@@ -6,9 +6,13 @@
import { ContractArtifact } from 'ethereum-types';
import * as AffiliateFeeTransformer from '../generated-artifacts/AffiliateFeeTransformer.json';
import * as AvalancheBridgeAdapter from '../generated-artifacts/AvalancheBridgeAdapter.json';
import * as BatchFillNativeOrdersFeature from '../generated-artifacts/BatchFillNativeOrdersFeature.json';
import * as BridgeAdapter from '../generated-artifacts/BridgeAdapter.json';
import * as BSCBridgeAdapter from '../generated-artifacts/BSCBridgeAdapter.json';
import * as CeloBridgeAdapter from '../generated-artifacts/CeloBridgeAdapter.json';
import * as CurveLiquidityProvider from '../generated-artifacts/CurveLiquidityProvider.json';
import * as EthereumBridgeAdapter from '../generated-artifacts/EthereumBridgeAdapter.json';
import * as FantomBridgeAdapter from '../generated-artifacts/FantomBridgeAdapter.json';
import * as FeeCollector from '../generated-artifacts/FeeCollector.json';
import * as FeeCollectorController from '../generated-artifacts/FeeCollectorController.json';
import * as FillQuoteTransformer from '../generated-artifacts/FillQuoteTransformer.json';
@@ -30,9 +34,11 @@ import * as LogMetadataTransformer from '../generated-artifacts/LogMetadataTrans
import * as MetaTransactionsFeature from '../generated-artifacts/MetaTransactionsFeature.json';
import * as MultiplexFeature from '../generated-artifacts/MultiplexFeature.json';
import * as NativeOrdersFeature from '../generated-artifacts/NativeOrdersFeature.json';
import * as OptimismBridgeAdapter from '../generated-artifacts/OptimismBridgeAdapter.json';
import * as OtcOrdersFeature from '../generated-artifacts/OtcOrdersFeature.json';
import * as OwnableFeature from '../generated-artifacts/OwnableFeature.json';
import * as PayTakerTransformer from '../generated-artifacts/PayTakerTransformer.json';
import * as PolygonBridgeAdapter from '../generated-artifacts/PolygonBridgeAdapter.json';
import * as PositiveSlippageFeeTransformer from '../generated-artifacts/PositiveSlippageFeeTransformer.json';
import * as SimpleFunctionRegistryFeature from '../generated-artifacts/SimpleFunctionRegistryFeature.json';
import * as TransformERC20Feature from '../generated-artifacts/TransformERC20Feature.json';
@@ -58,7 +64,6 @@ export const artifacts = {
AffiliateFeeTransformer: AffiliateFeeTransformer as ContractArtifact,
MetaTransactionsFeature: MetaTransactionsFeature as ContractArtifact,
LogMetadataTransformer: LogMetadataTransformer as ContractArtifact,
BridgeAdapter: BridgeAdapter as ContractArtifact,
LiquidityProviderFeature: LiquidityProviderFeature as ContractArtifact,
ILiquidityProviderFeature: ILiquidityProviderFeature as ContractArtifact,
NativeOrdersFeature: NativeOrdersFeature as ContractArtifact,
@@ -72,4 +77,11 @@ export const artifacts = {
IMultiplexFeature: IMultiplexFeature as ContractArtifact,
OtcOrdersFeature: OtcOrdersFeature as ContractArtifact,
IOtcOrdersFeature: IOtcOrdersFeature as ContractArtifact,
AvalancheBridgeAdapter: AvalancheBridgeAdapter as ContractArtifact,
BSCBridgeAdapter: BSCBridgeAdapter as ContractArtifact,
CeloBridgeAdapter: CeloBridgeAdapter as ContractArtifact,
EthereumBridgeAdapter: EthereumBridgeAdapter as ContractArtifact,
FantomBridgeAdapter: FantomBridgeAdapter as ContractArtifact,
OptimismBridgeAdapter: OptimismBridgeAdapter as ContractArtifact,
PolygonBridgeAdapter: PolygonBridgeAdapter as ContractArtifact,
};

View File

@@ -35,7 +35,11 @@ export * from './bloom_filter_utils';
export { GREEDY_TOKENS } from './constants';
export {
AffiliateFeeTransformerContract,
BridgeAdapterContract,
AvalancheBridgeAdapterContract,
BSCBridgeAdapterContract,
CeloBridgeAdapterContract,
EthereumBridgeAdapterContract,
FantomBridgeAdapterContract,
FillQuoteTransformerContract,
IOwnableFeatureContract,
IOwnableFeatureEvents,
@@ -45,7 +49,9 @@ export {
IZeroExContract,
LogMetadataTransformerContract,
MultiplexFeatureContract,
OptimismBridgeAdapterContract,
PayTakerTransformerContract,
PolygonBridgeAdapterContract,
PositiveSlippageFeeTransformerContract,
TransformERC20FeatureContract,
WethTransformerContract,

View File

@@ -4,9 +4,13 @@
* -----------------------------------------------------------------------------
*/
export * from '../generated-wrappers/affiliate_fee_transformer';
export * from '../generated-wrappers/avalanche_bridge_adapter';
export * from '../generated-wrappers/b_s_c_bridge_adapter';
export * from '../generated-wrappers/batch_fill_native_orders_feature';
export * from '../generated-wrappers/bridge_adapter';
export * from '../generated-wrappers/celo_bridge_adapter';
export * from '../generated-wrappers/curve_liquidity_provider';
export * from '../generated-wrappers/ethereum_bridge_adapter';
export * from '../generated-wrappers/fantom_bridge_adapter';
export * from '../generated-wrappers/fee_collector';
export * from '../generated-wrappers/fee_collector_controller';
export * from '../generated-wrappers/fill_quote_transformer';
@@ -28,9 +32,11 @@ export * from '../generated-wrappers/log_metadata_transformer';
export * from '../generated-wrappers/meta_transactions_feature';
export * from '../generated-wrappers/multiplex_feature';
export * from '../generated-wrappers/native_orders_feature';
export * from '../generated-wrappers/optimism_bridge_adapter';
export * from '../generated-wrappers/otc_orders_feature';
export * from '../generated-wrappers/ownable_feature';
export * from '../generated-wrappers/pay_taker_transformer';
export * from '../generated-wrappers/polygon_bridge_adapter';
export * from '../generated-wrappers/positive_slippage_fee_transformer';
export * from '../generated-wrappers/simple_function_registry_feature';
export * from '../generated-wrappers/transform_erc20_feature';

View File

@@ -5,15 +5,20 @@
*/
import { ContractArtifact } from 'ethereum-types';
import * as AbstractBridgeAdapter from '../test/generated-artifacts/AbstractBridgeAdapter.json';
import * as AffiliateFeeTransformer from '../test/generated-artifacts/AffiliateFeeTransformer.json';
import * as AvalancheBridgeAdapter from '../test/generated-artifacts/AvalancheBridgeAdapter.json';
import * as BatchFillNativeOrdersFeature from '../test/generated-artifacts/BatchFillNativeOrdersFeature.json';
import * as BootstrapFeature from '../test/generated-artifacts/BootstrapFeature.json';
import * as BridgeAdapter from '../test/generated-artifacts/BridgeAdapter.json';
import * as BridgeProtocols from '../test/generated-artifacts/BridgeProtocols.json';
import * as BSCBridgeAdapter from '../test/generated-artifacts/BSCBridgeAdapter.json';
import * as CeloBridgeAdapter from '../test/generated-artifacts/CeloBridgeAdapter.json';
import * as CurveLiquidityProvider from '../test/generated-artifacts/CurveLiquidityProvider.json';
import * as ERC1155OrdersFeature from '../test/generated-artifacts/ERC1155OrdersFeature.json';
import * as ERC165Feature from '../test/generated-artifacts/ERC165Feature.json';
import * as ERC721OrdersFeature from '../test/generated-artifacts/ERC721OrdersFeature.json';
import * as EthereumBridgeAdapter from '../test/generated-artifacts/EthereumBridgeAdapter.json';
import * as FantomBridgeAdapter from '../test/generated-artifacts/FantomBridgeAdapter.json';
import * as FeeCollector from '../test/generated-artifacts/FeeCollector.json';
import * as FeeCollectorController from '../test/generated-artifacts/FeeCollectorController.json';
import * as FillQuoteTransformer from '../test/generated-artifacts/FillQuoteTransformer.json';
@@ -103,7 +108,7 @@ import * as MixinBalancer from '../test/generated-artifacts/MixinBalancer.json';
import * as MixinBalancerV2 from '../test/generated-artifacts/MixinBalancerV2.json';
import * as MixinBalancerV2Batch from '../test/generated-artifacts/MixinBalancerV2Batch.json';
import * as MixinBancor from '../test/generated-artifacts/MixinBancor.json';
import * as MixinCoFiX from '../test/generated-artifacts/MixinCoFiX.json';
import * as MixinBancorV3 from '../test/generated-artifacts/MixinBancorV3.json';
import * as MixinCompound from '../test/generated-artifacts/MixinCompound.json';
import * as MixinCryptoCom from '../test/generated-artifacts/MixinCryptoCom.json';
import * as MixinCurve from '../test/generated-artifacts/MixinCurve.json';
@@ -111,14 +116,12 @@ import * as MixinCurveV2 from '../test/generated-artifacts/MixinCurveV2.json';
import * as MixinDodo from '../test/generated-artifacts/MixinDodo.json';
import * as MixinDodoV2 from '../test/generated-artifacts/MixinDodoV2.json';
import * as MixinGMX from '../test/generated-artifacts/MixinGMX.json';
import * as MixinKyber from '../test/generated-artifacts/MixinKyber.json';
import * as MixinKyberDmm from '../test/generated-artifacts/MixinKyberDmm.json';
import * as MixinLido from '../test/generated-artifacts/MixinLido.json';
import * as MixinMakerPSM from '../test/generated-artifacts/MixinMakerPSM.json';
import * as MixinMooniswap from '../test/generated-artifacts/MixinMooniswap.json';
import * as MixinMStable from '../test/generated-artifacts/MixinMStable.json';
import * as MixinNerve from '../test/generated-artifacts/MixinNerve.json';
import * as MixinOasis from '../test/generated-artifacts/MixinOasis.json';
import * as MixinPlatypus from '../test/generated-artifacts/MixinPlatypus.json';
import * as MixinShell from '../test/generated-artifacts/MixinShell.json';
import * as MixinUniswap from '../test/generated-artifacts/MixinUniswap.json';
@@ -139,11 +142,13 @@ import * as NativeOrdersInfo from '../test/generated-artifacts/NativeOrdersInfo.
import * as NativeOrdersProtocolFees from '../test/generated-artifacts/NativeOrdersProtocolFees.json';
import * as NativeOrdersSettlement from '../test/generated-artifacts/NativeOrdersSettlement.json';
import * as NFTOrders from '../test/generated-artifacts/NFTOrders.json';
import * as OptimismBridgeAdapter from '../test/generated-artifacts/OptimismBridgeAdapter.json';
import * as OtcOrdersFeature from '../test/generated-artifacts/OtcOrdersFeature.json';
import * as OwnableFeature from '../test/generated-artifacts/OwnableFeature.json';
import * as PancakeSwapFeature from '../test/generated-artifacts/PancakeSwapFeature.json';
import * as PayTakerTransformer from '../test/generated-artifacts/PayTakerTransformer.json';
import * as PermissionlessTransformerDeployer from '../test/generated-artifacts/PermissionlessTransformerDeployer.json';
import * as PolygonBridgeAdapter from '../test/generated-artifacts/PolygonBridgeAdapter.json';
import * as PositiveSlippageFeeTransformer from '../test/generated-artifacts/PositiveSlippageFeeTransformer.json';
import * as SimpleFunctionRegistryFeature from '../test/generated-artifacts/SimpleFunctionRegistryFeature.json';
import * as TestBridge from '../test/generated-artifacts/TestBridge.json';
@@ -310,15 +315,22 @@ export const artifacts = {
PositiveSlippageFeeTransformer: PositiveSlippageFeeTransformer as ContractArtifact,
Transformer: Transformer as ContractArtifact,
WethTransformer: WethTransformer as ContractArtifact,
BridgeAdapter: BridgeAdapter as ContractArtifact,
AbstractBridgeAdapter: AbstractBridgeAdapter as ContractArtifact,
AvalancheBridgeAdapter: AvalancheBridgeAdapter as ContractArtifact,
BSCBridgeAdapter: BSCBridgeAdapter as ContractArtifact,
BridgeProtocols: BridgeProtocols as ContractArtifact,
CeloBridgeAdapter: CeloBridgeAdapter as ContractArtifact,
EthereumBridgeAdapter: EthereumBridgeAdapter as ContractArtifact,
FantomBridgeAdapter: FantomBridgeAdapter as ContractArtifact,
IBridgeAdapter: IBridgeAdapter as ContractArtifact,
OptimismBridgeAdapter: OptimismBridgeAdapter as ContractArtifact,
PolygonBridgeAdapter: PolygonBridgeAdapter as ContractArtifact,
MixinAaveV2: MixinAaveV2 as ContractArtifact,
MixinBalancer: MixinBalancer as ContractArtifact,
MixinBalancerV2: MixinBalancerV2 as ContractArtifact,
MixinBalancerV2Batch: MixinBalancerV2Batch as ContractArtifact,
MixinBancor: MixinBancor as ContractArtifact,
MixinCoFiX: MixinCoFiX as ContractArtifact,
MixinBancorV3: MixinBancorV3 as ContractArtifact,
MixinCompound: MixinCompound as ContractArtifact,
MixinCryptoCom: MixinCryptoCom as ContractArtifact,
MixinCurve: MixinCurve as ContractArtifact,
@@ -326,14 +338,12 @@ export const artifacts = {
MixinDodo: MixinDodo as ContractArtifact,
MixinDodoV2: MixinDodoV2 as ContractArtifact,
MixinGMX: MixinGMX as ContractArtifact,
MixinKyber: MixinKyber as ContractArtifact,
MixinKyberDmm: MixinKyberDmm as ContractArtifact,
MixinLido: MixinLido as ContractArtifact,
MixinMStable: MixinMStable as ContractArtifact,
MixinMakerPSM: MixinMakerPSM as ContractArtifact,
MixinMooniswap: MixinMooniswap as ContractArtifact,
MixinNerve: MixinNerve as ContractArtifact,
MixinOasis: MixinOasis as ContractArtifact,
MixinPlatypus: MixinPlatypus as ContractArtifact,
MixinShell: MixinShell as ContractArtifact,
MixinUniswap: MixinUniswap as ContractArtifact,

View File

@@ -28,7 +28,7 @@ import { artifacts } from '../artifacts';
import { TestFillQuoteTransformerBridgeContract } from '../generated-wrappers/test_fill_quote_transformer_bridge';
import { getRandomLimitOrder, getRandomRfqOrder } from '../utils/orders';
import {
BridgeAdapterContract,
EthereumBridgeAdapterContract,
FillQuoteTransformerContract,
TestFillQuoteTransformerExchangeContract,
TestFillQuoteTransformerHostContract,
@@ -52,7 +52,8 @@ blockchainTests.resets('FillQuoteTransformer', env => {
let singleProtocolFee: BigNumber;
const GAS_PRICE = 1337;
const TEST_BRIDGE_SOURCE = hexUtils.random(32);
// Left half is 0, corresponding to BridgeProtocol.Unknown
const TEST_BRIDGE_SOURCE = hexUtils.leftPad(hexUtils.random(16), 32);
const HIGH_BIT = new BigNumber(2).pow(255);
const REVERT_AMOUNT = new BigNumber('0xdeadbeef');
@@ -64,8 +65,8 @@ blockchainTests.resets('FillQuoteTransformer', env => {
env.txDefaults,
artifacts,
);
const bridgeAdapter = await BridgeAdapterContract.deployFrom0xArtifactAsync(
artifacts.BridgeAdapter,
const bridgeAdapter = await EthereumBridgeAdapterContract.deployFrom0xArtifactAsync(
artifacts.EthereumBridgeAdapter,
env.provider,
env.txDefaults,
artifacts,

View File

@@ -3,15 +3,20 @@
* Warning: This file is auto-generated by contracts-gen. Don't edit manually.
* -----------------------------------------------------------------------------
*/
export * from '../test/generated-wrappers/abstract_bridge_adapter';
export * from '../test/generated-wrappers/affiliate_fee_transformer';
export * from '../test/generated-wrappers/avalanche_bridge_adapter';
export * from '../test/generated-wrappers/b_s_c_bridge_adapter';
export * from '../test/generated-wrappers/batch_fill_native_orders_feature';
export * from '../test/generated-wrappers/bootstrap_feature';
export * from '../test/generated-wrappers/bridge_adapter';
export * from '../test/generated-wrappers/bridge_protocols';
export * from '../test/generated-wrappers/celo_bridge_adapter';
export * from '../test/generated-wrappers/curve_liquidity_provider';
export * from '../test/generated-wrappers/erc1155_orders_feature';
export * from '../test/generated-wrappers/erc165_feature';
export * from '../test/generated-wrappers/erc721_orders_feature';
export * from '../test/generated-wrappers/ethereum_bridge_adapter';
export * from '../test/generated-wrappers/fantom_bridge_adapter';
export * from '../test/generated-wrappers/fee_collector';
export * from '../test/generated-wrappers/fee_collector_controller';
export * from '../test/generated-wrappers/fill_quote_transformer';
@@ -101,7 +106,7 @@ export * from '../test/generated-wrappers/mixin_balancer';
export * from '../test/generated-wrappers/mixin_balancer_v2';
export * from '../test/generated-wrappers/mixin_balancer_v2_batch';
export * from '../test/generated-wrappers/mixin_bancor';
export * from '../test/generated-wrappers/mixin_co_fi_x';
export * from '../test/generated-wrappers/mixin_bancor_v3';
export * from '../test/generated-wrappers/mixin_compound';
export * from '../test/generated-wrappers/mixin_crypto_com';
export * from '../test/generated-wrappers/mixin_curve';
@@ -109,14 +114,12 @@ export * from '../test/generated-wrappers/mixin_curve_v2';
export * from '../test/generated-wrappers/mixin_dodo';
export * from '../test/generated-wrappers/mixin_dodo_v2';
export * from '../test/generated-wrappers/mixin_g_m_x';
export * from '../test/generated-wrappers/mixin_kyber';
export * from '../test/generated-wrappers/mixin_kyber_dmm';
export * from '../test/generated-wrappers/mixin_lido';
export * from '../test/generated-wrappers/mixin_m_stable';
export * from '../test/generated-wrappers/mixin_maker_p_s_m';
export * from '../test/generated-wrappers/mixin_mooniswap';
export * from '../test/generated-wrappers/mixin_nerve';
export * from '../test/generated-wrappers/mixin_oasis';
export * from '../test/generated-wrappers/mixin_platypus';
export * from '../test/generated-wrappers/mixin_shell';
export * from '../test/generated-wrappers/mixin_uniswap';
@@ -137,11 +140,13 @@ export * from '../test/generated-wrappers/native_orders_feature';
export * from '../test/generated-wrappers/native_orders_info';
export * from '../test/generated-wrappers/native_orders_protocol_fees';
export * from '../test/generated-wrappers/native_orders_settlement';
export * from '../test/generated-wrappers/optimism_bridge_adapter';
export * from '../test/generated-wrappers/otc_orders_feature';
export * from '../test/generated-wrappers/ownable_feature';
export * from '../test/generated-wrappers/pancake_swap_feature';
export * from '../test/generated-wrappers/pay_taker_transformer';
export * from '../test/generated-wrappers/permissionless_transformer_deployer';
export * from '../test/generated-wrappers/polygon_bridge_adapter';
export * from '../test/generated-wrappers/positive_slippage_fee_transformer';
export * from '../test/generated-wrappers/simple_function_registry_feature';
export * from '../test/generated-wrappers/test_bridge';

View File

@@ -4,9 +4,13 @@
"include": ["./src/**/*", "./test/**/*", "./generated-wrappers/**/*", "./scripts/**/*"],
"files": [
"generated-artifacts/AffiliateFeeTransformer.json",
"generated-artifacts/AvalancheBridgeAdapter.json",
"generated-artifacts/BSCBridgeAdapter.json",
"generated-artifacts/BatchFillNativeOrdersFeature.json",
"generated-artifacts/BridgeAdapter.json",
"generated-artifacts/CeloBridgeAdapter.json",
"generated-artifacts/CurveLiquidityProvider.json",
"generated-artifacts/EthereumBridgeAdapter.json",
"generated-artifacts/FantomBridgeAdapter.json",
"generated-artifacts/FeeCollector.json",
"generated-artifacts/FeeCollectorController.json",
"generated-artifacts/FillQuoteTransformer.json",
@@ -28,23 +32,30 @@
"generated-artifacts/MetaTransactionsFeature.json",
"generated-artifacts/MultiplexFeature.json",
"generated-artifacts/NativeOrdersFeature.json",
"generated-artifacts/OptimismBridgeAdapter.json",
"generated-artifacts/OtcOrdersFeature.json",
"generated-artifacts/OwnableFeature.json",
"generated-artifacts/PayTakerTransformer.json",
"generated-artifacts/PolygonBridgeAdapter.json",
"generated-artifacts/PositiveSlippageFeeTransformer.json",
"generated-artifacts/SimpleFunctionRegistryFeature.json",
"generated-artifacts/TransformERC20Feature.json",
"generated-artifacts/WethTransformer.json",
"generated-artifacts/ZeroEx.json",
"test/generated-artifacts/AbstractBridgeAdapter.json",
"test/generated-artifacts/AffiliateFeeTransformer.json",
"test/generated-artifacts/AvalancheBridgeAdapter.json",
"test/generated-artifacts/BSCBridgeAdapter.json",
"test/generated-artifacts/BatchFillNativeOrdersFeature.json",
"test/generated-artifacts/BootstrapFeature.json",
"test/generated-artifacts/BridgeAdapter.json",
"test/generated-artifacts/BridgeProtocols.json",
"test/generated-artifacts/CeloBridgeAdapter.json",
"test/generated-artifacts/CurveLiquidityProvider.json",
"test/generated-artifacts/ERC1155OrdersFeature.json",
"test/generated-artifacts/ERC165Feature.json",
"test/generated-artifacts/ERC721OrdersFeature.json",
"test/generated-artifacts/EthereumBridgeAdapter.json",
"test/generated-artifacts/FantomBridgeAdapter.json",
"test/generated-artifacts/FeeCollector.json",
"test/generated-artifacts/FeeCollectorController.json",
"test/generated-artifacts/FillQuoteTransformer.json",
@@ -134,7 +145,7 @@
"test/generated-artifacts/MixinBalancerV2.json",
"test/generated-artifacts/MixinBalancerV2Batch.json",
"test/generated-artifacts/MixinBancor.json",
"test/generated-artifacts/MixinCoFiX.json",
"test/generated-artifacts/MixinBancorV3.json",
"test/generated-artifacts/MixinCompound.json",
"test/generated-artifacts/MixinCryptoCom.json",
"test/generated-artifacts/MixinCurve.json",
@@ -142,14 +153,12 @@
"test/generated-artifacts/MixinDodo.json",
"test/generated-artifacts/MixinDodoV2.json",
"test/generated-artifacts/MixinGMX.json",
"test/generated-artifacts/MixinKyber.json",
"test/generated-artifacts/MixinKyberDmm.json",
"test/generated-artifacts/MixinLido.json",
"test/generated-artifacts/MixinMStable.json",
"test/generated-artifacts/MixinMakerPSM.json",
"test/generated-artifacts/MixinMooniswap.json",
"test/generated-artifacts/MixinNerve.json",
"test/generated-artifacts/MixinOasis.json",
"test/generated-artifacts/MixinPlatypus.json",
"test/generated-artifacts/MixinShell.json",
"test/generated-artifacts/MixinUniswap.json",
@@ -170,11 +179,13 @@
"test/generated-artifacts/NativeOrdersInfo.json",
"test/generated-artifacts/NativeOrdersProtocolFees.json",
"test/generated-artifacts/NativeOrdersSettlement.json",
"test/generated-artifacts/OptimismBridgeAdapter.json",
"test/generated-artifacts/OtcOrdersFeature.json",
"test/generated-artifacts/OwnableFeature.json",
"test/generated-artifacts/PancakeSwapFeature.json",
"test/generated-artifacts/PayTakerTransformer.json",
"test/generated-artifacts/PermissionlessTransformerDeployer.json",
"test/generated-artifacts/PolygonBridgeAdapter.json",
"test/generated-artifacts/PositiveSlippageFeeTransformer.json",
"test/generated-artifacts/SimpleFunctionRegistryFeature.json",
"test/generated-artifacts/TestBridge.json",

View File

@@ -52,10 +52,10 @@
},
"config": {
"contractsPackages": "@0x/contracts-erc20 @0x/contracts-test-utils @0x/contracts-utils @0x/contracts-zero-ex @0x/contracts-treasury",
"nonContractPackages": "@0x/migrations @0x/contract-wrappers @0x/contract-addresses @0x/contract-artifacts @0x/contract-wrappers-test @0x/asset-swapper",
"nonContractPackages": "@0x/contract-wrappers @0x/contract-addresses @0x/contract-artifacts @0x/contract-wrappers-test @0x/asset-swapper",
"ignoreTestsForPackages": "",
"mnemonic": "concert load couple harbor equip island argue ramp clarify fence smart topic",
"packagesWithDocPages": "@0x/contract-wrappers @0x/migrations",
"packagesWithDocPages": "@0x/contract-wrappers",
"ignoreDependencyVersions": "@types/styled-components @types/node",
"ignoreDependencyVersionsForPackage": "contract-wrappers"
},

View File

@@ -1,4 +1,32 @@
[
{
"version": "16.61.0",
"changes": [
{
"note": "Add stETH wrap/unwrap support",
"pr": 476
},
{
"note": "Offboard/clean up Oasis, CoFix, and legacy Kyber",
"pr": 482
},
{
"note": "Add MeshSwap on Polygon",
"pr": 491
}
],
"timestamp": 1654284040
},
{
"version": "16.60.1",
"changes": [
{
"note": "Alias Balancer sor to the old version",
"pr": 481
}
],
"timestamp": 1652931596
},
{
"version": "16.60.0",
"changes": [

View File

@@ -5,6 +5,16 @@ Edit the package's CHANGELOG.json file only.
CHANGELOG
## v16.61.0 - _June 3, 2022_
* Add stETH wrap/unwrap support (#476)
* Offboard/clean up Oasis, CoFix, and legacy Kyber (#482)
* Add MeshSwap on Polygon (#491)
## v16.60.1 - _May 19, 2022_
* Alias Balancer sor to the old version (#481)
## v16.60.0 - _May 19, 2022_
* Add BiSwap on BSC (#467)

View File

@@ -0,0 +1,120 @@
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2022 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6;
pragma experimental ABIEncoderV2;
import "./interfaces/IBancorV3.sol";
contract BancorV3Sampler
{
/// @dev Gas limit for BancorV3 calls.
uint256 constant private BancorV3_CALL_GAS = 150e3; // 150k
address constant public ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev Sample sell quotes from BancorV3.
/// @param weth The WETH contract address
/// @param router Router to look up tokens and amounts
/// @param path Token route. Should be takerToken -> makerToken
/// @param takerTokenAmounts Taker token sell amount for each sample.
/// @return makerTokenAmounts Maker amounts bought at each taker token
/// amount.
function sampleSellsFromBancorV3(
address weth,
address router,
address[] memory path,
uint256[] memory takerTokenAmounts
)
public
view
returns (uint256[] memory makerTokenAmounts)
{
uint256 numSamples = takerTokenAmounts.length;
makerTokenAmounts = new uint256[](numSamples);
if(path[0] == weth){
path[0] = ETH;
}
if(path[1] == weth){
path[1] = ETH;
}
for (uint256 i = 0; i < numSamples; i++) {
try
IBancorV3(router).tradeOutputBySourceAmount(path[0], path[1], takerTokenAmounts[i])
returns (uint256 amount)
{
makerTokenAmounts[i] = amount;
// Break early if there are 0 amounts
if (makerTokenAmounts[i] == 0) {
break;
}
} catch (bytes memory) {
// Swallow failures, leaving all results as zero.
break;
}
}
}
/// @dev Sample buy quotes from BancorV3.
/// @param weth The WETH contract address
/// @param router Router to look up tokens and amounts
/// @param path Token route. Should be takerToken -> makerToken.
/// @param makerTokenAmounts Maker token buy amount for each sample.
/// @return takerTokenAmounts Taker amounts sold at each maker token
/// amount.
function sampleBuysFromBancorV3(
address weth,
address router,
address[] memory path,
uint256[] memory makerTokenAmounts
)
public
view
returns (uint256[] memory takerTokenAmounts)
{
uint256 numSamples = makerTokenAmounts.length;
takerTokenAmounts = new uint256[](numSamples);
if(path[0] == weth){
path[0] = ETH;
}
if(path[1] == weth){
path[1] = ETH;
}
for (uint256 i = 0; i < numSamples; i++) {
try
IBancorV3(router).tradeInputByTargetAmount(path[0], path[1], makerTokenAmounts[i])
returns (uint256 amount)
{
takerTokenAmounts[i] = amount;
// Break early if there are 0 amounts
if (takerTokenAmounts[i] == 0) {
break;
}
} catch (bytes memory) {
// Swallow failures, leaving all results as zero.
break;
}
}
}
}

View File

@@ -24,12 +24,12 @@ import "./BalancerSampler.sol";
import "./BalancerV2Sampler.sol";
import "./BalancerV2BatchSampler.sol";
import "./BancorSampler.sol";
import "./BancorV3Sampler.sol";
import "./CompoundSampler.sol";
import "./CurveSampler.sol";
import "./DODOSampler.sol";
import "./DODOV2Sampler.sol";
import "./GMXSampler.sol";
import "./KyberSampler.sol";
import "./KyberDmmSampler.sol";
import "./LidoSampler.sol";
import "./LiquidityProviderSampler.sol";
@@ -52,12 +52,12 @@ contract ERC20BridgeSampler is
BalancerV2Sampler,
BalancerV2BatchSampler,
BancorSampler,
BancorV3Sampler,
CompoundSampler,
CurveSampler,
DODOSampler,
DODOV2Sampler,
GMXSampler,
KyberSampler,
KyberDmmSampler,
LidoSampler,
LiquidityProviderSampler,

View File

@@ -1,301 +0,0 @@
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6;
pragma experimental ABIEncoderV2;
import "./interfaces/IKyberNetwork.sol";
import "./ApproximateBuys.sol";
import "./SamplerUtils.sol";
contract KyberSampler is
SamplerUtils,
ApproximateBuys
{
/// @dev Gas limit for Kyber calls.
uint256 constant private KYBER_CALL_GAS = 500e3; // 500k
/// @dev Kyber ETH pseudo-address.
address constant internal KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
struct KyberSamplerOpts {
uint256 reserveOffset;
address hintHandler;
address networkProxy;
address weth;
bytes hint;
}
/// @dev Sample sell quotes from Kyber.
/// @param opts KyberSamplerOpts The nth reserve
/// @param takerToken Address of the taker token (what to sell).
/// @param makerToken Address of the maker token (what to buy).
/// @param takerTokenAmounts Taker token sell amount for each sample.
/// @return reserveId The id of the reserve found at reserveOffset
/// @return hint The hint for the selected reserve
/// @return makerTokenAmounts Maker amounts bought at each taker token amount.
function sampleSellsFromKyberNetwork(
KyberSamplerOpts memory opts,
address takerToken,
address makerToken,
uint256[] memory takerTokenAmounts
)
public
view
returns (bytes32 reserveId, bytes memory hint, uint256[] memory makerTokenAmounts)
{
_assertValidPair(makerToken, takerToken);
reserveId = _getNextReserveId(opts, takerToken, makerToken);
if (reserveId == 0x0) {
return (reserveId, hint, makerTokenAmounts);
}
opts.hint = this.encodeKyberHint(opts, reserveId, takerToken, makerToken);
hint = opts.hint;
uint256 numSamples = takerTokenAmounts.length;
makerTokenAmounts = new uint256[](numSamples);
for (uint256 i = 0; i < numSamples; i++) {
uint256 value = this.sampleSellFromKyberNetwork(
opts,
takerToken,
makerToken,
takerTokenAmounts[i]
);
makerTokenAmounts[i] = value;
// Break early if there are 0 amounts
if (makerTokenAmounts[i] == 0) {
break;
}
}
}
/// @dev Sample buy quotes from Kyber.
/// @param opts KyberSamplerOpts The nth reserve
/// @param takerToken Address of the taker token (what to sell).
/// @param makerToken Address of the maker token (what to buy).
/// @param makerTokenAmounts Maker token buy amount for each sample.
/// @return reserveId The id of the reserve found at reserveOffset
/// @return hint The hint for the selected reserve
/// @return takerTokenAmounts Taker amounts sold at each maker token amount.
function sampleBuysFromKyberNetwork(
KyberSamplerOpts memory opts,
address takerToken,
address makerToken,
uint256[] memory makerTokenAmounts
)
public
view
returns (bytes32 reserveId, bytes memory hint, uint256[] memory takerTokenAmounts)
{
_assertValidPair(makerToken, takerToken);
reserveId = _getNextReserveId(opts, takerToken, makerToken);
if (reserveId == 0x0) {
return (reserveId, hint, takerTokenAmounts);
}
opts.hint = this.encodeKyberHint(opts, reserveId, takerToken, makerToken);
hint = opts.hint;
takerTokenAmounts = _sampleApproximateBuys(
ApproximateBuyQuoteOpts({
makerTokenData: abi.encode(makerToken, opts),
takerTokenData: abi.encode(takerToken, opts),
getSellQuoteCallback: _sampleSellForApproximateBuyFromKyber
}),
makerTokenAmounts
);
return (reserveId, hint, takerTokenAmounts);
}
function encodeKyberHint(
KyberSamplerOpts memory opts,
bytes32 reserveId,
address takerToken,
address makerToken
)
public
view
returns (bytes memory hint)
{
// Build a hint selecting the single reserve
IKyberHintHandler kyberHint = IKyberHintHandler(opts.hintHandler);
// All other reserves should be ignored with this hint
bytes32[] memory selectedReserves = new bytes32[](1);
selectedReserves[0] = reserveId;
uint256[] memory emptySplits = new uint256[](0);
if (takerToken == opts.weth) {
// ETH to Token
try
kyberHint.buildEthToTokenHint
{gas: KYBER_CALL_GAS}
(
makerToken,
IKyberHintHandler.TradeType.MaskIn,
selectedReserves,
emptySplits
)
returns (bytes memory result)
{
return result;
} catch (bytes memory) {
// Swallow failures, leaving all results as zero.
}
} else if (makerToken == opts.weth) {
// Token to ETH
try
kyberHint.buildTokenToEthHint
{gas: KYBER_CALL_GAS}
(
takerToken,
IKyberHintHandler.TradeType.MaskIn,
selectedReserves,
emptySplits
)
returns (bytes memory result)
{
return result;
} catch (bytes memory) {
// Swallow failures, leaving all results as zero.
}
} else {
// Token to Token
// We use the same reserve both ways
try
kyberHint.buildTokenToTokenHint
{gas: KYBER_CALL_GAS}
(
takerToken,
IKyberHintHandler.TradeType.MaskIn,
selectedReserves,
emptySplits,
makerToken,
IKyberHintHandler.TradeType.MaskIn,
selectedReserves,
emptySplits
)
returns (bytes memory result)
{
return result;
} catch (bytes memory) {
// Swallow failures, leaving all results as zero.
}
}
}
function _sampleSellForApproximateBuyFromKyber(
bytes memory takerTokenData,
bytes memory makerTokenData,
uint256 sellAmount
)
private
view
returns (uint256)
{
(address makerToken, KyberSamplerOpts memory opts) =
abi.decode(makerTokenData, (address, KyberSamplerOpts));
(address takerToken, ) =
abi.decode(takerTokenData, (address, KyberSamplerOpts));
try
this.sampleSellFromKyberNetwork
(opts, takerToken, makerToken, sellAmount)
returns (uint256 amount)
{
return amount;
} catch (bytes memory) {
// Swallow failures, leaving all results as zero.
return 0;
}
}
function sampleSellFromKyberNetwork(
KyberSamplerOpts memory opts,
address takerToken,
address makerToken,
uint256 takerTokenAmount
)
public
view
returns (uint256 makerTokenAmount)
{
// If there is no hint do not continue
if (opts.hint.length == 0) {
return 0;
}
try
IKyberNetworkProxy(opts.networkProxy).getExpectedRateAfterFee
{gas: KYBER_CALL_GAS}
(
takerToken == opts.weth ? KYBER_ETH_ADDRESS : takerToken,
makerToken == opts.weth ? KYBER_ETH_ADDRESS : makerToken,
takerTokenAmount,
0, // fee
opts.hint
)
returns (uint256 rate)
{
uint256 makerTokenDecimals = _getTokenDecimals(makerToken);
uint256 takerTokenDecimals = _getTokenDecimals(takerToken);
makerTokenAmount =
rate *
takerTokenAmount *
10 ** makerTokenDecimals /
10 ** takerTokenDecimals /
10 ** 18;
return makerTokenAmount;
} catch (bytes memory) {
// Swallow failures, leaving all results as zero.
return 0;
}
}
function _getNextReserveId(
KyberSamplerOpts memory opts,
address takerToken,
address makerToken
)
internal
view
returns (bytes32 reserveId)
{
// Fetch the registered reserves for this pair
IKyberHintHandler kyberHint = IKyberHintHandler(opts.hintHandler);
(bytes32[] memory reserveIds, ,) = kyberHint.getTradingReserves(
takerToken == opts.weth ? KYBER_ETH_ADDRESS : takerToken,
makerToken == opts.weth ? KYBER_ETH_ADDRESS : makerToken,
true,
new bytes(0) // empty hint
);
if (opts.reserveOffset >= reserveIds.length) {
return 0x0;
}
reserveId = reserveIds[opts.reserveOffset];
// Ignore Kyber Bridged Reserves (0xbb)
if (uint256(reserveId >> 248) == 0xbb) {
return 0x0;
}
return reserveId;
}
}

View File

@@ -22,10 +22,18 @@ pragma experimental ABIEncoderV2;
import "./SamplerUtils.sol";
interface IWstETH {
function getWstETHByStETH(uint256 _stETHAmount) external view returns (uint256);
function getStETHByWstETH(uint256 _wstETHAmount) external view returns (uint256);
}
contract LidoSampler is SamplerUtils {
struct LidoInfo {
address stEthToken;
address wethToken;
address wstEthToken;
}
/// @dev Sample sell quotes from Lido
@@ -42,20 +50,17 @@ contract LidoSampler is SamplerUtils {
uint256[] memory takerTokenAmounts
)
public
pure
view
returns (uint256[] memory)
{
_assertValidPair(makerToken, takerToken);
if (takerToken != lidoInfo.wethToken || makerToken != address(lidoInfo.stEthToken)) {
// Return 0 values if not selling WETH for stETH
uint256 numSamples = takerTokenAmounts.length;
uint256[] memory makerTokenAmounts = new uint256[](numSamples);
return makerTokenAmounts;
if (takerToken == lidoInfo.wethToken && makerToken == address(lidoInfo.stEthToken)) {
// Minting stETH is always 1:1 therefore we can just return the same amounts back.
return takerTokenAmounts;
}
// Minting stETH is always 1:1 therefore we can just return the same amounts back
return takerTokenAmounts;
return _sampleSellsForWrapped(lidoInfo, takerToken, makerToken, takerTokenAmounts);
}
/// @dev Sample buy quotes from Lido.
@@ -72,20 +77,43 @@ contract LidoSampler is SamplerUtils {
uint256[] memory makerTokenAmounts
)
public
pure
view
returns (uint256[] memory)
{
_assertValidPair(makerToken, takerToken);
if (takerToken != lidoInfo.wethToken || makerToken != address(lidoInfo.stEthToken)) {
// Return 0 values if not buying stETH for WETH
uint256 numSamples = makerTokenAmounts.length;
uint256[] memory takerTokenAmounts = new uint256[](numSamples);
return takerTokenAmounts;
if (takerToken == lidoInfo.wethToken && makerToken == address(lidoInfo.stEthToken)) {
// Minting stETH is always 1:1 therefore we can just return the same amounts back.
return makerTokenAmounts;
}
// Minting stETH is always 1:1 therefore we can just return the same amounts back
return makerTokenAmounts;
// Swap out `makerToken` and `takerToken` and re-use `_sampleSellsForWrapped`.
return _sampleSellsForWrapped(lidoInfo, makerToken, takerToken, makerTokenAmounts);
}
function _sampleSellsForWrapped(
LidoInfo memory lidoInfo,
address takerToken,
address makerToken,
uint256[] memory takerTokenAmounts
) private view returns (uint256[] memory) {
IWstETH wstETH = IWstETH(lidoInfo.wstEthToken);
uint256 numSamples = takerTokenAmounts.length;
uint256[] memory makerTokenAmounts = new uint256[](numSamples);
if (takerToken == lidoInfo.stEthToken && makerToken == lidoInfo.wstEthToken) {
for (uint256 i = 0; i < numSamples; i++) {
makerTokenAmounts[i] = wstETH.getWstETHByStETH(takerTokenAmounts[i]);
}
return makerTokenAmounts;
}
if (takerToken == lidoInfo.wstEthToken && makerToken == lidoInfo.stEthToken) {
for (uint256 i = 0; i < numSamples; i++) {
makerTokenAmounts[i] = wstETH.getStETHByWstETH(takerTokenAmounts[i]);
}
return makerTokenAmounts;
}
// Returns 0 values.
return makerTokenAmounts;
}
}

View File

@@ -0,0 +1,43 @@
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2022 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6;
pragma experimental ABIEncoderV2;
interface IBancorV3 {
/**
* @dev returns the output amount when trading by providing the source amount
*/
function tradeOutputBySourceAmount(
address sourceToken,
address targetToken,
uint256 sourceAmount
) external view returns (uint256);
/**
* @dev returns the input amount when trading by providing the target amount
*/
function tradeInputByTargetAmount(
address sourceToken,
address targetToken,
uint256 targetAmount
) external view returns (uint256);
}

View File

@@ -1,96 +0,0 @@
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6;
// Keepin everything together
interface IKyberNetwork {
}
interface IKyberNetworkProxy {
function getExpectedRateAfterFee(
address src,
address dest,
uint256 srcQty,
uint256 platformFeeBps,
bytes calldata hint
)
external
view
returns (uint256 expectedRate);
}
interface IKyberHintHandler {
enum TradeType {BestOfAll, MaskIn, MaskOut, Split}
enum ProcessWithRate {NotRequired, Required}
function getTradingReserves(
address tokenSrc,
address tokenDest,
bool isTokenToToken,
bytes calldata hint
)
external
view
returns (
bytes32[] memory reserveIds,
uint256[] memory splitValuesBps,
ProcessWithRate processWithRate
);
function buildTokenToEthHint(
address tokenSrc,
TradeType tokenToEthType,
bytes32[] calldata tokenToEthReserveIds,
uint256[] calldata tokenToEthSplits
)
external
view
returns (bytes memory hint);
function buildEthToTokenHint(
address tokenDest,
TradeType ethToTokenType,
bytes32[] calldata ethToTokenReserveIds,
uint256[] calldata ethToTokenSplits
)
external
view
returns (bytes memory hint);
function buildTokenToTokenHint(
address tokenSrc,
TradeType tokenToEthType,
bytes32[] calldata tokenToEthReserveIds,
uint256[] calldata tokenToEthSplits,
address tokenDest,
TradeType ethToTokenType,
bytes32[] calldata ethToTokenReserveIds,
uint256[] calldata ethToTokenSplits
)
external
view
returns (bytes memory hint);
}

View File

@@ -1,6 +1,6 @@
{
"name": "@0x/asset-swapper",
"version": "16.60.0",
"version": "16.61.0",
"engines": {
"node": ">=6.12"
},
@@ -34,12 +34,13 @@
"contracts:gen": "contracts-gen generate",
"contracts:copy": "contracts-gen copy",
"publish:private": "yarn build && gitpkg publish",
"sampler-size": "jq .compilerOutput.evm.deployedBytecode.object -- test/generated-artifacts/ERC20BridgeSampler.json | echo $(( $(wc -c) / 2 - 1 ))"
"sampler-size": "jq .compilerOutput.evm.deployedBytecode.object -- test/generated-artifacts/ERC20BridgeSampler.json | echo $(( $(wc -c) / 2 - 1 ))",
"list:deps": "yarn lerna list -l"
},
"config": {
"publicInterfaceContracts": "ERC20BridgeSampler,BalanceChecker,FakeTaker",
"abis:comment": "This list is auto-generated by contracts-gen. Don't edit manually.",
"abis": "./test/generated-artifacts/@(ApproximateBuys|BalanceChecker|BalancerSampler|BalancerV2BatchSampler|BalancerV2Common|BalancerV2Sampler|BancorSampler|CompoundSampler|CurveSampler|DODOSampler|DODOV2Sampler|ERC20BridgeSampler|FakeTaker|GMXSampler|IBalancer|IBalancerV2Vault|IBancor|ICurve|IGMX|IKyberNetwork|IMStable|IMooniswap|IMultiBridge|IPlatypus|IShell|ISmoothy|IUniswapExchangeQuotes|IUniswapV2Router01|KyberDmmSampler|KyberSampler|LidoSampler|LiquidityProviderSampler|MStableSampler|MakerPSMSampler|MooniswapSampler|NativeOrderSampler|PlatypusSampler|SamplerUtils|ShellSampler|SmoothySampler|TestNativeOrderSampler|TwoHopSampler|UniswapSampler|UniswapV2Sampler|UniswapV3Sampler|UtilitySampler).json",
"abis": "./test/generated-artifacts/@(ApproximateBuys|BalanceChecker|BalancerSampler|BalancerV2BatchSampler|BalancerV2Common|BalancerV2Sampler|BancorSampler|BancorV3Sampler|CompoundSampler|CurveSampler|DODOSampler|DODOV2Sampler|ERC20BridgeSampler|FakeTaker|GMXSampler|IBalancer|IBalancerV2Vault|IBancor|IBancorV3|ICurve|IGMX|IMStable|IMooniswap|IMultiBridge|IPlatypus|IShell|ISmoothy|IUniswapExchangeQuotes|IUniswapV2Router01|KyberDmmSampler|LidoSampler|LiquidityProviderSampler|MStableSampler|MakerPSMSampler|MooniswapSampler|NativeOrderSampler|PlatypusSampler|SamplerUtils|ShellSampler|SmoothySampler|TestNativeOrderSampler|TwoHopSampler|UniswapSampler|UniswapV2Sampler|UniswapV3Sampler|UtilitySampler).json",
"postpublish": {
"assets": []
}
@@ -60,21 +61,20 @@
"dependencies": {
"@0x/assert": "^3.0.34",
"@0x/base-contract": "^6.5.0",
"@0x/contract-addresses": "^6.14.0",
"@0x/contract-wrappers": "^13.20.2",
"@0x/contracts-erc20": "^3.3.30",
"@0x/contracts-zero-ex": "^0.33.0",
"@0x/contract-addresses": "^6.15.0",
"@0x/contract-wrappers": "^13.20.3",
"@0x/contracts-erc20": "^3.3.31",
"@0x/contracts-zero-ex": "^0.34.0",
"@0x/dev-utils": "^4.2.14",
"@0x/json-schemas": "^6.4.4",
"@0x/neon-router": "^0.3.5",
"@0x/protocol-utils": "^11.13.0",
"@0x/protocol-utils": "^11.14.0",
"@0x/quote-server": "^6.0.6",
"@0x/types": "^3.3.6",
"@0x/typescript-typings": "^5.3.1",
"@0x/utils": "^6.5.3",
"@0x/web3-wrapper": "^7.6.5",
"@balancer-labs/sdk": "^0.1.6",
"@balancer-labs/sor": "0.3.2",
"@balancer-labs/sdk": "0.1.6",
"@bancor/sdk": "0.2.9",
"@ethersproject/abi": "^5.0.1",
"@ethersproject/address": "^5.0.1",
@@ -83,6 +83,7 @@
"@ethersproject/strings": "^5.0.10",
"axios": "^0.21.1",
"axios-mock-adapter": "^1.19.0",
"balancer-labs-sor-v1": "npm:@balancer-labs/sor@0.3.2",
"cream-sor": "^0.3.3",
"decimal.js": "^10.2.0",
"ethereum-types": "^3.7.0",
@@ -91,8 +92,7 @@
"graphql": "^15.4.0",
"graphql-request": "^3.4.0",
"heartbeats": "^5.0.1",
"lodash": "^4.17.11",
"sorV2": "npm:@balancer-labs/sor"
"lodash": "^4.17.11"
},
"devDependencies": {
"@0x/abi-gen": "^5.8.0",
@@ -100,10 +100,9 @@
"@0x/contracts-exchange": "^3.2.38",
"@0x/contracts-exchange-libs": "^4.3.37",
"@0x/contracts-gen": "^2.0.46",
"@0x/contracts-test-utils": "^5.4.21",
"@0x/contracts-utils": "^4.8.11",
"@0x/contracts-test-utils": "^5.4.22",
"@0x/contracts-utils": "^4.8.12",
"@0x/mesh-rpc-client": "^9.4.2",
"@0x/migrations": "^8.1.19",
"@0x/sol-compiler": "^4.8.1",
"@0x/subproviders": "^6.6.5",
"@0x/ts-doc-gen": "^0.0.28",

View File

@@ -153,7 +153,6 @@ export {
Fill,
FillData,
GetMarketOrdersRfqOpts,
KyberFillData,
LiquidityProviderFillData,
LiquidityProviderRegistry,
MarketDepth,

View File

@@ -1,5 +1,5 @@
import { ChainId } from '@0x/contract-addresses';
import { BigNumber, NULL_BYTES } from '@0x/utils';
import { BigNumber } from '@0x/utils';
import {
ACRYPTOS_BSC_INFOS,
@@ -28,10 +28,8 @@ import {
IRONSWAP_POLYGON_INFOS,
JETSWAP_ROUTER_BY_CHAIN_ID,
JULSWAP_ROUTER_BY_CHAIN_ID,
KYBER_BANNED_RESERVES,
KYBER_BRIDGED_LIQUIDITY_PREFIX,
MAX_DODOV2_POOLS_QUERIED,
MAX_KYBER_RESERVES_QUERIED,
MESHSWAP_ROUTER_BY_CHAIN_ID,
MOBIUSMONEY_CELO_INFOS,
MORPHEUSSWAP_ROUTER_BY_CHAIN_ID,
MSTABLE_POOLS_BY_CHAIN_ID,
@@ -66,32 +64,11 @@ import {
} from './constants';
import { CurveInfo, ERC20BridgeSource, PlatypusInfo } from './types';
/**
* Filter Kyber reserves which should not be used (0xbb bridged reserves)
* @param reserveId Kyber reserveId
*/
export function isAllowedKyberReserveId(reserveId: string): boolean {
return (
reserveId !== NULL_BYTES &&
!reserveId.startsWith(KYBER_BRIDGED_LIQUIDITY_PREFIX) &&
!KYBER_BANNED_RESERVES.includes(reserveId)
);
}
// tslint:disable-next-line: completed-docs ban-types
export function isValidAddress(address: string | String): address is string {
return (typeof address === 'string' || address instanceof String) && address.toString() !== NULL_ADDRESS;
}
/**
* Returns the offsets to be used to discover Kyber reserves
*/
export function getKyberOffsets(): BigNumber[] {
return Array(MAX_KYBER_RESERVES_QUERIED)
.fill(0)
.map((_v, i) => new BigNumber(i));
}
// tslint:disable completed-docs
export function getDodoV2Offsets(): BigNumber[] {
return Array(MAX_DODOV2_POOLS_QUERIED)
@@ -567,7 +544,8 @@ export function uniswapV2LikeRouterAddress(
| ERC20BridgeSource.SpookySwap
| ERC20BridgeSource.SpiritSwap
| ERC20BridgeSource.BiSwap
| ERC20BridgeSource.Yoshi,
| ERC20BridgeSource.Yoshi
| ERC20BridgeSource.MeshSwap,
): string {
switch (source) {
case ERC20BridgeSource.UniswapV2:
@@ -620,6 +598,8 @@ export function uniswapV2LikeRouterAddress(
return BISWAP_ROUTER_BY_CHAIN_ID[chainId];
case ERC20BridgeSource.Yoshi:
return YOSHI_ROUTER_BY_CHAIN_ID[chainId];
case ERC20BridgeSource.MeshSwap:
return MESHSWAP_ROUTER_BY_CHAIN_ID[chainId];
default:
throw new Error(`Unknown UniswapV2 like source ${source}`);
}

View File

@@ -22,7 +22,7 @@ import {
GeistFillData,
GetMarketOrdersOpts,
isFinalUniswapV3FillData,
KyberSamplerOpts,
LidoFillData,
LidoInfo,
LiquidityProviderFillData,
LiquidityProviderRegistry,
@@ -80,11 +80,11 @@ export const SELL_SOURCE_FILTER_BY_CHAIN_ID = valueByChainId<SourceFilters>(
ERC20BridgeSource.Native,
ERC20BridgeSource.Uniswap,
ERC20BridgeSource.UniswapV2,
ERC20BridgeSource.Kyber,
ERC20BridgeSource.Curve,
ERC20BridgeSource.Balancer,
ERC20BridgeSource.BalancerV2,
ERC20BridgeSource.Bancor,
ERC20BridgeSource.BancorV3,
ERC20BridgeSource.MStable,
ERC20BridgeSource.Mooniswap,
ERC20BridgeSource.SushiSwap,
@@ -111,7 +111,6 @@ export const SELL_SOURCE_FILTER_BY_CHAIN_ID = valueByChainId<SourceFilters>(
// ERC20BridgeSource.Compound,
]),
[ChainId.Ropsten]: new SourceFilters([
ERC20BridgeSource.Kyber,
ERC20BridgeSource.Native,
ERC20BridgeSource.SushiSwap,
ERC20BridgeSource.Uniswap,
@@ -172,6 +171,7 @@ export const SELL_SOURCE_FILTER_BY_CHAIN_ID = valueByChainId<SourceFilters>(
ERC20BridgeSource.AaveV2,
ERC20BridgeSource.UniswapV3,
ERC20BridgeSource.Synapse,
ERC20BridgeSource.MeshSwap,
]),
[ChainId.Avalanche]: new SourceFilters([
ERC20BridgeSource.MultiHop,
@@ -226,11 +226,11 @@ export const BUY_SOURCE_FILTER_BY_CHAIN_ID = valueByChainId<SourceFilters>(
ERC20BridgeSource.Native,
ERC20BridgeSource.Uniswap,
ERC20BridgeSource.UniswapV2,
ERC20BridgeSource.Kyber,
ERC20BridgeSource.Curve,
ERC20BridgeSource.Balancer,
ERC20BridgeSource.BalancerV2,
// ERC20BridgeSource.Bancor, // FIXME: Bancor Buys not implemented in Sampler
ERC20BridgeSource.BancorV3,
ERC20BridgeSource.MStable,
ERC20BridgeSource.Mooniswap,
ERC20BridgeSource.Shell,
@@ -257,7 +257,6 @@ export const BUY_SOURCE_FILTER_BY_CHAIN_ID = valueByChainId<SourceFilters>(
// ERC20BridgeSource.Compound,
]),
[ChainId.Ropsten]: new SourceFilters([
ERC20BridgeSource.Kyber,
ERC20BridgeSource.Native,
ERC20BridgeSource.SushiSwap,
ERC20BridgeSource.Uniswap,
@@ -293,7 +292,6 @@ export const BUY_SOURCE_FILTER_BY_CHAIN_ID = valueByChainId<SourceFilters>(
ERC20BridgeSource.JetSwap,
ERC20BridgeSource.ACryptos,
ERC20BridgeSource.KyberDmm,
ERC20BridgeSource.Synapse,
ERC20BridgeSource.BiSwap,
]),
[ChainId.Polygon]: new SourceFilters([
@@ -319,6 +317,7 @@ export const BUY_SOURCE_FILTER_BY_CHAIN_ID = valueByChainId<SourceFilters>(
ERC20BridgeSource.AaveV2,
ERC20BridgeSource.UniswapV3,
ERC20BridgeSource.Synapse,
ERC20BridgeSource.MeshSwap,
]),
[ChainId.Avalanche]: new SourceFilters([
ERC20BridgeSource.MultiHop,
@@ -454,6 +453,7 @@ export const MAINNET_TOKENS = {
sEUR: '0xd71ecff9342a5ced620049e616c5035f1db98620',
sETH: '0x5e74c9036fb86bd7ecdcb084a0673efc32ea31cb',
stETH: '0xae7ab96520de3a18e5e111b5eaab095312d7fe84',
wstETH: '0x7f39c581f595b53c5cb19bd0b3f8da6c935e2ca0',
LINK: '0x514910771af9ca656af840dff83e8264ecf986ca',
MANA: '0x0f5d2fb29fb7d3cfee444a200298f468908cc942',
KNC: '0xdefa4e8a7bcba345f687a2f1456f5edd9ce97202',
@@ -937,6 +937,10 @@ export const DEFAULT_TOKEN_ADJACENCY_GRAPH_BY_CHAIN_ID = valueByChainId<TokenAdj
builder
.add(MAINNET_TOKENS.OHMV2, MAINNET_TOKENS.BTRFLY)
.add(MAINNET_TOKENS.BTRFLY, MAINNET_TOKENS.OHMV2);
// Lido
builder
.add(MAINNET_TOKENS.stETH, MAINNET_TOKENS.wstETH)
.add(MAINNET_TOKENS.wstETH, MAINNET_TOKENS.stETH);
})
// Build
.build(),
@@ -1847,35 +1851,6 @@ export const PLATYPUS_AVALANCHE_INFOS: { [name: string]: PlatypusInfo } = {
},
};
/**
* Kyber reserve prefixes
* 0xff Fed price reserve
* 0xaa Automated price reserve
* 0xbb Bridged price reserve (i.e Uniswap/Curve)
*/
export const KYBER_BRIDGED_LIQUIDITY_PREFIX = '0xbb';
export const KYBER_BANNED_RESERVES = ['0xff4f6e65426974205175616e7400000000000000000000000000000000000000'];
export const MAX_KYBER_RESERVES_QUERIED = 5;
export const KYBER_CONFIG_BY_CHAIN_ID = valueByChainId<KyberSamplerOpts>(
{
[ChainId.Mainnet]: {
networkProxy: '0x9aab3f75489902f3a48495025729a0af77d4b11e',
hintHandler: '0xa1C0Fa73c39CFBcC11ec9Eb1Afc665aba9996E2C',
weth: MAINNET_TOKENS.WETH,
},
[ChainId.Ropsten]: {
networkProxy: '0x818e6fecd516ecc3849daf6845e3ec868087b755',
hintHandler: '0x63f773c026093eef988e803bdd5772dd235a8e71',
weth: getContractAddressesForChainOrThrow(ChainId.Ropsten).etherToken,
},
},
{
networkProxy: NULL_ADDRESS,
hintHandler: NULL_ADDRESS,
weth: NULL_ADDRESS,
},
);
export const LIQUIDITY_PROVIDER_REGISTRY_BY_CHAIN_ID = valueByChainId<LiquidityProviderRegistry>(
{
[ChainId.Mainnet]: {
@@ -1980,13 +1955,6 @@ export const MSTABLE_POOLS_BY_CHAIN_ID = valueByChainId(
},
);
export const OASIS_ROUTER_BY_CHAIN_ID = valueByChainId<string>(
{
[ChainId.Mainnet]: '0x5e3e0548935a83ad29fb2a9153d331dc6d49020f',
},
NULL_ADDRESS,
);
export const KYBER_DMM_ROUTER_BY_CHAIN_ID = valueByChainId<string>(
{
[ChainId.Mainnet]: '0x1c87257f5e8609940bc751a07bb085bb7f8cdbe6',
@@ -2092,6 +2060,20 @@ export const BANCOR_REGISTRY_BY_CHAIN_ID = valueByChainId<string>(
NULL_ADDRESS,
);
export const BANCORV3_NETWORK_BY_CHAIN_ID = valueByChainId<string>(
{
[ChainId.Mainnet]: '0xeef417e1d5cc832e619ae18d2f140de2999dd4fb',
},
NULL_ADDRESS,
);
export const BANCORV3_NETWORK_INFO_BY_CHAIN_ID = valueByChainId<string>(
{
[ChainId.Mainnet]: '0x8e303d296851b320e6a697bacb979d13c9d6e760',
},
NULL_ADDRESS,
);
export const SHELL_POOLS_BY_CHAIN_ID = valueByChainId(
{
[ChainId.Mainnet]: {
@@ -2167,11 +2149,13 @@ export const BEETHOVEN_X_VAULT_ADDRESS_BY_CHAIN = valueByChainId<string>(
export const LIDO_INFO_BY_CHAIN = valueByChainId<LidoInfo>(
{
[ChainId.Mainnet]: {
stEthToken: '0xae7ab96520de3a18e5e111b5eaab095312d7fe84',
stEthToken: MAINNET_TOKENS.stETH,
wstEthToken: MAINNET_TOKENS.wstETH,
wethToken: MAINNET_TOKENS.WETH,
},
},
{
wstEthToken: NULL_ADDRESS,
stEthToken: NULL_ADDRESS,
wethToken: NULL_ADDRESS,
},
@@ -2328,6 +2312,13 @@ export const POLYDEX_ROUTER_BY_CHAIN_ID = valueByChainId<string>(
NULL_ADDRESS,
);
export const MESHSWAP_ROUTER_BY_CHAIN_ID = valueByChainId<string>(
{
[ChainId.Polygon]: '0x10f4a785f458bc144e3706575924889954946639',
},
NULL_ADDRESS,
);
export const JETSWAP_ROUTER_BY_CHAIN_ID = valueByChainId<string>(
{
[ChainId.BSC]: '0xbe65b8f75b9f20f4c522e0067a3887fada714800',
@@ -2471,7 +2462,6 @@ export const DEFAULT_GAS_SCHEDULE: Required<FeeSchedule> = {
[ERC20BridgeSource.LiquidityProvider]: fillData => {
return (fillData as LiquidityProviderFillData).gasCost || 100e3;
},
[ERC20BridgeSource.Kyber]: () => 450e3,
[ERC20BridgeSource.Curve]: fillData => (fillData as CurveFillData).pool.gasSchedule,
[ERC20BridgeSource.CurveV2]: fillData => (fillData as CurveFillData).pool.gasSchedule,
[ERC20BridgeSource.Nerve]: fillData => (fillData as CurveFillData).pool.gasSchedule,
@@ -2528,6 +2518,7 @@ export const DEFAULT_GAS_SCHEDULE: Required<FeeSchedule> = {
}
return gas;
},
[ERC20BridgeSource.BancorV3]: () => 250e3, // revisit gas costs with wrap/unwrap
[ERC20BridgeSource.KyberDmm]: (fillData?: FillData) => {
let gas = 170e3;
const path = (fillData as UniswapV2FillData).tokenAddressPath;
@@ -2567,7 +2558,18 @@ export const DEFAULT_GAS_SCHEDULE: Required<FeeSchedule> = {
return gas;
},
[ERC20BridgeSource.Lido]: () => 226e3,
[ERC20BridgeSource.Lido]: (fillData?: FillData) => {
const lidoFillData = fillData as LidoFillData;
const wethAddress = NATIVE_FEE_TOKEN_BY_CHAIN_ID[ChainId.Mainnet];
// WETH -> stETH
if (lidoFillData.takerToken === wethAddress) {
return 226e3;
} else if (lidoFillData.takerToken === lidoFillData.stEthTokenAddress) {
return 120e3;
} else {
return 95e3;
}
},
[ERC20BridgeSource.AaveV2]: (fillData?: FillData) => {
const aaveFillData = fillData as AaveV2FillData;
// NOTE: The Aave deposit method is more expensive than the withdraw
@@ -2609,6 +2611,7 @@ export const DEFAULT_GAS_SCHEDULE: Required<FeeSchedule> = {
[ERC20BridgeSource.Dfyn]: uniswapV2CloneGasSchedule,
[ERC20BridgeSource.Polydex]: uniswapV2CloneGasSchedule,
[ERC20BridgeSource.JetSwap]: uniswapV2CloneGasSchedule,
[ERC20BridgeSource.MeshSwap]: uniswapV2CloneGasSchedule,
//
// Avalanche

View File

@@ -23,7 +23,6 @@ import {
GenericRouterFillData,
GMXFillData,
KyberDmmFillData,
KyberFillData,
LidoFillData,
LiquidityProviderFillData,
MakerPsmFillData,
@@ -92,8 +91,6 @@ export function getErc20BridgeSourceToBridgeSource(source: ERC20BridgeSource): s
return encodeBridgeSourceId(BridgeProtocol.BalancerV2Batch, 'BalancerV2');
case ERC20BridgeSource.Bancor:
return encodeBridgeSourceId(BridgeProtocol.Bancor, 'Bancor');
// case ERC20BridgeSource.CoFiX:
// return encodeBridgeSourceId(BridgeProtocol.CoFiX, 'CoFiX');
case ERC20BridgeSource.Curve:
return encodeBridgeSourceId(BridgeProtocol.Curve, 'Curve');
case ERC20BridgeSource.Cream:
@@ -102,8 +99,6 @@ export function getErc20BridgeSourceToBridgeSource(source: ERC20BridgeSource): s
return encodeBridgeSourceId(BridgeProtocol.CryptoCom, 'CryptoCom');
case ERC20BridgeSource.Dodo:
return encodeBridgeSourceId(BridgeProtocol.Dodo, 'Dodo');
case ERC20BridgeSource.Kyber:
return encodeBridgeSourceId(BridgeProtocol.Kyber, 'Kyber');
case ERC20BridgeSource.LiquidityProvider:
// "LiquidityProvider" is too long to encode (17 characters).
return encodeBridgeSourceId(BridgeProtocol.Unknown, 'LP');
@@ -211,6 +206,10 @@ export function getErc20BridgeSourceToBridgeSource(source: ERC20BridgeSource): s
return encodeBridgeSourceId(BridgeProtocol.GMX, 'GMX');
case ERC20BridgeSource.Platypus:
return encodeBridgeSourceId(BridgeProtocol.Platypus, 'Platypus');
case ERC20BridgeSource.MeshSwap:
return encodeBridgeSourceId(BridgeProtocol.UniswapV2, 'MeshSwap');
case ERC20BridgeSource.BancorV3:
return encodeBridgeSourceId(BridgeProtocol.BancorV3, 'BancorV3');
default:
throw new Error(AggregationError.NoBridgeForSource);
}
@@ -302,13 +301,10 @@ export function createBridgeDataForBridgeOrder(order: OptimizedMarketBridgeOrder
case ERC20BridgeSource.MorpheusSwap:
case ERC20BridgeSource.BiSwap:
case ERC20BridgeSource.Yoshi:
case ERC20BridgeSource.MeshSwap:
const uniswapV2FillData = (order as OptimizedMarketBridgeOrder<UniswapV2FillData>).fillData;
bridgeData = encoder.encode([uniswapV2FillData.router, uniswapV2FillData.tokenAddressPath]);
break;
case ERC20BridgeSource.Kyber:
const kyberFillData = (order as OptimizedMarketBridgeOrder<KyberFillData>).fillData;
bridgeData = encoder.encode([kyberFillData.networkProxy, kyberFillData.hint]);
break;
case ERC20BridgeSource.Mooniswap:
const mooniswapFillData = (order as OptimizedMarketBridgeOrder<MooniswapFillData>).fillData;
bridgeData = encoder.encode([mooniswapFillData.poolAddress]);
@@ -360,7 +356,7 @@ export function createBridgeDataForBridgeOrder(order: OptimizedMarketBridgeOrder
break;
case ERC20BridgeSource.Lido:
const lidoFillData = (order as OptimizedMarketBridgeOrder<LidoFillData>).fillData;
bridgeData = encoder.encode([lidoFillData.stEthTokenAddress]);
bridgeData = encoder.encode([lidoFillData.stEthTokenAddress, lidoFillData.wstEthTokenAddress]);
break;
case ERC20BridgeSource.AaveV2:
const aaveFillData = (order as OptimizedMarketBridgeOrder<AaveV2FillData>).fillData;
@@ -391,7 +387,10 @@ export function createBridgeDataForBridgeOrder(order: OptimizedMarketBridgeOrder
platypusFillData.tokenAddressPath,
]);
break;
case ERC20BridgeSource.BancorV3:
const bancorV3FillData = (order as OptimizedMarketBridgeOrder<BancorFillData>).fillData;
bridgeData = encoder.encode([bancorV3FillData.networkAddress, bancorV3FillData.path]);
break;
default:
throw new Error(AggregationError.NoBridgeForSource);
}
@@ -490,10 +489,6 @@ export const BRIDGE_ENCODERS: {
{ name: 'provider', type: 'address' },
{ name: 'data', type: 'bytes' },
]),
[ERC20BridgeSource.Kyber]: AbiEncoder.create([
{ name: 'kyberNetworkProxy', type: 'address' },
{ name: 'hint', type: 'bytes' },
]),
[ERC20BridgeSource.Dodo]: AbiEncoder.create([
{ name: 'helper', type: 'address' },
{ name: 'poolAddress', type: 'address' },
@@ -519,6 +514,7 @@ export const BRIDGE_ENCODERS: {
[ERC20BridgeSource.MobiusMoney]: curveEncoder,
// UniswapV2 like, (router, address[])
[ERC20BridgeSource.Bancor]: routerAddressPathEncoder,
[ERC20BridgeSource.BancorV3]: routerAddressPathEncoder,
[ERC20BridgeSource.UniswapV2]: routerAddressPathEncoder,
[ERC20BridgeSource.SushiSwap]: routerAddressPathEncoder,
[ERC20BridgeSource.CryptoCom]: routerAddressPathEncoder,
@@ -530,6 +526,7 @@ export const BRIDGE_ENCODERS: {
[ERC20BridgeSource.MorpheusSwap]: routerAddressPathEncoder,
[ERC20BridgeSource.BiSwap]: routerAddressPathEncoder,
[ERC20BridgeSource.Yoshi]: routerAddressPathEncoder,
[ERC20BridgeSource.MeshSwap]: routerAddressPathEncoder,
// Avalanche
[ERC20BridgeSource.GMX]: gmxAddressPathEncoder,
[ERC20BridgeSource.Platypus]: platypusAddressPathEncoder,
@@ -581,7 +578,7 @@ export const BRIDGE_ENCODERS: {
{ name: 'path', type: 'bytes' },
]),
[ERC20BridgeSource.KyberDmm]: AbiEncoder.create('(address,address[],address[])'),
[ERC20BridgeSource.Lido]: AbiEncoder.create('(address)'),
[ERC20BridgeSource.Lido]: AbiEncoder.create('(address,address)'),
[ERC20BridgeSource.AaveV2]: AbiEncoder.create('(address,address)'),
[ERC20BridgeSource.Compound]: AbiEncoder.create('(address)'),
[ERC20BridgeSource.Geist]: AbiEncoder.create('(address,address)'),

View File

@@ -1,5 +1,5 @@
import { getPoolsWithTokens, parsePoolData } from '@balancer-labs/sor';
import { Pool } from '@balancer-labs/sor/dist/types';
import { getPoolsWithTokens, parsePoolData } from 'balancer-labs-sor-v1';
import { Pool } from 'balancer-labs-sor-v1/dist/types';
import { gql, request } from 'graphql-request';
import { BALANCER_MAX_POOLS_FETCHED, BALANCER_SUBGRAPH_URL, BALANCER_TOP_POOLS_FETCHED } from '../constants';

View File

@@ -1,7 +1,7 @@
import { ChainId } from '@0x/contract-addresses';
import { BigNumber } from '@0x/utils';
// import { parsePoolData } from '@balancer-labs'; // TODO - upgrade to v2
import { Pool } from '@balancer-labs/sor/dist/types';
import { Pool } from 'balancer-labs-sor-v1/dist/types';
import { gql, request } from 'graphql-request';
import { DEFAULT_WARNING_LOGGER } from '../../../constants';

View File

@@ -1,4 +1,4 @@
import { Pool } from '@balancer-labs/sor/dist/types';
import { Pool } from 'balancer-labs-sor-v1/dist/types';
import { getPoolsWithTokens, parsePoolData } from 'cream-sor';
import { BALANCER_MAX_POOLS_FETCHED } from '../constants';

View File

@@ -1,4 +1,4 @@
import { Pool } from '@balancer-labs/sor/dist/types';
import { Pool } from 'balancer-labs-sor-v1/dist/types';
import { ONE_HOUR_IN_SECONDS, ONE_SECOND_MS } from '../constants';
export { Pool };

View File

@@ -13,10 +13,8 @@ import { BancorService } from './bancor_service';
import {
getCurveLikeInfosForPair,
getDodoV2Offsets,
getKyberOffsets,
getPlatypusInfoForPair,
getShellLikeInfosForPair,
isAllowedKyberReserveId,
isBadTokenForSource,
isValidAddress,
uniswapV2LikeRouterAddress,
@@ -27,6 +25,8 @@ import {
AVALANCHE_TOKENS,
BALANCER_V2_VAULT_ADDRESS_BY_CHAIN,
BANCOR_REGISTRY_BY_CHAIN_ID,
BANCORV3_NETWORK_BY_CHAIN_ID,
BANCORV3_NETWORK_INFO_BY_CHAIN_ID,
BEETHOVEN_X_SUBGRAPH_URL_BY_CHAIN,
BEETHOVEN_X_VAULT_ADDRESS_BY_CHAIN,
COMPOUND_API_URL_BY_CHAIN_ID,
@@ -35,16 +35,15 @@ import {
GMX_READER_BY_CHAIN_ID,
GMX_ROUTER_BY_CHAIN_ID,
GMX_VAULT_BY_CHAIN_ID,
KYBER_CONFIG_BY_CHAIN_ID,
KYBER_DMM_ROUTER_BY_CHAIN_ID,
LIDO_INFO_BY_CHAIN,
LIQUIDITY_PROVIDER_REGISTRY_BY_CHAIN_ID,
MAINNET_TOKENS,
MAKER_PSM_INFO_BY_CHAIN_ID,
MAX_UINT256,
MOONISWAP_REGISTRIES_BY_CHAIN_ID,
NATIVE_FEE_TOKEN_BY_CHAIN_ID,
NULL_ADDRESS,
NULL_BYTES,
PLATYPUS_ROUTER_BY_CHAIN_ID,
SELL_SOURCE_FILTER_BY_CHAIN_ID,
UNISWAPV1_ROUTER_BY_CHAIN_ID,
@@ -81,8 +80,6 @@ import {
GMXFillData,
HopInfo,
KyberDmmFillData,
KyberFillData,
KyberSamplerOpts,
LidoFillData,
LidoInfo,
LiquidityProviderFillData,
@@ -266,54 +263,6 @@ export class SamplerOperations {
});
}
public getKyberSellQuotes(
kyberOpts: KyberSamplerOpts,
reserveOffset: BigNumber,
makerToken: string,
takerToken: string,
takerFillAmounts: BigNumber[],
): SourceQuoteOperation {
return new SamplerContractOperation({
source: ERC20BridgeSource.Kyber,
contract: this._samplerContract,
function: this._samplerContract.sampleSellsFromKyberNetwork,
params: [{ ...kyberOpts, reserveOffset, hint: NULL_BYTES }, takerToken, makerToken, takerFillAmounts],
callback: (callResults: string, fillData: KyberFillData): BigNumber[] => {
const [reserveId, hint, samples] = this._samplerContract.getABIDecodedReturnData<
[string, string, BigNumber[]]
>('sampleSellsFromKyberNetwork', callResults);
fillData.hint = hint;
fillData.reserveId = reserveId;
fillData.networkProxy = kyberOpts.networkProxy;
return isAllowedKyberReserveId(reserveId) ? samples : [];
},
});
}
public getKyberBuyQuotes(
kyberOpts: KyberSamplerOpts,
reserveOffset: BigNumber,
makerToken: string,
takerToken: string,
makerFillAmounts: BigNumber[],
): SourceQuoteOperation {
return new SamplerContractOperation({
source: ERC20BridgeSource.Kyber,
contract: this._samplerContract,
function: this._samplerContract.sampleBuysFromKyberNetwork,
params: [{ ...kyberOpts, reserveOffset, hint: NULL_BYTES }, takerToken, makerToken, makerFillAmounts],
callback: (callResults: string, fillData: KyberFillData): BigNumber[] => {
const [reserveId, hint, samples] = this._samplerContract.getABIDecodedReturnData<
[string, string, BigNumber[]]
>('sampleBuysFromKyberNetwork', callResults);
fillData.hint = hint;
fillData.reserveId = reserveId;
fillData.networkProxy = kyberOpts.networkProxy;
return isAllowedKyberReserveId(reserveId) ? samples : [];
},
});
}
public getKyberDmmSellQuotes(
router: string,
tokenAddressPath: string[],
@@ -763,6 +712,36 @@ export class SamplerOperations {
});
}
public getBancorV3SellQuotes(
networkAddress: string,
networkInfoAddress: string,
path: string[],
takerFillAmounts: BigNumber[],
): SourceQuoteOperation<BancorFillData> {
return new SamplerContractOperation({
source: ERC20BridgeSource.BancorV3,
fillData: { networkAddress, path },
contract: this._samplerContract,
function: this._samplerContract.sampleSellsFromBancorV3,
params: [MAINNET_TOKENS.WETH, networkInfoAddress, path, takerFillAmounts],
});
}
public getBancorV3BuyQuotes(
networkAddress: string,
networkInfoAddress: string,
path: string[],
makerFillAmounts: BigNumber[],
): SourceQuoteOperation<BancorFillData> {
return new SamplerContractOperation({
source: ERC20BridgeSource.BancorV3,
fillData: { networkAddress, path },
contract: this._samplerContract,
function: this._samplerContract.sampleBuysFromBancorV3,
params: [MAINNET_TOKENS.WETH, networkInfoAddress, path, makerFillAmounts],
});
}
public getMooniswapSellQuotes(
registry: string,
makerToken: string,
@@ -1160,8 +1139,10 @@ export class SamplerOperations {
return new SamplerContractOperation({
source: ERC20BridgeSource.Lido,
fillData: {
makerToken,
takerToken,
stEthTokenAddress: lidoInfo.stEthToken,
wstEthTokenAddress: lidoInfo.wstEthToken,
},
contract: this._samplerContract,
function: this._samplerContract.sampleSellsFromLido,
@@ -1178,8 +1159,10 @@ export class SamplerOperations {
return new SamplerContractOperation({
source: ERC20BridgeSource.Lido,
fillData: {
makerToken,
takerToken,
stEthTokenAddress: lidoInfo.stEthToken,
wstEthTokenAddress: lidoInfo.wstEthToken,
},
contract: this._samplerContract,
function: this._samplerContract.sampleBuysFromLido,
@@ -1465,6 +1448,7 @@ export class SamplerOperations {
case ERC20BridgeSource.Yoshi:
case ERC20BridgeSource.MorpheusSwap:
case ERC20BridgeSource.BiSwap:
case ERC20BridgeSource.MeshSwap:
const uniLikeRouter = uniswapV2LikeRouterAddress(this.chainId, source);
if (!isValidAddress(uniLikeRouter)) {
return [];
@@ -1479,16 +1463,6 @@ export class SamplerOperations {
return [];
}
return this.getKyberDmmSellQuotes(kyberDmmRouter, [takerToken, makerToken], takerFillAmounts);
case ERC20BridgeSource.Kyber:
return getKyberOffsets().map(offset =>
this.getKyberSellQuotes(
KYBER_CONFIG_BY_CHAIN_ID[this.chainId],
offset,
makerToken,
takerToken,
takerFillAmounts,
),
);
case ERC20BridgeSource.Curve:
case ERC20BridgeSource.CurveV2:
case ERC20BridgeSource.Nerve:
@@ -1667,16 +1641,10 @@ export class SamplerOperations {
].map(path => this.getUniswapV3SellQuotes(router, quoter, path, takerFillAmounts));
}
case ERC20BridgeSource.Lido: {
const lidoInfo = LIDO_INFO_BY_CHAIN[this.chainId];
if (
lidoInfo.stEthToken === NULL_ADDRESS ||
lidoInfo.wethToken === NULL_ADDRESS ||
takerToken.toLowerCase() !== lidoInfo.wethToken.toLowerCase() ||
makerToken.toLowerCase() !== lidoInfo.stEthToken.toLowerCase()
) {
if (!this._isLidoSupported(takerToken, makerToken)) {
return [];
}
const lidoInfo = LIDO_INFO_BY_CHAIN[this.chainId];
return this.getLidoSellQuotes(lidoInfo, makerToken, takerToken, takerFillAmounts);
}
case ERC20BridgeSource.AaveV2: {
@@ -1741,6 +1709,14 @@ export class SamplerOperations {
),
);
}
case ERC20BridgeSource.BancorV3: {
return this.getBancorV3SellQuotes(
BANCORV3_NETWORK_BY_CHAIN_ID[this.chainId],
BANCORV3_NETWORK_INFO_BY_CHAIN_ID[this.chainId],
[takerToken, makerToken],
takerFillAmounts,
);
}
default:
throw new Error(`Unsupported sell sample source: ${source}`);
}
@@ -1749,6 +1725,24 @@ export class SamplerOperations {
return allOps;
}
private _isLidoSupported(takerTokenAddress: string, makerTokenAddress: string): boolean {
const lidoInfo = LIDO_INFO_BY_CHAIN[this.chainId];
if (lidoInfo.wethToken === NULL_ADDRESS) {
return false;
}
const takerToken = takerTokenAddress.toLowerCase();
const makerToken = makerTokenAddress.toLowerCase();
const wethToken = lidoInfo.wethToken.toLowerCase();
const stEthToken = lidoInfo.stEthToken.toLowerCase();
const wstEthToken = lidoInfo.wstEthToken.toLowerCase();
if (takerToken === wethToken && makerToken === stEthToken) {
return true;
}
return _.difference([stEthToken, wstEthToken], [takerToken, makerToken]).length === 0;
}
private _getBuyQuoteOperations(
sources: ERC20BridgeSource[],
makerToken: string,
@@ -1796,6 +1790,7 @@ export class SamplerOperations {
case ERC20BridgeSource.Yoshi:
case ERC20BridgeSource.MorpheusSwap:
case ERC20BridgeSource.BiSwap:
case ERC20BridgeSource.MeshSwap:
const uniLikeRouter = uniswapV2LikeRouterAddress(this.chainId, source);
if (!isValidAddress(uniLikeRouter)) {
return [];
@@ -1810,16 +1805,6 @@ export class SamplerOperations {
return [];
}
return this.getKyberDmmBuyQuotes(kyberDmmRouter, [takerToken, makerToken], makerFillAmounts);
case ERC20BridgeSource.Kyber:
return getKyberOffsets().map(offset =>
this.getKyberBuyQuotes(
KYBER_CONFIG_BY_CHAIN_ID[this.chainId],
offset,
makerToken,
takerToken,
makerFillAmounts,
),
);
case ERC20BridgeSource.Curve:
case ERC20BridgeSource.CurveV2:
case ERC20BridgeSource.Nerve:
@@ -1998,17 +1983,10 @@ export class SamplerOperations {
].map(path => this.getUniswapV3BuyQuotes(router, quoter, path, makerFillAmounts));
}
case ERC20BridgeSource.Lido: {
const lidoInfo = LIDO_INFO_BY_CHAIN[this.chainId];
if (
lidoInfo.stEthToken === NULL_ADDRESS ||
lidoInfo.wethToken === NULL_ADDRESS ||
takerToken.toLowerCase() !== lidoInfo.wethToken.toLowerCase() ||
makerToken.toLowerCase() !== lidoInfo.stEthToken.toLowerCase()
) {
if (!this._isLidoSupported(takerToken, makerToken)) {
return [];
}
const lidoInfo = LIDO_INFO_BY_CHAIN[this.chainId];
return this.getLidoBuyQuotes(lidoInfo, makerToken, takerToken, makerFillAmounts);
}
case ERC20BridgeSource.AaveV2: {
@@ -2067,6 +2045,14 @@ export class SamplerOperations {
),
);
}
case ERC20BridgeSource.BancorV3: {
return this.getBancorV3BuyQuotes(
BANCORV3_NETWORK_BY_CHAIN_ID[this.chainId],
BANCORV3_NETWORK_INFO_BY_CHAIN_ID[this.chainId],
[takerToken, makerToken],
makerFillAmounts,
);
}
default:
throw new Error(`Unsupported buy sample source: ${source}`);
}

View File

@@ -38,7 +38,6 @@ export enum ERC20BridgeSource {
Native = 'Native',
Uniswap = 'Uniswap',
UniswapV2 = 'Uniswap_V2',
Kyber = 'Kyber',
Curve = 'Curve',
LiquidityProvider = 'LiquidityProvider',
MultiBridge = 'MultiBridge',
@@ -67,6 +66,7 @@ export enum ERC20BridgeSource {
AaveV2 = 'Aave_V2',
Compound = 'Compound',
Synapse = 'Synapse',
BancorV3 = 'BancorV3',
// BSC only
PancakeSwap = 'PancakeSwap',
PancakeSwapV2 = 'PancakeSwap_V2',
@@ -89,6 +89,7 @@ export enum ERC20BridgeSource {
FirebirdOneSwap = 'FirebirdOneSwap',
JetSwap = 'JetSwap',
IronSwap = 'IronSwap',
MeshSwap = 'MeshSwap',
// Avalanche
Pangolin = 'Pangolin',
TraderJoe = 'TraderJoe',
@@ -168,6 +169,7 @@ export interface PsmInfo {
export interface LidoInfo {
stEthToken: string;
wethToken: string;
wstEthToken: string;
}
/**
@@ -262,10 +264,9 @@ export interface BancorFillData extends FillData {
networkAddress: string;
}
export interface KyberFillData extends FillData {
hint: string;
reserveId: string;
networkProxy: string;
export interface BancorV3FillData extends FillData {
path: string[];
networkAddress: string;
}
export interface MooniswapFillData extends FillData {
@@ -332,7 +333,9 @@ export interface FinalUniswapV3FillData extends Omit<UniswapV3FillData, 'pathAmo
export interface LidoFillData extends FillData {
stEthTokenAddress: string;
wstEthTokenAddress: string;
takerToken: string;
makerToken: string;
}
export interface AaveV2FillData extends FillData {
@@ -392,7 +395,7 @@ export interface Fill<TFillData extends FillData = FillData> {
input: BigNumber;
// Output fill amount (maker asset amount in a sell, taker asset amount in a buy).
output: BigNumber;
// The output fill amount, ajdusted by fees.
// The output fill amount, adjusted by fees.
adjustedOutput: BigNumber;
// Fill that must precede this one. This enforces certain fills to be contiguous.
parent?: Fill;
@@ -693,9 +696,3 @@ export interface GenerateOptimizedOrdersOpts {
export interface ComparisonPrice {
wholeOrder: BigNumber | undefined;
}
export interface KyberSamplerOpts {
networkProxy: string;
hintHandler: string;
weth: string;
}

View File

@@ -12,6 +12,7 @@ import * as BalancerV2BatchSampler from '../test/generated-artifacts/BalancerV2B
import * as BalancerV2Common from '../test/generated-artifacts/BalancerV2Common.json';
import * as BalancerV2Sampler from '../test/generated-artifacts/BalancerV2Sampler.json';
import * as BancorSampler from '../test/generated-artifacts/BancorSampler.json';
import * as BancorV3Sampler from '../test/generated-artifacts/BancorV3Sampler.json';
import * as CompoundSampler from '../test/generated-artifacts/CompoundSampler.json';
import * as CurveSampler from '../test/generated-artifacts/CurveSampler.json';
import * as DODOSampler from '../test/generated-artifacts/DODOSampler.json';
@@ -22,9 +23,9 @@ import * as GMXSampler from '../test/generated-artifacts/GMXSampler.json';
import * as IBalancer from '../test/generated-artifacts/IBalancer.json';
import * as IBalancerV2Vault from '../test/generated-artifacts/IBalancerV2Vault.json';
import * as IBancor from '../test/generated-artifacts/IBancor.json';
import * as IBancorV3 from '../test/generated-artifacts/IBancorV3.json';
import * as ICurve from '../test/generated-artifacts/ICurve.json';
import * as IGMX from '../test/generated-artifacts/IGMX.json';
import * as IKyberNetwork from '../test/generated-artifacts/IKyberNetwork.json';
import * as IMooniswap from '../test/generated-artifacts/IMooniswap.json';
import * as IMStable from '../test/generated-artifacts/IMStable.json';
import * as IMultiBridge from '../test/generated-artifacts/IMultiBridge.json';
@@ -34,7 +35,6 @@ import * as ISmoothy from '../test/generated-artifacts/ISmoothy.json';
import * as IUniswapExchangeQuotes from '../test/generated-artifacts/IUniswapExchangeQuotes.json';
import * as IUniswapV2Router01 from '../test/generated-artifacts/IUniswapV2Router01.json';
import * as KyberDmmSampler from '../test/generated-artifacts/KyberDmmSampler.json';
import * as KyberSampler from '../test/generated-artifacts/KyberSampler.json';
import * as LidoSampler from '../test/generated-artifacts/LidoSampler.json';
import * as LiquidityProviderSampler from '../test/generated-artifacts/LiquidityProviderSampler.json';
import * as MakerPSMSampler from '../test/generated-artifacts/MakerPSMSampler.json';
@@ -59,6 +59,7 @@ export const artifacts = {
BalancerV2Common: BalancerV2Common as ContractArtifact,
BalancerV2Sampler: BalancerV2Sampler as ContractArtifact,
BancorSampler: BancorSampler as ContractArtifact,
BancorV3Sampler: BancorV3Sampler as ContractArtifact,
CompoundSampler: CompoundSampler as ContractArtifact,
CurveSampler: CurveSampler as ContractArtifact,
DODOSampler: DODOSampler as ContractArtifact,
@@ -67,7 +68,6 @@ export const artifacts = {
FakeTaker: FakeTaker as ContractArtifact,
GMXSampler: GMXSampler as ContractArtifact,
KyberDmmSampler: KyberDmmSampler as ContractArtifact,
KyberSampler: KyberSampler as ContractArtifact,
LidoSampler: LidoSampler as ContractArtifact,
LiquidityProviderSampler: LiquidityProviderSampler as ContractArtifact,
MStableSampler: MStableSampler as ContractArtifact,
@@ -86,9 +86,9 @@ export const artifacts = {
IBalancer: IBalancer as ContractArtifact,
IBalancerV2Vault: IBalancerV2Vault as ContractArtifact,
IBancor: IBancor as ContractArtifact,
IBancorV3: IBancorV3 as ContractArtifact,
ICurve: ICurve as ContractArtifact,
IGMX: IGMX as ContractArtifact,
IKyberNetwork: IKyberNetwork as ContractArtifact,
IMStable: IMStable as ContractArtifact,
IMooniswap: IMooniswap as ContractArtifact,
IMultiBridge: IMultiBridge as ContractArtifact,

View File

@@ -21,8 +21,8 @@ const GAS_PRICE = new BigNumber(50e9); // 50 gwei
const NATIVE_ORDER_FEE = new BigNumber(220e3); // 220K gas
// DEX samples to fill in MarketSideLiquidity
const kyberSample1: DexSample = {
source: ERC20BridgeSource.Kyber,
const curveSample: DexSample = {
source: ERC20BridgeSource.Curve,
input: new BigNumber(10000),
output: new BigNumber(10001),
fillData: {},
@@ -33,7 +33,7 @@ const uniswapSample1: DexSample = {
output: new BigNumber(10004),
fillData: {},
};
const dexQuotes: DexSample[] = [kyberSample1, uniswapSample1];
const dexQuotes: DexSample[] = [curveSample, uniswapSample1];
const feeSchedule = {
[ERC20BridgeSource.Native]: _.constant(GAS_PRICE.times(NATIVE_ORDER_FEE)),

View File

@@ -0,0 +1,298 @@
import { ChainId } from '@0x/contract-addresses';
import { blockchainTests, constants, describe, expect } from '@0x/contracts-test-utils';
import {
artifacts as zeroExArtifacts,
AvalancheBridgeAdapterContract,
BSCBridgeAdapterContract,
CeloBridgeAdapterContract,
EthereumBridgeAdapterContract,
FantomBridgeAdapterContract,
OptimismBridgeAdapterContract,
PolygonBridgeAdapterContract,
} from '@0x/contracts-zero-ex';
import { BUY_SOURCE_FILTER_BY_CHAIN_ID, ERC20BridgeSource, SELL_SOURCE_FILTER_BY_CHAIN_ID } from '../../src';
import { getErc20BridgeSourceToBridgeSource } from '../../src/utils/market_operation_utils/orders';
blockchainTests('Bridge adapter source compatibility tests', env => {
describe('Avalanche', () => {
let adapter: AvalancheBridgeAdapterContract;
before(async () => {
adapter = await AvalancheBridgeAdapterContract.deployFrom0xArtifactAsync(
zeroExArtifacts.AvalancheBridgeAdapter,
env.provider,
env.txDefaults,
zeroExArtifacts,
constants.NULL_ADDRESS,
);
});
it('sell sources', async () => {
const sellSources = SELL_SOURCE_FILTER_BY_CHAIN_ID[ChainId.Avalanche].exclude([
ERC20BridgeSource.Native,
ERC20BridgeSource.MultiHop,
]).sources;
return Promise.all(
sellSources.map(async source => {
const isSupported = await adapter
.isSupportedSource(getErc20BridgeSourceToBridgeSource(source))
.callAsync();
expect(isSupported, `${source} is not supported`).to.be.true();
}),
);
});
it('buy sources', async () => {
const buySources = BUY_SOURCE_FILTER_BY_CHAIN_ID[ChainId.Avalanche].exclude([
ERC20BridgeSource.Native,
ERC20BridgeSource.MultiHop,
]).sources;
return Promise.all(
buySources.map(async source => {
const isSupported = await adapter
.isSupportedSource(getErc20BridgeSourceToBridgeSource(source))
.callAsync();
expect(isSupported, `${source} is not supported`).to.be.true();
}),
);
});
});
describe('BSC', () => {
let adapter: BSCBridgeAdapterContract;
before(async () => {
adapter = await BSCBridgeAdapterContract.deployFrom0xArtifactAsync(
zeroExArtifacts.BSCBridgeAdapter,
env.provider,
env.txDefaults,
zeroExArtifacts,
constants.NULL_ADDRESS,
);
});
it('sell sources', async () => {
const sellSources = SELL_SOURCE_FILTER_BY_CHAIN_ID[ChainId.BSC].exclude([
ERC20BridgeSource.Native,
ERC20BridgeSource.MultiHop,
]).sources;
return Promise.all(
sellSources.map(async source => {
const isSupported = await adapter
.isSupportedSource(getErc20BridgeSourceToBridgeSource(source))
.callAsync();
expect(isSupported, `${source} is not supported`).to.be.true();
}),
);
});
it('buy sources', async () => {
const buySources = BUY_SOURCE_FILTER_BY_CHAIN_ID[ChainId.BSC].exclude([
ERC20BridgeSource.Native,
ERC20BridgeSource.MultiHop,
]).sources;
return Promise.all(
buySources.map(async source => {
const isSupported = await adapter
.isSupportedSource(getErc20BridgeSourceToBridgeSource(source))
.callAsync();
expect(isSupported, `${source} is not supported`).to.be.true();
}),
);
});
});
describe('Celo', () => {
let adapter: CeloBridgeAdapterContract;
before(async () => {
adapter = await CeloBridgeAdapterContract.deployFrom0xArtifactAsync(
zeroExArtifacts.CeloBridgeAdapter,
env.provider,
env.txDefaults,
zeroExArtifacts,
constants.NULL_ADDRESS,
);
});
it('sell sources', async () => {
const sellSources = SELL_SOURCE_FILTER_BY_CHAIN_ID[ChainId.Celo].exclude([
ERC20BridgeSource.Native,
ERC20BridgeSource.MultiHop,
]).sources;
return Promise.all(
sellSources.map(async source => {
const isSupported = await adapter
.isSupportedSource(getErc20BridgeSourceToBridgeSource(source))
.callAsync();
expect(isSupported, `${source} is not supported`).to.be.true();
}),
);
});
it('buy sources', async () => {
const buySources = BUY_SOURCE_FILTER_BY_CHAIN_ID[ChainId.Celo].exclude([
ERC20BridgeSource.Native,
ERC20BridgeSource.MultiHop,
]).sources;
return Promise.all(
buySources.map(async source => {
const isSupported = await adapter
.isSupportedSource(getErc20BridgeSourceToBridgeSource(source))
.callAsync();
expect(isSupported, `${source} is not supported`).to.be.true();
}),
);
});
});
describe('Ethereum', () => {
let adapter: EthereumBridgeAdapterContract;
before(async () => {
adapter = await EthereumBridgeAdapterContract.deployFrom0xArtifactAsync(
zeroExArtifacts.EthereumBridgeAdapter,
env.provider,
env.txDefaults,
zeroExArtifacts,
constants.NULL_ADDRESS,
);
});
it('sell sources', async () => {
const sellSources = SELL_SOURCE_FILTER_BY_CHAIN_ID[ChainId.Mainnet].exclude([
ERC20BridgeSource.Native,
ERC20BridgeSource.MultiHop,
]).sources;
return Promise.all(
sellSources.map(async source => {
const isSupported = await adapter
.isSupportedSource(getErc20BridgeSourceToBridgeSource(source))
.callAsync();
expect(isSupported, `${source} is not supported`).to.be.true();
}),
);
});
it('buy sources', async () => {
const buySources = BUY_SOURCE_FILTER_BY_CHAIN_ID[ChainId.Mainnet].exclude([
ERC20BridgeSource.Native,
ERC20BridgeSource.MultiHop,
]).sources;
return Promise.all(
buySources.map(async source => {
const isSupported = await adapter
.isSupportedSource(getErc20BridgeSourceToBridgeSource(source))
.callAsync();
expect(isSupported, `${source} is not supported`).to.be.true();
}),
);
});
});
describe('Fantom', () => {
let adapter: FantomBridgeAdapterContract;
before(async () => {
adapter = await FantomBridgeAdapterContract.deployFrom0xArtifactAsync(
zeroExArtifacts.FantomBridgeAdapter,
env.provider,
env.txDefaults,
zeroExArtifacts,
constants.NULL_ADDRESS,
);
});
it('sell sources', async () => {
const sellSources = SELL_SOURCE_FILTER_BY_CHAIN_ID[ChainId.Fantom].exclude([
ERC20BridgeSource.Native,
ERC20BridgeSource.MultiHop,
]).sources;
return Promise.all(
sellSources.map(async source => {
const isSupported = await adapter
.isSupportedSource(getErc20BridgeSourceToBridgeSource(source))
.callAsync();
expect(isSupported, `${source} is not supported`).to.be.true();
}),
);
});
it('buy sources', async () => {
const buySources = BUY_SOURCE_FILTER_BY_CHAIN_ID[ChainId.Fantom].exclude([
ERC20BridgeSource.Native,
ERC20BridgeSource.MultiHop,
]).sources;
return Promise.all(
buySources.map(async source => {
const isSupported = await adapter
.isSupportedSource(getErc20BridgeSourceToBridgeSource(source))
.callAsync();
expect(isSupported, `${source} is not supported`).to.be.true();
}),
);
});
});
describe('Optimism', () => {
let adapter: OptimismBridgeAdapterContract;
before(async () => {
adapter = await OptimismBridgeAdapterContract.deployFrom0xArtifactAsync(
zeroExArtifacts.OptimismBridgeAdapter,
env.provider,
env.txDefaults,
zeroExArtifacts,
constants.NULL_ADDRESS,
);
});
it('sell sources', async () => {
const sellSources = SELL_SOURCE_FILTER_BY_CHAIN_ID[ChainId.Optimism].exclude([
ERC20BridgeSource.Native,
ERC20BridgeSource.MultiHop,
]).sources;
return Promise.all(
sellSources.map(async source => {
const isSupported = await adapter
.isSupportedSource(getErc20BridgeSourceToBridgeSource(source))
.callAsync();
expect(isSupported, `${source} is not supported`).to.be.true();
}),
);
});
it('buy sources', async () => {
const buySources = BUY_SOURCE_FILTER_BY_CHAIN_ID[ChainId.Optimism].exclude([
ERC20BridgeSource.Native,
ERC20BridgeSource.MultiHop,
]).sources;
return Promise.all(
buySources.map(async source => {
const isSupported = await adapter
.isSupportedSource(getErc20BridgeSourceToBridgeSource(source))
.callAsync();
expect(isSupported, `${source} is not supported`).to.be.true();
}),
);
});
});
describe('Polygon', () => {
let adapter: PolygonBridgeAdapterContract;
before(async () => {
adapter = await PolygonBridgeAdapterContract.deployFrom0xArtifactAsync(
zeroExArtifacts.PolygonBridgeAdapter,
env.provider,
env.txDefaults,
zeroExArtifacts,
constants.NULL_ADDRESS,
);
});
it('sell sources', async () => {
const sellSources = SELL_SOURCE_FILTER_BY_CHAIN_ID[ChainId.Polygon].exclude([
ERC20BridgeSource.Native,
ERC20BridgeSource.MultiHop,
]).sources;
return Promise.all(
sellSources.map(async source => {
const isSupported = await adapter
.isSupportedSource(getErc20BridgeSourceToBridgeSource(source))
.callAsync();
expect(isSupported, `${source} is not supported`).to.be.true();
}),
);
});
it('buy sources', async () => {
const buySources = BUY_SOURCE_FILTER_BY_CHAIN_ID[ChainId.Polygon].exclude([
ERC20BridgeSource.Native,
ERC20BridgeSource.MultiHop,
]).sources;
return Promise.all(
buySources.map(async source => {
const isSupported = await adapter
.isSupportedSource(getErc20BridgeSourceToBridgeSource(source))
.callAsync();
expect(isSupported, `${source} is not supported`).to.be.true();
}),
);
});
});
});

View File

@@ -1,9 +1,7 @@
import { ChainId } from '@0x/contract-addresses';
import { blockchainTests, describe, expect, toBaseUnitAmount, Web3ProviderEngine } from '@0x/contracts-test-utils';
import { RPCSubprovider } from '@0x/subproviders';
import { BigNumber, NULL_BYTES, providerUtils } from '@0x/utils';
import { BigNumber, providerUtils } from '@0x/utils';
import { KYBER_CONFIG_BY_CHAIN_ID, MAINNET_TOKENS } from '../../src/utils/market_operation_utils/constants';
import { artifacts } from '../artifacts';
import { ERC20BridgeSamplerContract } from '../wrappers';
@@ -79,60 +77,4 @@ blockchainTests.skip('Mainnet Sampler Tests', env => {
});
});
});
describe('Kyber', () => {
const WETH = MAINNET_TOKENS.WETH;
const DAI = MAINNET_TOKENS.DAI;
const USDC = MAINNET_TOKENS.USDC;
const RESERVE_OFFSET = new BigNumber(0);
const KYBER_OPTS = {
...KYBER_CONFIG_BY_CHAIN_ID[ChainId.Mainnet],
reserveOffset: RESERVE_OFFSET,
hint: NULL_BYTES,
};
describe('sampleSellsFromKyberNetwork()', () => {
it('samples sells from Kyber DAI->WETH', async () => {
const [, samples] = await testContract
.sampleSellsFromKyberNetwork(KYBER_OPTS, DAI, WETH, [toBaseUnitAmount(1)])
.callAsync({ overrides });
expect(samples.length).to.be.bignumber.greaterThan(0);
expect(samples[0]).to.be.bignumber.greaterThan(0);
});
it('samples sells from Kyber WETH->DAI', async () => {
const [, samples] = await testContract
.sampleSellsFromKyberNetwork(KYBER_OPTS, WETH, DAI, [toBaseUnitAmount(1)])
.callAsync({ overrides });
expect(samples.length).to.be.bignumber.greaterThan(0);
expect(samples[0]).to.be.bignumber.greaterThan(0);
});
it('samples sells from Kyber DAI->USDC', async () => {
const [, samples] = await testContract
.sampleSellsFromKyberNetwork(KYBER_OPTS, DAI, USDC, [toBaseUnitAmount(1)])
.callAsync({ overrides });
expect(samples.length).to.be.bignumber.greaterThan(0);
expect(samples[0]).to.be.bignumber.greaterThan(0);
});
});
describe('sampleBuysFromKyber()', () => {
it('samples buys from Kyber WETH->DAI', async () => {
// From ETH to DAI
// I want to buy 1 DAI
const [, samples] = await testContract
.sampleBuysFromKyberNetwork(KYBER_OPTS, WETH, DAI, [toBaseUnitAmount(1)])
.callAsync({ overrides });
expect(samples.length).to.be.bignumber.greaterThan(0);
expect(samples[0]).to.be.bignumber.greaterThan(0);
});
it('samples buys from Kyber DAI->WETH', async () => {
// From USDC to DAI
// I want to buy 1 WETH
const [, samples] = await testContract
.sampleBuysFromKyberNetwork(KYBER_OPTS, DAI, WETH, [toBaseUnitAmount(1)])
.callAsync({ overrides });
expect(samples.length).to.be.bignumber.greaterThan(0);
expect(samples[0]).to.be.bignumber.greaterThan(0);
});
});
});
});

View File

@@ -21,7 +21,7 @@ import { generatePseudoRandomSalt } from './utils/utils';
const CHAIN_ID = 1;
const EMPTY_BYTES32 = '0x0000000000000000000000000000000000000000000000000000000000000000';
// tslint:disable: custom-no-magic-numbers
describe.skip('DexSampler tests', () => {
describe('DexSampler tests', () => {
const MAKER_TOKEN = randomAddress();
const TAKER_TOKEN = randomAddress();
const chainId = ChainId.Mainnet;
@@ -142,40 +142,6 @@ describe.skip('DexSampler tests', () => {
expect(fillableAmounts).to.deep.eq(expectedFillableAmounts);
});
it('getKyberSellQuotes()', async () => {
const expectedTakerToken = randomAddress();
const expectedMakerToken = randomAddress();
const expectedTakerFillAmounts = getSampleAmounts(new BigNumber(100e18), 10);
const expectedMakerFillAmounts = getSampleAmounts(new BigNumber(100e18), 10);
const sampler = new MockSamplerContract({
sampleSellsFromKyberNetwork: (_reserveOffset, takerToken, makerToken, fillAmounts) => {
expect(takerToken).to.eq(expectedTakerToken);
expect(makerToken).to.eq(expectedMakerToken);
expect(fillAmounts).to.deep.eq(expectedTakerFillAmounts);
return ['0x', '0x', expectedMakerFillAmounts];
},
});
const dexOrderSampler = new DexOrderSampler(
chainId,
sampler,
undefined,
undefined,
undefined,
undefined,
async () => undefined,
);
const [fillableAmounts] = await dexOrderSampler.executeAsync(
dexOrderSampler.getKyberSellQuotes(
{ hintHandler: randomAddress(), networkProxy: randomAddress(), weth: randomAddress() },
new BigNumber(0),
expectedMakerToken,
expectedTakerToken,
expectedTakerFillAmounts,
),
);
expect(fillableAmounts).to.deep.eq(expectedMakerFillAmounts);
});
it('getLiquidityProviderSellQuotes()', async () => {
const expectedMakerToken = randomAddress();
const expectedTakerToken = randomAddress();
@@ -370,7 +336,6 @@ describe.skip('DexSampler tests', () => {
const expectedMakerToken = randomAddress();
const sources = [ERC20BridgeSource.Uniswap, ERC20BridgeSource.UniswapV2];
const ratesBySource: RatesBySource = {
[ERC20BridgeSource.Kyber]: getRandomFloat(0, 100),
[ERC20BridgeSource.Uniswap]: getRandomFloat(0, 100),
[ERC20BridgeSource.UniswapV2]: getRandomFloat(0, 100),
};

View File

@@ -11,7 +11,7 @@ import {
import { FillQuoteTransformerOrderType, LimitOrder, RfqOrder, SignatureType } from '@0x/protocol-utils';
import { BigNumber, hexUtils, NULL_BYTES } from '@0x/utils';
import { Web3Wrapper } from '@0x/web3-wrapper';
import { Pool } from '@balancer-labs/sor/dist/types';
import { Pool } from 'balancer-labs-sor-v1/dist/types';
import * as _ from 'lodash';
import * as TypeMoq from 'typemoq';
@@ -50,9 +50,9 @@ const TAKER_TOKEN = randomAddress();
const DEFAULT_INCLUDED = [
ERC20BridgeSource.SushiSwap,
ERC20BridgeSource.Kyber,
ERC20BridgeSource.Native,
ERC20BridgeSource.Uniswap,
ERC20BridgeSource.Curve,
];
const DEFAULT_EXCLUDED = SELL_SOURCE_FILTER_BY_CHAIN_ID[ChainId.Mainnet].sources.filter(
@@ -321,7 +321,7 @@ describe('MarketOperationUtils tests', () => {
[ERC20BridgeSource.Native]: createDecreasingRates(NUM_SAMPLES),
[ERC20BridgeSource.SushiSwap]: createDecreasingRates(NUM_SAMPLES),
[ERC20BridgeSource.Uniswap]: createDecreasingRates(NUM_SAMPLES),
[ERC20BridgeSource.Kyber]: createDecreasingRates(NUM_SAMPLES),
[ERC20BridgeSource.Curve]: createDecreasingRates(NUM_SAMPLES),
};
interface FillDataBySource {
@@ -337,7 +337,6 @@ describe('MarketOperationUtils tests', () => {
deadline: Math.floor(Date.now() / 1000) + 300,
},
[ERC20BridgeSource.Bancor]: { path: [], networkAddress: randomAddress() },
[ERC20BridgeSource.Kyber]: { hint: '0x', reserveId: '0x', networkAddress: randomAddress() },
[ERC20BridgeSource.Curve]: {
pool: {
poolAddress: randomAddress(),
@@ -1034,7 +1033,7 @@ describe('MarketOperationUtils tests', () => {
rates[ERC20BridgeSource.Native] = [0.4, 0.3, 0.2, 0.1];
rates[ERC20BridgeSource.Uniswap] = [0.5, 0.05, 0.05, 0.05];
rates[ERC20BridgeSource.SushiSwap] = [0.6, 0.05, 0.05, 0.05];
rates[ERC20BridgeSource.Kyber] = [0, 0, 0, 0]; // unused
rates[ERC20BridgeSource.Curve] = [0, 0, 0, 0]; // unused
replaceSamplerOps({
getSellQuotes: createGetMultipleSellQuotesOperationFromRates(rates),
});
@@ -1066,7 +1065,6 @@ describe('MarketOperationUtils tests', () => {
[ERC20BridgeSource.Native]: [1, 0.99, 0.98, 0.97], // Effectively [0.94, 0.93, 0.92, 0.91]
[ERC20BridgeSource.Uniswap]: [0.96, 0.1, 0.1, 0.1],
[ERC20BridgeSource.SushiSwap]: [0.95, 0.1, 0.1, 0.1],
[ERC20BridgeSource.Kyber]: [0.1, 0.1, 0.1, 0.1],
};
const feeSchedule = {
[ERC20BridgeSource.Native]: _.constant(
@@ -1097,12 +1095,10 @@ describe('MarketOperationUtils tests', () => {
});
it('factors in fees for dexes', async () => {
// Kyber will have the best rates but will have fees,
// dropping its effective rates.
const uniswapFeeRate = 0.2;
const rates: RatesBySource = {
[ERC20BridgeSource.Native]: [0.95, 0.1, 0.1, 0.1],
[ERC20BridgeSource.Kyber]: [0.1, 0.1, 0.1, 0.1],
[ERC20BridgeSource.Curve]: [0.1, 0.1, 0.1, 0.1],
[ERC20BridgeSource.SushiSwap]: [0.92, 0.1, 0.1, 0.1],
// Effectively [0.8, ~0.5, ~0, ~0]
[ERC20BridgeSource.Uniswap]: [1, 0.7, 0.2, 0.2],
@@ -1136,7 +1132,7 @@ describe('MarketOperationUtils tests', () => {
it('can mix one concave source', async () => {
const rates: RatesBySource = {
[ERC20BridgeSource.Kyber]: [0, 0, 0, 0], // Won't use
[ERC20BridgeSource.Curve]: [0, 0, 0, 0], // Won't use
[ERC20BridgeSource.SushiSwap]: [0.5, 0.85, 0.75, 0.75], // Concave
[ERC20BridgeSource.Uniswap]: [0.96, 0.2, 0.1, 0.1],
[ERC20BridgeSource.Native]: [0.95, 0.2, 0.2, 0.1],
@@ -1168,7 +1164,7 @@ describe('MarketOperationUtils tests', () => {
rates[ERC20BridgeSource.Native] = [1, 1, 0.01, 0.01];
rates[ERC20BridgeSource.Uniswap] = [1, 1, 0.01, 0.01];
rates[ERC20BridgeSource.SushiSwap] = [0.49, 0.49, 0.49, 0.49];
rates[ERC20BridgeSource.Kyber] = [0.35, 0.2, 0.01, 0.01];
rates[ERC20BridgeSource.Curve] = [0.35, 0.2, 0.01, 0.01];
replaceSamplerOps({
getSellQuotes: createGetMultipleSellQuotesOperationFromRates(rates),
});
@@ -1517,7 +1513,7 @@ describe('MarketOperationUtils tests', () => {
[ERC20BridgeSource.Native]: [1, 0.99, 0.98, 0.97], // Effectively [0.94, ~0.93, ~0.92, ~0.91]
[ERC20BridgeSource.Uniswap]: [0.96, 0.1, 0.1, 0.1],
[ERC20BridgeSource.SushiSwap]: [0.95, 0.1, 0.1, 0.1],
[ERC20BridgeSource.Kyber]: [0.1, 0.1, 0.1, 0.1],
[ERC20BridgeSource.Curve]: [0.1, 0.1, 0.1, 0.1],
};
const feeSchedule = {
[ERC20BridgeSource.Native]: _.constant(

View File

@@ -58,8 +58,8 @@ describe('generateQuoteReport', async () => {
it('should generate report properly for sell', () => {
const marketOperation: MarketOperation = MarketOperation.Sell;
const kyberSample2: DexSample = {
source: ERC20BridgeSource.Kyber,
const balancerSample2: DexSample = {
source: ERC20BridgeSource.BalancerV2,
input: new BigNumber(10003),
output: new BigNumber(10004),
fillData: {},
@@ -117,15 +117,15 @@ describe('generateQuoteReport', async () => {
sourcePathId: hexUtils.random(),
type: FillQuoteTransformerOrderType.Bridge,
};
const kyber2Fill: CollapsedFill = {
...kyberSample2,
const balancer2Fill: CollapsedFill = {
...balancerSample2,
subFills: [],
sourcePathId: hexUtils.random(),
type: FillQuoteTransformerOrderType.Bridge,
};
const orderbookOrder2Fill: CollapsedFill = collapsedFillFromNativeOrder(orderbookOrder2);
const rfqtOrder2Fill: CollapsedFill = collapsedFillFromNativeOrder(rfqtOrder2);
const pathGenerated: CollapsedFill[] = [rfqtOrder2Fill, orderbookOrder2Fill, uniswap2Fill, kyber2Fill];
const pathGenerated: CollapsedFill[] = [rfqtOrder2Fill, orderbookOrder2Fill, uniswap2Fill, balancer2Fill];
// quote generator mock
const quoteRequestor = TypeMoq.Mock.ofType<QuoteRequestor>();
@@ -190,10 +190,10 @@ describe('generateQuoteReport', async () => {
takerAmount: uniswapSample2.input,
fillData: {},
};
const kyber2Source: BridgeQuoteReportEntry = {
liquiditySource: ERC20BridgeSource.Kyber,
makerAmount: kyberSample2.output,
takerAmount: kyberSample2.input,
const balancer2Source: BridgeQuoteReportEntry = {
liquiditySource: ERC20BridgeSource.BalancerV2,
makerAmount: balancerSample2.output,
takerAmount: balancerSample2.input,
fillData: {},
};
@@ -202,7 +202,7 @@ describe('generateQuoteReport', async () => {
rfqtOrder2Source,
orderbookOrder2Source,
uniswap2Source,
kyber2Source,
balancer2Source,
];
expectEqualQuoteReportEntries(orderReport.sourcesConsidered, expectedSourcesConsidered, `sourcesConsidered`);
expectEqualQuoteReportEntries(orderReport.sourcesDelivered, expectedSourcesDelivered, `sourcesDelivered`);
@@ -210,8 +210,8 @@ describe('generateQuoteReport', async () => {
});
it('should handle properly for buy without quoteRequestor', () => {
const marketOperation: MarketOperation = MarketOperation.Buy;
const kyberSample1: DexSample = {
source: ERC20BridgeSource.Kyber,
const balancerSample1: DexSample = {
source: ERC20BridgeSource.BalancerV2,
input: new BigNumber(10000),
output: new BigNumber(10001),
fillData: {},
@@ -248,13 +248,13 @@ describe('generateQuoteReport', async () => {
sourcePathId: hexUtils.random(),
type: FillQuoteTransformerOrderType.Bridge,
};
const kyber1Fill: CollapsedFill = {
...kyberSample1,
const balancer1Fill: CollapsedFill = {
...balancerSample1,
subFills: [],
sourcePathId: hexUtils.random(),
type: FillQuoteTransformerOrderType.Bridge,
};
const pathGenerated: CollapsedFill[] = [orderbookOrder1Fill, uniswap1Fill, kyber1Fill];
const pathGenerated: CollapsedFill[] = [orderbookOrder1Fill, uniswap1Fill, balancer1Fill];
const orderReport = generateQuoteReport(marketOperation, nativeOrders, pathGenerated);
@@ -274,16 +274,16 @@ describe('generateQuoteReport', async () => {
takerAmount: uniswapSample1.output,
fillData: {},
};
const kyber1Source: BridgeQuoteReportEntry = {
liquiditySource: ERC20BridgeSource.Kyber,
makerAmount: kyberSample1.input,
takerAmount: kyberSample1.output,
const balancer1Source: BridgeQuoteReportEntry = {
liquiditySource: ERC20BridgeSource.BalancerV2,
makerAmount: balancerSample1.input,
takerAmount: balancerSample1.output,
fillData: {},
};
// No order is considered here because only Native RFQ orders are considered.
const expectedSourcesConsidered: QuoteReportEntry[] = [];
const expectedSourcesDelivered: QuoteReportEntry[] = [orderbookOrder1Source, uniswap1Source, kyber1Source];
const expectedSourcesDelivered: QuoteReportEntry[] = [orderbookOrder1Source, uniswap1Source, balancer1Source];
expectEqualQuoteReportEntries(orderReport.sourcesConsidered, expectedSourcesConsidered, `sourcesConsidered`);
expectEqualQuoteReportEntries(orderReport.sourcesDelivered, expectedSourcesDelivered, `sourcesDelivered`);
});

View File

@@ -1,10 +1,9 @@
import { ContractTxFunctionObj } from '@0x/base-contract';
import { constants } from '@0x/contracts-test-utils';
import { LimitOrderFields, Signature } from '@0x/protocol-utils';
import { BigNumber, hexUtils, NULL_BYTES } from '@0x/utils';
import { BigNumber, hexUtils } from '@0x/utils';
import { SamplerCallResult } from '../../src/types';
import { KyberSamplerOpts } from '../../src/utils/market_operation_utils/types';
import { ERC20BridgeSamplerContract } from '../../src/wrappers';
export type GetOrderFillableAssetAmountResult = BigNumber[];
@@ -39,18 +38,6 @@ export type SampleBuysEth2DaiHandler = (
makerToken: string,
makerTokenAmounts: BigNumber[],
) => SampleResults;
export type SampleSellsKyberHandler = (
opts: KyberSamplerOpts,
takerToken: string,
makerToken: string,
takerTokenAmounts: BigNumber[],
) => [string, string, SampleResults];
export type SampleBuysKyberHandler = (
reserveId: string,
takerToken: string,
makerToken: string,
makerTokenAmounts: BigNumber[],
) => [string, SampleResults];
export type SampleUniswapV2Handler = (router: string, path: string[], assetAmounts: BigNumber[]) => SampleResults;
export type SampleBuysMultihopHandler = (path: string[], takerTokenAmounts: BigNumber[]) => SampleResults;
export type SampleSellsLPHandler = (
@@ -70,7 +57,6 @@ const DUMMY_PROVIDER = {
interface Handlers {
getLimitOrderFillableMakerAssetAmounts: GetOrderFillableAssetAmountHandler;
getLimitOrderFillableTakerAssetAmounts: GetOrderFillableAssetAmountHandler;
sampleSellsFromKyberNetwork: SampleSellsKyberHandler;
sampleSellsFromLiquidityProvider: SampleSellsLPHandler;
sampleSellsFromUniswap: SampleSellsUniswapHandler;
sampleSellsFromUniswapV2: SampleUniswapV2Handler;
@@ -123,22 +109,6 @@ export class MockSamplerContract extends ERC20BridgeSamplerContract {
);
}
public sampleSellsFromKyberNetwork(
opts: KyberSamplerOpts,
takerToken: string,
makerToken: string,
takerAssetAmounts: BigNumber[],
): ContractTxFunctionObj<[string, string, BigNumber[]]> {
return this._wrapCall(
super.sampleSellsFromKyberNetwork,
this._handlers.sampleSellsFromKyberNetwork,
{ ...opts, reserveOffset: new BigNumber(1), hint: NULL_BYTES },
takerToken,
makerToken,
takerAssetAmounts,
);
}
public sampleSellsFromUniswap(
router: string,
takerToken: string,

View File

@@ -10,6 +10,7 @@ export * from '../test/generated-wrappers/balancer_v2_batch_sampler';
export * from '../test/generated-wrappers/balancer_v2_common';
export * from '../test/generated-wrappers/balancer_v2_sampler';
export * from '../test/generated-wrappers/bancor_sampler';
export * from '../test/generated-wrappers/bancor_v3_sampler';
export * from '../test/generated-wrappers/compound_sampler';
export * from '../test/generated-wrappers/curve_sampler';
export * from '../test/generated-wrappers/d_o_d_o_sampler';
@@ -20,8 +21,8 @@ export * from '../test/generated-wrappers/g_m_x_sampler';
export * from '../test/generated-wrappers/i_balancer';
export * from '../test/generated-wrappers/i_balancer_v2_vault';
export * from '../test/generated-wrappers/i_bancor';
export * from '../test/generated-wrappers/i_bancor_v3';
export * from '../test/generated-wrappers/i_curve';
export * from '../test/generated-wrappers/i_kyber_network';
export * from '../test/generated-wrappers/i_m_stable';
export * from '../test/generated-wrappers/i_mooniswap';
export * from '../test/generated-wrappers/i_multi_bridge';
@@ -32,7 +33,6 @@ export * from '../test/generated-wrappers/i_uniswap_exchange_quotes';
export * from '../test/generated-wrappers/i_uniswap_v2_router01';
export * from '../test/generated-wrappers/igmx';
export * from '../test/generated-wrappers/kyber_dmm_sampler';
export * from '../test/generated-wrappers/kyber_sampler';
export * from '../test/generated-wrappers/lido_sampler';
export * from '../test/generated-wrappers/liquidity_provider_sampler';
export * from '../test/generated-wrappers/m_stable_sampler';

View File

@@ -13,6 +13,7 @@
"test/generated-artifacts/BalancerV2Common.json",
"test/generated-artifacts/BalancerV2Sampler.json",
"test/generated-artifacts/BancorSampler.json",
"test/generated-artifacts/BancorV3Sampler.json",
"test/generated-artifacts/CompoundSampler.json",
"test/generated-artifacts/CurveSampler.json",
"test/generated-artifacts/DODOSampler.json",
@@ -23,9 +24,9 @@
"test/generated-artifacts/IBalancer.json",
"test/generated-artifacts/IBalancerV2Vault.json",
"test/generated-artifacts/IBancor.json",
"test/generated-artifacts/IBancorV3.json",
"test/generated-artifacts/ICurve.json",
"test/generated-artifacts/IGMX.json",
"test/generated-artifacts/IKyberNetwork.json",
"test/generated-artifacts/IMStable.json",
"test/generated-artifacts/IMooniswap.json",
"test/generated-artifacts/IMultiBridge.json",
@@ -35,7 +36,6 @@
"test/generated-artifacts/IUniswapExchangeQuotes.json",
"test/generated-artifacts/IUniswapV2Router01.json",
"test/generated-artifacts/KyberDmmSampler.json",
"test/generated-artifacts/KyberSampler.json",
"test/generated-artifacts/LidoSampler.json",
"test/generated-artifacts/LiquidityProviderSampler.json",
"test/generated-artifacts/MStableSampler.json",

View File

@@ -1,4 +1,13 @@
[
{
"version": "6.15.0",
"changes": [
{
"note": "Redeploy FQT on Mainnet"
}
],
"timestamp": 1654284040
},
{
"version": "6.14.0",
"changes": [

View File

@@ -5,6 +5,10 @@ Edit the package's CHANGELOG.json file only.
CHANGELOG
## v6.15.0 - _June 3, 2022_
* Redeploy FQT on Mainnet
## v6.14.0 - _May 19, 2022_
* Redeploy FQT on Avalanche and BSC

View File

@@ -37,7 +37,7 @@
"wethTransformer": "0xb2bc06a4efb20fc6553a69dbfa49b7be938034a7",
"payTakerTransformer": "0x4638a7ebe75b911b995d0ec73a81e4f85f41f24e",
"affiliateFeeTransformer": "0xda6d9fc5998f550a094585cf9171f0e8ee3ac59f",
"fillQuoteTransformer": "0xadbe39f2988a8be1c1120f05e28cc888b150c8a6",
"fillQuoteTransformer": "0xa651c18efcf50409f3d0f5cdbf615d3016b828c8",
"positiveSlippageFeeTransformer": "0xa9416ce1dbde8d331210c07b5c253d94ee4cc3fd"
}
},

View File

@@ -1,6 +1,6 @@
{
"name": "@0x/contract-addresses",
"version": "6.14.0",
"version": "6.15.0",
"engines": {
"node": ">=6.12"
},

View File

@@ -1,4 +1,13 @@
[
{
"timestamp": 1654284040,
"version": "13.20.3",
"changes": [
{
"note": "Dependencies updated"
}
]
},
{
"timestamp": 1652919697,
"version": "13.20.2",

View File

@@ -5,6 +5,10 @@ Edit the package's CHANGELOG.json file only.
CHANGELOG
## v13.20.3 - _June 3, 2022_
* Dependencies updated
## v13.20.2 - _May 19, 2022_
* Dependencies updated

View File

@@ -1,6 +1,6 @@
{
"name": "@0x/contract-wrappers",
"version": "13.20.2",
"version": "13.20.3",
"engines": {
"node": ">=6.12"
},
@@ -57,7 +57,7 @@
"dependencies": {
"@0x/assert": "^3.0.34",
"@0x/base-contract": "^6.5.0",
"@0x/contract-addresses": "^6.14.0",
"@0x/contract-addresses": "^6.15.0",
"@0x/json-schemas": "^6.4.4",
"@0x/types": "^3.3.6",
"@0x/utils": "^6.5.3",

View File

@@ -1,2 +0,0 @@
*.zip
0x_ganache_snapshot

View File

@@ -1,10 +0,0 @@
# Blacklist all files
.*
*
# Whitelist lib
!lib/**/*
# Blacklist tests and publish scripts
/lib/test/*
/lib/monorepo_scripts/
# Package specific ignore
!bin/**/*

File diff suppressed because it is too large Load Diff

View File

@@ -1,582 +0,0 @@
<!--
changelogUtils.file is auto-generated using the monorepo-scripts package. Don't edit directly.
Edit the package's CHANGELOG.json file only.
-->
CHANGELOG
## v8.1.19 - _May 19, 2022_
* Dependencies updated
## v8.1.18 - _April 22, 2022_
* Dependencies updated
## v8.1.17 - _March 31, 2022_
* Dependencies updated
## v8.1.16 - _March 2, 2022_
* Dependencies updated
## v8.1.15 - _February 22, 2022_
* Dependencies updated
## v8.1.14 - _December 24, 2021_
* Dependencies updated
## v8.1.13 - _December 1, 2021_
* Dependencies updated
## v8.1.12 - _November 16, 2021_
* Dependencies updated
## v8.1.11 - _November 16, 2021_
* Dependencies updated
## v8.1.10 - _November 3, 2021_
* Add OtcOrders to fullMigrateAsync (#350)
## v8.1.9 - _October 19, 2021_
* Dependencies updated
## v8.1.8 - _October 4, 2021_
* Dependencies updated
## v8.1.7 - _September 29, 2021_
* Dependencies updated
## v8.1.6 - _September 15, 2021_
* Dependencies updated
## v8.1.5 - _September 8, 2021_
* Dependencies updated
## v8.1.4 - _September 1, 2021_
* Dependencies updated
## v8.1.3 - _August 19, 2021_
* Dependencies updated
## v8.1.2 - _August 19, 2021_
* Dependencies updated
## v8.1.1 - _August 16, 2021_
* Dependencies updated
## v8.1.0 - _August 11, 2021_
* Add zrxTreasury address (#301)
## v8.0.12 - _August 6, 2021_
* Dependencies updated
## v8.0.11 - _June 22, 2021_
* Dependencies updated
## v8.0.10 - _June 11, 2021_
* Dependencies updated
## v8.0.9 - _June 2, 2021_
* Dependencies updated
## v8.0.8 - _May 25, 2021_
* Dependencies updated
## v8.0.7 - _May 21, 2021_
* Dependencies updated
## v8.0.6 - _May 5, 2021_
* Dependencies updated
## v8.0.5 - _May 1, 2021_
* Dependencies updated
## v8.0.4 - _April 30, 2021_
* Dependencies updated
## v8.0.3 - _April 28, 2021_
* Dependencies updated
## v8.0.2 - _April 26, 2021_
* Dependencies updated
## v8.0.1 - _April 12, 2021_
* Dependencies updated
## v8.0.0 - _April 1, 2021_
* Remove exchangeProxyAllowanceTarget
## v7.0.1 - _March 17, 2021_
* Dependencies updated
## v7.0.0 - _February 24, 2021_
* Major version bump with V4 FQT
## v6.6.0 - _February 10, 2021_
* Update `BridgeAdapter` deployment (#104)
## v6.5.11 - _January 26, 2021_
* Set BOTH networkId and chainId to 1337 in dockerfile (#118)
## v6.5.10 - _January 13, 2021_
* Dependencies updated
## v6.5.9 - _January 4, 2021_
* Dependencies updated
## v6.5.8 - _December 23, 2020_
* Dependencies updated
## v6.5.7 - _December 17, 2020_
* Dependencies updated
## v6.5.6 - _December 16, 2020_
* Dependencies updated
## v6.5.5 - _December 16, 2020_
* Dependencies updated
## v6.5.4 - _December 9, 2020_
* Dependencies updated
## v6.5.3 - _December 7, 2020_
* Dependencies updated
## v6.5.2 - _December 3, 2020_
* Dependencies updated
## v6.5.1 - _November 19, 2020_
* Dependencies updated
## v6.5.0 - _November 13, 2020_
* Add `exchangeProxyLiquidityProviderSandbox` address (#16)
## v6.4.7 - _November 3, 2020_
* Dependencies updated
## v6.4.6 - _November 3, 2020_
* Dependencies updated
## v6.4.5 - _November 2, 2020_
* Dependencies updated
## v6.4.4 - _October 28, 2020_
* Dependencies updated
## v6.4.3 - _October 27, 2020_
* Dependencies updated
## v6.4.2 - _October 23, 2020_
* Dependencies updated
## v6.4.1 - _October 21, 2020_
* Change test protocol fee to 70000. (#2637)
* Refactor `migration.ts` a little (#2656)
* Add bancorBridge to addresses (#2650)
* Update EP migration. (#2657)
* Add mooniswap addresses to `BridgeAdapter` deployment (#2692)
* Reorder transformer deployments (#2693)
## v6.4.0 - _July 15, 2020_
* Add Exchange Proxy migration. (#2612)
* Add affiliate fee transformer migration and flash wallet address (#2622)
* Add BalancerBridge to returned object in `migration.ts` (#2613)
## v6.3.0 - _June 24, 2020_
* Add `dexForwarderBridge` to migration output (#2525)
* Add `ERC20BridgeSampler` deployment (#2541)
* Added `UniswapV2Bridge` address on Mainnet (#2599)
* Return empty Exchange Proxy addresses (#2591)
## v6.2.4 - _March 3, 2020_
* Dependencies updated
## v6.2.3 - _February 27, 2020_
* Dependencies updated
## v6.2.2 - _February 26, 2020_
* Dependencies updated
## v6.2.1 - _February 25, 2020_
* Dependencies updated
## v6.2.0 - _February 15, 2020_
* Added `CurveBridge` address (null) (#2483)
## v6.1.0 - _February 8, 2020_
* Update `DevUtils` deployment (#2456)
* Remove `LibTransactionDecoder` deployment (#2456)
* Use contract package artifacts in ganache migrations (#2456)
* Update deployment for new DevUtils (#2466)
## v6.0.2 - _February 6, 2020_
* Dependencies updated
## v6.0.1 - _February 4, 2020_
* Dependencies updated
## v6.0.0 - _January 22, 2020_
* Update Forwarder deployment (#2432)
## v5.1.0 - _January 6, 2020_
* Added DydxBridge Contract to ContractAddresses (#2401)
* Changed docker image command to overwrite any existing snapshot when unzipping the image downloaded from S3. (#2420)
## v5.0.2 - _December 17, 2019_
* Dependencies updated
## v5.0.1 - _December 9, 2019_
* Dependencies updated
## v5.0.0 - _December 2, 2019_
* Deploy Forwarder after Exchange is configured as Staking Proxy is queried (#2368)
* Subsequent contract addresses after the Forwarder are now modified (#2368)
* Update Exchange, DevUtils, Coordinator, and Forwarder addresses on all networks (#2349)
* Update StakingProxy, Staking, and ZrxVault addresses on mainnet (#2349)
* Add UniswapBridge and Eth2DaiBridge addresses to schema, add mainnet addresses (#2349)
* Deploy Forwarder AFTER staking is hooked up (#2350)
* Migrations script no longer deploys DutchAuction since it is not yet upgraded for V3 of the protocol (#2324)
* Added `Staking` and `ERC20BridgeProxy` contracts (#2323)
* Update all contract deployments to pass the actual chain ID (rather than the network ID) via the newly modified @0x/utils/provider_utils (#2270)
* All references to network ID have been removed, and references to chain ID have been introduced instead (#2313)
* Update Coordinator and Exchange deployments to pass `chainId` (#1742)
## v4.4.0-beta.4 - _December 2, 2019_
* Deploy Forwarder after Exchange is configured as Staking Proxy is queried (#2368)
* Subsequent contract addresses after the Forwarder are now modified (#2368)
## v4.4.0-beta.3 - _November 20, 2019_
* Update Exchange, DevUtils, Coordinator, and Forwarder addresses on all networks (#2349)
* Update StakingProxy, Staking, and ZrxVault addresses on mainnet (#2349)
* Add UniswapBridge and Eth2DaiBridge addresses to schema, add mainnet addresses (#2349)
* Deploy Forwarder AFTER staking is hooked up (#2350)
## v4.4.0-beta.2 - _November 17, 2019_
* Migrations script no longer deploys DutchAuction since it is not yet upgraded for V3 of the protocol (#2324)
* Added `Staking` and `ERC20BridgeProxy` contracts (#2323)
## v4.4.0-beta.1 - _November 7, 2019_
* Update all contract deployments to pass the actual chain ID (rather than the network ID) via the newly modified @0x/utils/provider_utils (#2270)
* All references to network ID have been removed, and references to chain ID have been introduced instead (#2313)
## v4.4.0-beta.0 - _October 3, 2019_
* Update Coordinator and Exchange deployments to pass `chainId` (#1742)
## v4.3.2 - _September 17, 2019_
* Removed dependency on @0x/order-utils (#2096)
## v4.3.1 - _September 3, 2019_
* Dependencies updated
## v4.3.0 - _August 22, 2019_
* Added DevUtils to migration script (#2060)
## v4.2.0 - _August 8, 2019_
* Added StaticCallAssetProxy and ERC1155AssetProxy (#2021)
## v4.1.11 - _July 31, 2019_
* Updated calls to <contract wrapper>.deploy0xArtifactAsync to include log decode dependencies. (#1995)
## v4.1.10 - _July 24, 2019_
* Dependencies updated
## v4.1.9 - _July 15, 2019_
* Dependencies updated
## v4.1.8 - _July 13, 2019_
* Dependencies updated
## v4.1.7 - _July 13, 2019_
* Dependencies updated
## v4.1.6 - _May 24, 2019_
* Dependencies updated
## v4.1.5 - _May 15, 2019_
* Dependencies updated
## v4.1.4 - _May 14, 2019_
* Add --pk flag to accept private key when migrating (#1811)
## v4.1.2 - _May 10, 2019_
* Dependencies updated
## v4.1.1 - _April 11, 2019_
* Dependencies updated
## v4.1.0 - _March 21, 2019_
* Add deployment of `Coordinator` and `CoordinatorRegistry` contracts to migration script (#1689)
* Added `startProviderEngine` to `providerUtils`. Preventing excess block polling (#1695)
## v4.0.4 - _March 20, 2019_
* Dependencies updated
## v4.0.3 - _March 1, 2019_
* Dependencies updated
## v4.0.2 - _February 27, 2019_
* Dependencies updated
## v4.0.1 - _February 26, 2019_
* Dependencies updated
## v4.0.0 - _February 25, 2019_
* Replace Provider param interface with Web3ProviderEngine (#1627)
## v3.0.4 - _February 9, 2019_
* Dependencies updated
## v3.0.3 - _February 7, 2019_
* Dependencies updated
## v3.0.2 - _February 7, 2019_
* Dependencies updated
## v3.0.1 - _February 6, 2019_
* Dependencies updated
## v3.0.0 - _February 5, 2019_
* Upgrade the bignumber.js to v8.0.2 (#1517)
* Removed `owner` in Migrations (#1533)
* `txDefaults` parameter now requires the `from` field (#1533)
* Convert `from` to lower case when passed in via cli (#1533)
## v2.4.0 - _January 15, 2019_
* Added migrations for `MultiAssetProxy` contract (#1503)
## v2.3.1 - _January 11, 2019_
* Dependencies updated
## v2.3.0 - _January 9, 2019_
* Added migrations for Dutch Auction contract (#1465)
## v2.2.2 - _December 13, 2018_
* Dependencies updated
## v2.2.1 - _December 11, 2018_
* Dependencies updated
## v2.2.0 - _November 28, 2018_
* Add CLI `0x-migrate` for running the 0x migrations in a language-agnostic way (#1324)
* Deploy testnet Exchange arfitact. Previously mainnet Exchange artifact was deployed. (#1309)
* Fund the Forwarder with ZRX for fees. (#1309)
## v2.1.0 - _November 21, 2018_
* Export all type declarations used by the public interface, as well as the `ContractAddresses` mapping (#1301)
## v2.0.4 - _November 14, 2018_
* Dependencies updated
## v2.0.3 - _November 13, 2018_
* Dependencies updated
## v2.0.2 - _November 12, 2018_
* Dependencies updated
## v2.0.1 - _November 9, 2018_
* Dependencies updated
## v2.0.0 - _October 18, 2018_
* Contract artifacts have been moved to the new @0xproject/contract-artifacts package. v1 migrations have been removed. `runMigrationsAsync` returns the addresses of the contracts that were deployed. (#1105)
## v1.0.14 - _October 4, 2018_
* Dependencies updated
## v1.0.13 - _September 28, 2018_
* Dependencies updated
## v1.0.12 - _September 25, 2018_
* Dependencies updated
## v1.0.11 - _September 25, 2018_
* Dependencies updated
## v1.0.10 - _September 21, 2018_
* Dependencies updated
## v1.0.9 - _September 19, 2018_
* Dependencies updated
## v1.0.8 - _September 18, 2018_
* Dependencies updated
## v1.0.7 - _September 5, 2018_
* Dependencies updated
## v1.0.6 - _August 27, 2018_
* Dependencies updated
## v1.0.5 - _August 24, 2018_
* Dependencies updated
## v1.0.4 - _August 14, 2018_
* Dependencies updated
## v1.0.3 - _July 26, 2018_
* Dependencies updated
## v1.0.2 - _July 26, 2018_
* Dependencies updated
## v1.0.1 - _July 23, 2018_
* Dependencies updated
## v1.0.0 - _July 19, 2018_
* Added migrations for 0x Protocol v2
## v0.0.10 - _July 18, 2018_
* Dependencies updated
## v0.0.9 - _July 9, 2018_
* Dependencies updated
## v0.0.8 - _June 19, 2018_
* Dependencies updated
## v0.0.7 - _May 22, 2018_
* Use AssetProxyOwner instead of MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress (#675)
## v0.0.6 - _May 22, 2018_
* Dependencies updated
## v0.0.5 - _May 4, 2018_
* Dependencies updated
## v0.0.4 - _May 4, 2018_
* Dependencies updated
## v0.0.3 - _April 18, 2018_
* Dependencies updated

View File

@@ -1,15 +0,0 @@
FROM mhart/alpine-node:12
WORKDIR /usr/src/app
RUN npm install -g ganache-cli@6.12.1
ENV MNEMONIC "concert load couple harbor equip island argue ramp clarify fence smart topic"
ENV NETWORK_ID 1337
ENV CHAIN_ID 1337
ENV VERSION "latest"
ENV SNAPSHOT_HOST "http://ganache-snapshots.0x.org.s3-website.us-east-2.amazonaws.com"
ENV SNAPSHOT_NAME "0x_ganache_snapshot"
EXPOSE 8545
CMD [ "sh", "-c", "echo downloading snapshot version: $VERSION; wget $SNAPSHOT_HOST/$SNAPSHOT_NAME-$VERSION.zip -O snapshot.zip && unzip -o snapshot.zip && ganache-cli --gasLimit 12000000 --allowUnlimitedContractSize=true --db $SNAPSHOT_NAME --noVMErrorsOnRPCResponse -p 8545 --keepAliveTimeout=40000 --networkId \"$NETWORK_ID\" --chainId \"$CHAIN_ID\" -m \"$MNEMONIC\" -h 0.0.0.0"]

View File

@@ -1,104 +0,0 @@
## Migrations
Migrate the 0x system of smart contracts on the network of your choice using these migrations.
## Contributing
We welcome improvements and fixes from the wider community! To report bugs within this package, please create an issue in this repository.
Please read our [contribution guidelines](../../CONTRIBUTING.md) before getting started.
### Install dependencies
If you don't have yarn workspaces enabled (Yarn < v1.0) - enable them:
```bash
yarn config set workspaces-experimental true
```
Then install dependencies
```bash
yarn install
```
### Build
To build this package and all other monorepo packages that it depends on, run the following from the monorepo root directory:
```bash
PKG=@0x/migrations yarn build
```
Or continuously rebuild on change:
```bash
PKG=@0x/migrations yarn watch
```
### Clean
```bash
yarn clean
```
### Lint
```bash
yarn lint
```
### Migrate
#### V2 smart contracts
In order to migrate the V2 0x smart contracts to TestRPC/Ganache running at `http://localhost:8545`, run:
```bash
yarn migrate:v2
```
### Publish
#### 0x Ganache Snapshot
The 0x Ganache snapshot can be generated and published in this package. In order to build the snapshot for this version of migrations run:
```bash
yarn build:snapshot
```
This will run the migrations in Ganache and output a zip file to be uploaded to the s3 bucket. For example, after running this command you will have created `0x_ganache_snapshot-2.2.2.zip`. To publish the zip file to the s3 bucket run:
```bash
yarn publish:snapshot
```
This snapshot will now be publicly available at http://ganache-snapshots.0x.org.s3.amazonaws.com/0x_ganache_snapshot-latest.zip and also versioned with the package.json version.
#### 0x Ganache Docker Image
We also publish a simple docker image which downloads the latest snapshot, extracts and runs Ganache. This is not required to be built when migrations change as it always downloads and runs the latest zip file. If you have made changes to the Dockerfile then a publish of the image is required. To do this run:
```bash
yarn build:snapshot:docker
yarn publish:snapshot:docker
```
The result is a published docker image to the 0xorg docker registry. To start the docker image run:
```bash
docker run -p 8545:8545 -ti 0xorg/ganache-cli:latest
```
This will pull the latest zip in the s3 bucket, extract and start Ganache with the snapshot.
In the event you need a specific version of the published Ganache snapshot run the following specifying the VERSION environment variable:
```bash
docker run -e VERSION=2.2.2 -p 8545:8545 -ti 0xorg/ganache-cli:latest
```
#### Production
If deploying contract changes to mainnet, `@0x/contract-artifacts` should also be updated and published. The artifacts must be copied from each `contracts/{package-name}/generated-artifacts/{contract}.json`.

View File

@@ -1,2 +0,0 @@
#!/usr/bin/env node
require('../lib/src/cli.js');

View File

@@ -1,920 +0,0 @@
# Interface: GanacheProvider
## Methods
### sendAsync
▸ **sendAsync**(`payload`: [JSONRPCRequestPayload](_ethereum_types_src_index_.jsonrpcrequestpayload.md), `callback`: [JSONRPCErrorCallback](#jsonrpcerrorcallback)): *void*
*Defined in [ethereum-types/src/index.ts:14](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L14)*
**Parameters:**
Name | Type |
------ | ------ |
`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) |
`callback` | [JSONRPCErrorCallback](#jsonrpcerrorcallback) |
**Returns:** *void*
<hr />
# Interface: ContractAddresses
## Properties
### assetProxyOwner
• **assetProxyOwner**: *string*
*Defined in [contract-addresses/src/index.ts:12](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/contract-addresses/src/index.ts#L12)*
___
### coordinator
• **coordinator**: *string*
*Defined in [contract-addresses/src/index.ts:18](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/contract-addresses/src/index.ts#L18)*
___
### coordinatorRegistry
• **coordinatorRegistry**: *string*
*Defined in [contract-addresses/src/index.ts:17](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/contract-addresses/src/index.ts#L17)*
___
### devUtils
• **devUtils**: *string*
*Defined in [contract-addresses/src/index.ts:22](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/contract-addresses/src/index.ts#L22)*
___
### dutchAuction
• **dutchAuction**: *string*
*Defined in [contract-addresses/src/index.ts:16](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/contract-addresses/src/index.ts#L16)*
___
### erc1155Proxy
• **erc1155Proxy**: *string*
*Defined in [contract-addresses/src/index.ts:21](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/contract-addresses/src/index.ts#L21)*
___
### erc20BridgeProxy
• **erc20BridgeProxy**: *string*
*Defined in [contract-addresses/src/index.ts:26](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/contract-addresses/src/index.ts#L26)*
___
### erc20Proxy
• **erc20Proxy**: *string*
*Defined in [contract-addresses/src/index.ts:6](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/contract-addresses/src/index.ts#L6)*
___
### erc721Proxy
• **erc721Proxy**: *string*
*Defined in [contract-addresses/src/index.ts:7](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/contract-addresses/src/index.ts#L7)*
___
### etherToken
• **etherToken**: *string*
*Defined in [contract-addresses/src/index.ts:9](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/contract-addresses/src/index.ts#L9)*
___
### exchange
• **exchange**: *string*
*Defined in [contract-addresses/src/index.ts:11](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/contract-addresses/src/index.ts#L11)*
___
### exchangeV2
• **exchangeV2**: *string*
*Defined in [contract-addresses/src/index.ts:10](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/contract-addresses/src/index.ts#L10)*
___
### forwarder
• **forwarder**: *string*
*Defined in [contract-addresses/src/index.ts:14](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/contract-addresses/src/index.ts#L14)*
___
### multiAssetProxy
• **multiAssetProxy**: *string*
*Defined in [contract-addresses/src/index.ts:19](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/contract-addresses/src/index.ts#L19)*
___
### orderValidator
• **orderValidator**: *string*
*Defined in [contract-addresses/src/index.ts:15](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/contract-addresses/src/index.ts#L15)*
___
### staking
• **staking**: *string*
*Defined in [contract-addresses/src/index.ts:24](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/contract-addresses/src/index.ts#L24)*
___
### stakingProxy
• **stakingProxy**: *string*
*Defined in [contract-addresses/src/index.ts:25](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/contract-addresses/src/index.ts#L25)*
___
### staticCallProxy
• **staticCallProxy**: *string*
*Defined in [contract-addresses/src/index.ts:20](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/contract-addresses/src/index.ts#L20)*
___
### zeroExGovernor
• **zeroExGovernor**: *string*
*Defined in [contract-addresses/src/index.ts:13](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/contract-addresses/src/index.ts#L13)*
___
### zrxToken
• **zrxToken**: *string*
*Defined in [contract-addresses/src/index.ts:8](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/contract-addresses/src/index.ts#L8)*
___
### zrxVault
• **zrxVault**: *string*
*Defined in [contract-addresses/src/index.ts:23](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/contract-addresses/src/index.ts#L23)*
<hr />
# Interface: EIP1193Provider
## Properties
### isEIP1193
• **isEIP1193**: *boolean*
*Defined in [ethereum-types/src/index.ts:73](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L73)*
## Methods
### on
▸ **on**(`event`: [EIP1193Event](#eip1193event), `listener`: function): *this*
*Defined in [ethereum-types/src/index.ts:75](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L75)*
**Parameters:**
▪ **event**: *[EIP1193Event](#eip1193event)*
▪ **listener**: *function*
▸ (`result`: any): *void*
**Parameters:**
Name | Type |
------ | ------ |
`result` | any |
**Returns:** *this*
___
### send
▸ **send**(`method`: string, `params?`: any[]): *`Promise<any>`*
*Defined in [ethereum-types/src/index.ts:74](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L74)*
**Parameters:**
Name | Type |
------ | ------ |
`method` | string |
`params?` | any[] |
**Returns:** *`Promise<any>`*
<hr />
# Interface: JSONRPCRequestPayload
## Properties
### id
• **id**: *number*
*Defined in [ethereum-types/src/index.ts:331](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L331)*
___
### jsonrpc
• **jsonrpc**: *string*
*Defined in [ethereum-types/src/index.ts:332](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L332)*
___
### method
• **method**: *string*
*Defined in [ethereum-types/src/index.ts:330](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L330)*
___
### params
• **params**: *any[]*
*Defined in [ethereum-types/src/index.ts:329](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L329)*
<hr />
# Interface: JSONRPCResponseError
## Properties
### code
• **code**: *number*
*Defined in [ethereum-types/src/index.ts:337](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L337)*
___
### message
• **message**: *string*
*Defined in [ethereum-types/src/index.ts:336](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L336)*
<hr />
# Interface: JSONRPCResponsePayload
## Properties
### `Optional` error
• **error**? : *[JSONRPCResponseError](#class-jsonrpcresponseerror)*
*Defined in [ethereum-types/src/index.ts:344](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L344)*
___
### id
• **id**: *number*
*Defined in [ethereum-types/src/index.ts:342](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L342)*
___
### jsonrpc
• **jsonrpc**: *string*
*Defined in [ethereum-types/src/index.ts:343](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L343)*
___
### result
• **result**: *any*
*Defined in [ethereum-types/src/index.ts:341](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L341)*
<hr />
# Interface: TxData
## Properties
### `Optional` data
• **data**? : *undefined | string*
*Inherited from [CallTxDataBase](#interface-calltxdatabase).[data](#optional-data)*
*Defined in [ethereum-types/src/index.ts:394](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L394)*
___
### from
• **from**: *string*
*Defined in [ethereum-types/src/index.ts:399](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L399)*
___
### `Optional` gas
• **gas**? : *number | string | `BigNumber`*
*Inherited from [CallTxDataBase](#interface-calltxdatabase).[gas](#optional-gas)*
*Defined in [ethereum-types/src/index.ts:392](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L392)*
___
### `Optional` gasPrice
• **gasPrice**? : *number | string | `BigNumber`*
*Inherited from [CallTxDataBase](#interface-calltxdatabase).[gasPrice](#optional-gasprice)*
*Defined in [ethereum-types/src/index.ts:393](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L393)*
___
### `Optional` nonce
• **nonce**? : *undefined | number*
*Inherited from [CallTxDataBase](#interface-calltxdatabase).[nonce](#optional-nonce)*
*Defined in [ethereum-types/src/index.ts:395](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L395)*
___
### `Optional` to
• **to**? : *undefined | string*
*Inherited from [CallTxDataBase](#interface-calltxdatabase).[to](#optional-to)*
*Defined in [ethereum-types/src/index.ts:390](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L390)*
___
### `Optional` value
• **value**? : *number | string | `BigNumber`*
*Inherited from [CallTxDataBase](#interface-calltxdatabase).[value](#optional-value)*
*Defined in [ethereum-types/src/index.ts:391](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L391)*
<hr />
# Interface: TxDataPayable
## Properties
### `Optional` data
• **data**? : *undefined | string*
*Inherited from [CallTxDataBase](#interface-calltxdatabase).[data](#optional-data)*
*Defined in [ethereum-types/src/index.ts:394](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L394)*
___
### from
• **from**: *string*
*Inherited from [TxData](#interface-txdata).[from](#from)*
*Defined in [ethereum-types/src/index.ts:399](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L399)*
___
### `Optional` gas
• **gas**? : *number | string | `BigNumber`*
*Inherited from [CallTxDataBase](#interface-calltxdatabase).[gas](#optional-gas)*
*Defined in [ethereum-types/src/index.ts:392](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L392)*
___
### `Optional` gasPrice
• **gasPrice**? : *number | string | `BigNumber`*
*Inherited from [CallTxDataBase](#interface-calltxdatabase).[gasPrice](#optional-gasprice)*
*Defined in [ethereum-types/src/index.ts:393](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L393)*
___
### `Optional` nonce
• **nonce**? : *undefined | number*
*Inherited from [CallTxDataBase](#interface-calltxdatabase).[nonce](#optional-nonce)*
*Defined in [ethereum-types/src/index.ts:395](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L395)*
___
### `Optional` to
• **to**? : *undefined | string*
*Inherited from [CallTxDataBase](#interface-calltxdatabase).[to](#optional-to)*
*Defined in [ethereum-types/src/index.ts:390](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L390)*
___
### `Optional` value
• **value**? : *`BigNumber`*
*Overrides [CallTxDataBase](_ethereum_types_src_index_.calltxdatabase.md).[value](#optional-value)*
*Defined in [ethereum-types/src/index.ts:443](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L443)*
<hr />
# Interface: Web3JsV1Provider
Web3.js version 1 provider interface
This provider interface was implemented in the pre-1.0Beta releases for Web3.js.
This interface allowed sending synchonous requests, support for which was later dropped.
## Methods
### send
▸ **send**(`payload`: [JSONRPCRequestPayload](_ethereum_types_src_index_.jsonrpcrequestpayload.md)): *[JSONRPCResponsePayload](#class-jsonrpcresponsepayload)*
*Defined in [ethereum-types/src/index.ts:45](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L45)*
**Parameters:**
Name | Type |
------ | ------ |
`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) |
**Returns:** *[JSONRPCResponsePayload](#class-jsonrpcresponsepayload)*
___
### sendAsync
▸ **sendAsync**(`payload`: [JSONRPCRequestPayload](_ethereum_types_src_index_.jsonrpcrequestpayload.md), `callback`: [JSONRPCErrorCallback](#jsonrpcerrorcallback)): *void*
*Defined in [ethereum-types/src/index.ts:44](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L44)*
**Parameters:**
Name | Type |
------ | ------ |
`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) |
`callback` | [JSONRPCErrorCallback](#jsonrpcerrorcallback) |
**Returns:** *void*
<hr />
# Interface: Web3JsV2Provider
Web3.js version 2 provider interface
This provider interface was used in a couple of Web3.js 1.0 beta releases
before the first attempts to conform to EIP1193
## Methods
### send
▸ **send**(`payload`: [JSONRPCRequestPayload](_ethereum_types_src_index_.jsonrpcrequestpayload.md), `callback`: [JSONRPCErrorCallback](#jsonrpcerrorcallback)): *void*
*Defined in [ethereum-types/src/index.ts:54](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L54)*
**Parameters:**
Name | Type |
------ | ------ |
`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) |
`callback` | [JSONRPCErrorCallback](#jsonrpcerrorcallback) |
**Returns:** *void*
<hr />
# Interface: Web3JsV3Provider
Web3.js version 3 provider interface
This provider interface was implemented with the hopes for conforming to the EIP1193 spec,
however it does not conform entirely.
## Methods
### send
▸ **send**(`method`: string, `params?`: any[]): *`Promise<any>`*
*Defined in [ethereum-types/src/index.ts:63](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L63)*
**Parameters:**
Name | Type |
------ | ------ |
`method` | string |
`params?` | any[] |
**Returns:** *`Promise<any>`*
<hr />
# Interface: ZeroExProvider
The interface for the provider used internally by 0x libraries
Any property we use from any SupportedProvider should we explicitly
add here
## Properties
### `Optional` isMetaMask
• **isMetaMask**? : *undefined | false | true*
*Defined in [ethereum-types/src/index.ts:31](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L31)*
___
### `Optional` isParity
• **isParity**? : *undefined | false | true*
*Defined in [ethereum-types/src/index.ts:32](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L32)*
___
### `Optional` isZeroExProvider
• **isZeroExProvider**? : *undefined | false | true*
*Defined in [ethereum-types/src/index.ts:30](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L30)*
## Methods
### `Optional` enable
▸ **enable**(): *`Promise<void>`*
*Defined in [ethereum-types/src/index.ts:34](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L34)*
**Returns:** *`Promise<void>`*
___
### sendAsync
▸ **sendAsync**(`payload`: [JSONRPCRequestPayload](_ethereum_types_src_index_.jsonrpcrequestpayload.md), `callback`: [JSONRPCErrorCallback](#jsonrpcerrorcallback)): *void*
*Defined in [ethereum-types/src/index.ts:35](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L35)*
**Parameters:**
Name | Type |
------ | ------ |
`payload` | [JSONRPCRequestPayload](#class-jsonrpcrequestpayload) |
`callback` | [JSONRPCErrorCallback](#jsonrpcerrorcallback) |
**Returns:** *void*
___
### `Optional` stop
▸ **stop**(): *void*
*Defined in [ethereum-types/src/index.ts:33](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L33)*
**Returns:** *void*
<hr />
## Functions
### runMigrationsAsync
▸ **runMigrationsAsync**(`supportedProvider`: [SupportedProvider](#supportedprovider), `txDefaults`: `TxData`): *`Promise<ContractAddresses>`*
*Defined in [migrations/src/migration.ts:63](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/migrations/src/migration.ts#L63)*
Creates and deploys all the contracts that are required for the latest
version of the 0x protocol.
**Parameters:**
Name | Type | Description |
------ | ------ | ------ |
`supportedProvider` | [SupportedProvider](#supportedprovider) | Web3 provider instance. Your provider instance should connect to the testnet you want to deploy to. |
`txDefaults` | `TxData` | Default transaction values to use when deploying contracts (e.g., specify the desired contract creator with the `from` parameter). |
**Returns:** *`Promise<ContractAddresses>`*
The addresses of the contracts that were deployed.
___
### runMigrationsOnceAsync
▸ **runMigrationsOnceAsync**(`provider`: `Web3ProviderEngine`, `txDefaults`: `TxData`): *`Promise<ContractAddresses>`*
*Defined in [migrations/src/migration.ts:321](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/migrations/src/migration.ts#L321)*
Exactly like runMigrationsAsync but will only run the migrations the first
time it is called. Any subsequent calls will return the cached contract
addresses.
**Parameters:**
Name | Type | Description |
------ | ------ | ------ |
`provider` | `Web3ProviderEngine` | Web3 provider instance. Your provider instance should connect to the testnet you want to deploy to. |
`txDefaults` | `TxData` | Default transaction values to use when deploying contracts (e.g., specify the desired contract creator with the `from` parameter). |
**Returns:** *`Promise<ContractAddresses>`*
The addresses of the contracts that were deployed.
<hr />
## Functions
### getContractAddressesForChainOrThrow
▸ **getContractAddressesForChainOrThrow**(`chainId`: [ChainId](#enumeration-chainid)): *[ContractAddresses](#interface-contractaddresses)*
*Defined in [contract-addresses/src/index.ts:45](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/contract-addresses/src/index.ts#L45)*
Used to get addresses of contracts that have been deployed to either the
Ethereum mainnet or a supported testnet. Throws if there are no known
contracts deployed on the corresponding chain.
**Parameters:**
Name | Type | Description |
------ | ------ | ------ |
`chainId` | [ChainId](#enumeration-chainid) | The desired chainId. |
**Returns:** *[ContractAddresses](#interface-contractaddresses)*
The set of addresses for contracts which have been deployed on the
given chainId.
<hr />
## Type aliases
### EIP1193Event
Ƭ **EIP1193Event**: *"accountsChanged" | "networkChanged" | "close" | "connect" | "notification"*
*Defined in [ethereum-types/src/index.ts:70](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L70)*
Interface for providers that conform to EIP 1193
Source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md
___
### JSONRPCErrorCallback
Ƭ **JSONRPCErrorCallback**: *function*
*Defined in [ethereum-types/src/index.ts:3](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L3)*
#### Type declaration:
▸ (`err`: `Error` | null, `result?`: [JSONRPCResponsePayload](#interface-jsonrpcresponsepayload)): *void*
**Parameters:**
Name | Type |
------ | ------ |
`err` | `Error` \| null |
`result?` | [JSONRPCResponsePayload](#interface-jsonrpcresponsepayload) |
___
### SupportedProvider
Ƭ **SupportedProvider**: *[Web3JsProvider](_ethereum_types_src_index_.md#web3jsprovider) | [GanacheProvider](#interface-ganacheprovider) | [EIP1193Provider](#interface-eip1193provider) | [ZeroExProvider](#interface-zeroexprovider)*
*Defined in [ethereum-types/src/index.ts:9](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L9)*
Do not create your own provider. Use an existing provider from a Web3 or ProviderEngine library
Read more about Providers in the guides section of the 0x docs.
___
### Web3JsProvider
Ƭ **Web3JsProvider**: *[Web3JsV1Provider](#interface-web3jsv1provider) | [Web3JsV2Provider](#interface-web3jsv2provider) | [Web3JsV3Provider](#interface-web3jsv3provider)*
*Defined in [ethereum-types/src/index.ts:11](https://github.com/0xProject/0x-monorepo/blob/34538f2ce/packages/ethereum-types/src/index.ts#L11)*
<hr />

View File

@@ -1,104 +0,0 @@
{
"name": "@0x/migrations",
"version": "8.1.19",
"engines": {
"node": ">=6.12"
},
"description": "0x smart contract migrations",
"main": "lib/src/index.js",
"types": "lib/src/index.d.ts",
"scripts": {
"build": "tsc -b",
"build:ci": "yarn build",
"clean": "shx rm -rf lib ${npm_package_config_snapshot_name} ${npm_package_config_snapshot_name}-*.zip",
"prettier": "prettier --check 'src/**/*.{ts,tsx,json}' --config ../../.prettierrc",
"lint": "tslint --format stylish --project . && yarn prettier",
"fix": "tslint --fix --format stylish --project .",
"test": "yarn run_mocha",
"test:circleci": "yarn test",
"run_mocha": "mocha --require source-map-support/register --require make-promises-safe lib/test/**/*_test.js --bail --timeout 30000 --exit",
"migrate:v2": "run-s build script:migrate:v2",
"migrate:v2:snapshot": "run-s build script:migrate:v2:snapshot",
"script:migrate:v2": "node ./lib/src/migrate.js",
"script:migrate:v2:snapshot": "node ./lib/src/migrate_snapshot.js",
"diff_docs": "git diff --exit-code ./docs",
"s3:sync_md_docs": "aws s3 sync ./docs s3://docs-markdown/${npm_package_name}/v${npm_package_version} --profile 0xproject --region us-east-1 --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers",
"docs:md": "ts-doc-gen --sourceDir='$PROJECT_FILES' --output=$MD_FILE_DIR --fileExtension=mdx --tsconfig=./typedoc-tsconfig.json",
"docs:json": "typedoc --excludePrivate --excludeExternals --excludeProtected --ignoreCompilerErrors --target ES5 --tsconfig typedoc-tsconfig.json --json $JSON_FILE_PATH $PROJECT_FILES",
"build:snapshot": "rm -rf ${npm_package_config_snapshot_name} && yarn migrate:v2:snapshot && zip -r \"${npm_package_config_snapshot_name}-${npm_package_version}.zip\" ${npm_package_config_snapshot_name}",
"build:snapshot:docker": "docker build --tag ${npm_package_config_docker_snapshot_name}:${npm_package_version} --tag ${npm_package_config_docker_snapshot_name}:latest .",
"publish:snapshot": "aws s3 cp ${npm_package_config_snapshot_name}-${npm_package_version}.zip ${npm_package_config_s3_snapshot_bucket} && aws s3 cp ${npm_package_config_s3_snapshot_bucket}/${npm_package_config_snapshot_name}-${npm_package_version}.zip ${npm_package_config_s3_snapshot_bucket}/${npm_package_config_snapshot_name}-latest.zip",
"publish:snapshot:docker": "docker push ${npm_package_config_docker_snapshot_name}:latest && docker push ${npm_package_config_docker_snapshot_name}:${npm_package_version}",
"test_contract_configs": "node ./lib/test_contract_configs.js",
"publish:private": "yarn build && gitpkg publish"
},
"config": {
"s3_snapshot_bucket": "s3://ganache-snapshots.0x.org",
"docker_snapshot_name": "0xorg/ganache-cli",
"snapshot_name": "0x_ganache_snapshot",
"postpublish": {
"assets": []
}
},
"bin": {
"0x-migrate": "bin/0x-migrate.js"
},
"license": "Apache-2.0",
"gitpkg": {
"registry": "git@github.com:0xProject/gitpkg-registry.git"
},
"devDependencies": {
"@0x/dev-utils": "^4.2.14",
"@0x/ts-doc-gen": "^0.0.28",
"@0x/tslint-config": "^4.1.4",
"@0x/types": "^3.3.6",
"@types/yargs": "^11.0.0",
"chai": "^4.0.1",
"dirty-chai": "^2.0.1",
"gitpkg": "https://github.com/0xProject/gitpkg.git",
"make-promises-safe": "^1.1.0",
"mocha": "^6.2.0",
"npm-run-all": "^4.1.2",
"shx": "^0.2.2",
"tslint": "5.11.0",
"typedoc": "~0.16.11",
"typescript": "4.6.3",
"web3-provider-engine": "14.0.6",
"yargs": "^10.0.3"
},
"dependencies": {
"@0x/base-contract": "^6.5.0",
"@0x/contract-addresses": "^6.14.0",
"@0x/contracts-asset-proxy": "^3.7.19",
"@0x/contracts-coordinator": "^3.1.38",
"@0x/contracts-dev-utils": "^1.3.36",
"@0x/contracts-erc1155": "^2.1.37",
"@0x/contracts-erc20": "^3.3.30",
"@0x/contracts-erc721": "^3.1.37",
"@0x/contracts-exchange": "^3.2.38",
"@0x/contracts-exchange-forwarder": "^4.2.38",
"@0x/contracts-extensions": "^6.2.32",
"@0x/contracts-multisig": "^4.1.38",
"@0x/contracts-staking": "^2.0.45",
"@0x/contracts-utils": "^4.8.11",
"@0x/contracts-zero-ex": "^0.33.0",
"@0x/sol-compiler": "^4.8.1",
"@0x/subproviders": "^6.6.5",
"@0x/typescript-typings": "^5.3.1",
"@0x/utils": "^6.5.3",
"@0x/web3-wrapper": "^7.6.5",
"@ledgerhq/hw-app-eth": "^4.3.0",
"@types/web3-provider-engine": "^14.0.0",
"ethereum-types": "^3.7.0",
"ethereumjs-util": "^7.1.0",
"ethers": "~4.0.4",
"lodash": "^4.17.11"
},
"optionalDependencies": {
"@ledgerhq/hw-transport-node-hid": "^4.3.0"
},
"publishConfig": {
"access": "public"
},
"gitHead": "4f91bfd907996b2f4dd383778b50c479c2602b56"
}

View File

@@ -1,49 +0,0 @@
#!/usr/bin/env node
import { PrivateKeyWalletSubprovider, RPCSubprovider, Web3ProviderEngine } from '@0x/subproviders';
import { logUtils, providerUtils } from '@0x/utils';
import * as yargs from 'yargs';
import { runMigrationsAsync } from './migration';
const args = yargs
.option('rpc-url', {
describe: 'Endpoint where backing Ethereum JSON RPC interface is available',
type: 'string',
demandOption: false,
default: 'http://localhost:8545',
})
.option('from', {
describe: 'Ethereum address from which to deploy the contracts',
type: 'string',
demandOption: true,
})
.option('pk', {
describe: 'Private key for the `from` address',
type: 'string',
})
.example(
'$0 --rpc-url http://localhost:8545 --from 0x5409ed021d9299bf6814279a6a1411a7e866a631 --pk 0xf2f48ee19680706196e2e339e5da3491186e0c4c5030670656b0e0164837257d',
'Full usage example',
).argv;
(async () => {
const rpcSubprovider = new RPCSubprovider(args['rpc-url']);
const provider = new Web3ProviderEngine();
if (args.pk !== undefined && args.pk !== '') {
const pkSubprovider = new PrivateKeyWalletSubprovider(args.pk as string);
provider.addProvider(pkSubprovider);
}
provider.addProvider(rpcSubprovider);
providerUtils.startProviderEngine(provider);
const normalizedFromAddress = (args.from as string).toLowerCase();
const txDefaults = {
from: normalizedFromAddress,
};
await runMigrationsAsync(provider, txDefaults);
process.exit(0);
})().catch(err => {
logUtils.log(err);
process.exit(1);
});

View File

@@ -1,21 +0,0 @@
export {
TxData,
TxDataPayable,
SupportedProvider,
Web3JsProvider,
GanacheProvider,
EIP1193Provider,
ZeroExProvider,
EIP1193Event,
JSONRPCErrorCallback,
Web3JsV1Provider,
Web3JsV2Provider,
Web3JsV3Provider,
JSONRPCRequestPayload,
JSONRPCResponsePayload,
JSONRPCResponseError,
} from 'ethereum-types';
export { ContractAddresses } from '@0x/contract-addresses';
export { runMigrationsAsync, runMigrationsOnceAsync } from './migration';
export { migrateOnceAsync } from './migrate_with_test_defaults';
export import Web3ProviderEngine = require('web3-provider-engine');

View File

@@ -1,23 +0,0 @@
#!/usr/bin/env node
import { devConstants, web3Factory } from '@0x/dev-utils';
import { Web3ProviderEngine } from '@0x/subproviders';
import { logUtils } from '@0x/utils';
import { runMigrationsAsync } from './migration';
(async () => {
let providerConfigs;
let provider: Web3ProviderEngine;
let txDefaults;
providerConfigs = { shouldUseInProcessGanache: false };
provider = web3Factory.getRpcProvider(providerConfigs);
txDefaults = {
from: devConstants.TESTRPC_FIRST_ADDRESS,
};
await runMigrationsAsync(provider, txDefaults);
process.exit(0);
})().catch(err => {
logUtils.log(err);
process.exit(1);
});

View File

@@ -1,32 +0,0 @@
#!/usr/bin/env node
import { devConstants, web3Factory } from '@0x/dev-utils';
import { Web3ProviderEngine } from '@0x/subproviders';
import { logUtils } from '@0x/utils';
import * as fs from 'fs';
import * as _ from 'lodash';
import * as path from 'path';
import { runMigrationsAsync } from './migration';
(async () => {
let providerConfigs;
let provider: Web3ProviderEngine;
let txDefaults;
const packageJsonPath = path.join(__dirname, '../..', 'package.json');
const packageJsonString = fs.readFileSync(packageJsonPath, 'utf8');
const packageJson = JSON.parse(packageJsonString);
if (packageJson.config === undefined || packageJson.config.snapshot_name === undefined) {
throw new Error(`Did not find 'snapshot_name' key in package.json config`);
}
providerConfigs = { shouldUseInProcessGanache: true, ganacheDatabasePath: packageJson.config.snapshot_name };
provider = web3Factory.getRpcProvider(providerConfigs);
txDefaults = {
from: devConstants.TESTRPC_FIRST_ADDRESS,
};
await runMigrationsAsync(provider, txDefaults);
process.exit(0);
})().catch(err => {
logUtils.log(err);
process.exit(1);
});

View File

@@ -1,18 +0,0 @@
import { ContractAddresses } from '@0x/contract-addresses';
import { devConstants } from '@0x/dev-utils';
import { Web3ProviderEngine } from '@0x/subproviders';
import { runMigrationsOnceAsync } from './index';
/**
* Configures and runs the migrations exactly once. Any subsequent times this is
* called, it returns the cached addresses.
* @returns The addresses of contracts that were deployed during the migrations.
*/
export async function migrateOnceAsync(provider: Web3ProviderEngine): Promise<ContractAddresses> {
const txDefaults = {
gas: devConstants.GAS_LIMIT,
from: devConstants.TESTRPC_FIRST_ADDRESS,
};
return runMigrationsOnceAsync(provider, txDefaults);
}

View File

@@ -1,351 +0,0 @@
import { ChainId, ContractAddresses, getContractAddressesForChainOrThrow } from '@0x/contract-addresses';
import { artifacts as assetProxyArtifacts, ERC20ProxyContract } from '@0x/contracts-asset-proxy';
import { artifacts as erc20Artifacts, DummyERC20TokenContract, WETH9Contract } from '@0x/contracts-erc20';
import {
artifacts as stakingArtifacts,
StakingProxyContract,
TestStakingContract,
ZrxVaultContract,
} from '@0x/contracts-staking';
import {
AffiliateFeeTransformerContract,
artifacts as exchangeProxyArtifacts,
BridgeAdapterContract,
FillQuoteTransformerContract,
fullMigrateAsync as fullMigrateExchangeProxyAsync,
PayTakerTransformerContract,
PositiveSlippageFeeTransformerContract,
WethTransformerContract,
} from '@0x/contracts-zero-ex';
import { Web3ProviderEngine } from '@0x/subproviders';
import { BigNumber, providerUtils } from '@0x/utils';
import { Web3Wrapper } from '@0x/web3-wrapper';
import { SupportedProvider, TxData } from 'ethereum-types';
import { bufferToHex, rlphash } from 'ethereumjs-util';
import { constants } from './utils/constants';
import { erc20TokenInfo } from './utils/token_info';
const allArtifacts = {
...assetProxyArtifacts,
...stakingArtifacts,
...exchangeProxyArtifacts,
...assetProxyArtifacts,
};
const { NULL_ADDRESS } = constants;
// tslint:disable:custom-no-magic-numbers
function getDeploymentNonce(deployer: string, address: string): number {
for (let i = 0; i < 10000; i++) {
const candidate = bufferToHex(rlphash([deployer, i]).slice(12));
if (candidate.toLowerCase() === address.toLowerCase()) {
return i;
}
}
throw new Error(`Exhausted all attempts to find ${address} deployed by ${deployer}`);
}
async function deployAtAddressAsync<T>(
cb: () => Promise<T>,
provider: SupportedProvider,
txDefaults: TxData,
wantedAddress: string,
): Promise<T> {
await untilWantedAddressAsync(wantedAddress, provider, txDefaults);
return cb();
}
/**
* Increases addresses nonce until the deployment of a contract would occur at the wanted address.
*/
async function untilWantedAddressAsync(
wantedAddress: string,
provider: SupportedProvider,
txDefaults: TxData,
offset: number = 0,
): Promise<void> {
const web3Wrapper = new Web3Wrapper(provider);
const from = txDefaults.from;
const currentNonce = await web3Wrapper.getAccountNonceAsync(from);
const wantedNonce = getDeploymentNonce(from, wantedAddress);
if (currentNonce > wantedNonce) {
throw new Error(`Current nonce is ${currentNonce} but wanted nonce is ${wantedNonce}`);
}
for (let i = 0; i < wantedNonce - currentNonce + offset; i++) {
await web3Wrapper.sendTransactionAsync({ from, to: from, value: new BigNumber(0) });
}
}
/**
* Creates and deploys all the contracts that are required for the latest
* version of the 0x protocol.
* @param supportedProvider Web3 provider instance. Your provider instance should connect to the testnet you want to deploy to.
* @param txDefaults Default transaction values to use when deploying contracts (e.g., specify the desired contract creator with the `from` parameter).
* @returns The addresses of the contracts that were deployed.
*/
export async function runMigrationsAsync(
supportedProvider: SupportedProvider,
txDefaults: TxData,
): Promise<ContractAddresses> {
const provider = providerUtils.standardizeOrThrow(supportedProvider);
const expectedAddresses = getContractAddressesForChainOrThrow(ChainId.Ganache);
const erc20Proxy = await deployAtAddressAsync(
() =>
ERC20ProxyContract.deployFrom0xArtifactAsync(
assetProxyArtifacts.ERC20Proxy,
provider,
txDefaults,
allArtifacts,
),
provider,
txDefaults,
expectedAddresses.erc20Proxy,
);
// ZRX
const zrxToken = await deployAtAddressAsync(
() =>
DummyERC20TokenContract.deployFrom0xArtifactAsync(
erc20Artifacts.DummyERC20Token,
provider,
txDefaults,
allArtifacts,
'0x Protocol Token',
'ZRX',
new BigNumber(18),
new BigNumber(1000000000000000000000000000),
),
provider,
txDefaults,
expectedAddresses.zrxToken,
);
// Ether token
const etherToken = await deployAtAddressAsync(
() => WETH9Contract.deployFrom0xArtifactAsync(erc20Artifacts.WETH9, provider, txDefaults, allArtifacts),
provider,
txDefaults,
expectedAddresses.etherToken,
);
// Dummy ERC20 tokens
for (const token of erc20TokenInfo) {
const totalSupply = new BigNumber(1000000000000000000000000000);
// tslint:disable-next-line:no-unused-variable
const dummyErc20Token = await DummyERC20TokenContract.deployFrom0xArtifactAsync(
erc20Artifacts.DummyERC20Token,
provider,
txDefaults,
allArtifacts,
token.name,
token.symbol,
token.decimals,
totalSupply,
);
}
const zrxProxy = erc20Proxy.address;
const zrxVault = await deployAtAddressAsync(
() =>
ZrxVaultContract.deployFrom0xArtifactAsync(
stakingArtifacts.ZrxVault,
provider,
txDefaults,
allArtifacts,
zrxProxy,
zrxToken.address,
),
provider,
txDefaults,
expectedAddresses.zrxVault,
);
// Note we use TestStakingContract as the deployed bytecode of a StakingContract
// has the tokens hardcoded
const stakingLogic = await deployAtAddressAsync(
() =>
TestStakingContract.deployFrom0xArtifactAsync(
stakingArtifacts.TestStaking,
provider,
txDefaults,
allArtifacts,
etherToken.address,
zrxVault.address,
),
provider,
txDefaults,
expectedAddresses.staking,
);
const stakingProxy = await deployAtAddressAsync(
() =>
StakingProxyContract.deployFrom0xArtifactAsync(
stakingArtifacts.StakingProxy,
provider,
txDefaults,
allArtifacts,
stakingLogic.address,
),
provider,
txDefaults,
expectedAddresses.stakingProxy,
);
await erc20Proxy.addAuthorizedAddress(zrxVault.address).awaitTransactionSuccessAsync(txDefaults);
// Reference the Proxy as the StakingContract for setup
await new TestStakingContract(stakingProxy.address, provider, txDefaults);
await stakingProxy.addAuthorizedAddress(txDefaults.from).awaitTransactionSuccessAsync(txDefaults);
await zrxVault.addAuthorizedAddress(txDefaults.from).awaitTransactionSuccessAsync(txDefaults);
await zrxVault.setStakingProxy(stakingProxy.address).awaitTransactionSuccessAsync(txDefaults);
await stakingLogic.addAuthorizedAddress(txDefaults.from).awaitTransactionSuccessAsync(txDefaults);
// Exchange Proxy //////////////////////////////////////////////////////////
const bridgeAdapter = await BridgeAdapterContract.deployFrom0xArtifactAsync(
exchangeProxyArtifacts.BridgeAdapter,
provider,
txDefaults,
allArtifacts,
etherToken.address,
);
// HACK: Full migration first deploys a Migrator
await untilWantedAddressAsync(expectedAddresses.exchangeProxy, provider, txDefaults, -1);
const exchangeProxy = await fullMigrateExchangeProxyAsync(txDefaults.from, provider, txDefaults);
const exchangeProxyFlashWalletAddress = await exchangeProxy.getTransformWallet().callAsync();
// Deploy transformers.
const wethTransformer = await deployAtAddressAsync(
() =>
WethTransformerContract.deployFrom0xArtifactAsync(
exchangeProxyArtifacts.WethTransformer,
provider,
txDefaults,
allArtifacts,
etherToken.address,
),
provider,
txDefaults,
expectedAddresses.transformers.wethTransformer,
);
const payTakerTransformer = await deployAtAddressAsync(
() =>
PayTakerTransformerContract.deployFrom0xArtifactAsync(
exchangeProxyArtifacts.PayTakerTransformer,
provider,
txDefaults,
allArtifacts,
),
provider,
txDefaults,
expectedAddresses.transformers.payTakerTransformer,
);
const affiliateFeeTransformer = await deployAtAddressAsync(
() =>
AffiliateFeeTransformerContract.deployFrom0xArtifactAsync(
exchangeProxyArtifacts.AffiliateFeeTransformer,
provider,
txDefaults,
allArtifacts,
),
provider,
txDefaults,
expectedAddresses.transformers.affiliateFeeTransformer,
);
const fillQuoteTransformer = await deployAtAddressAsync(
() =>
FillQuoteTransformerContract.deployFrom0xArtifactAsync(
exchangeProxyArtifacts.FillQuoteTransformer,
provider,
txDefaults,
allArtifacts,
bridgeAdapter.address,
exchangeProxy.address,
),
provider,
txDefaults,
expectedAddresses.transformers.fillQuoteTransformer,
);
const positiveSlippageFeeTransformer = await deployAtAddressAsync(
() =>
PositiveSlippageFeeTransformerContract.deployFrom0xArtifactAsync(
exchangeProxyArtifacts.PositiveSlippageFeeTransformer,
provider,
txDefaults,
allArtifacts,
),
provider,
txDefaults,
expectedAddresses.transformers.positiveSlippageFeeTransformer,
);
const contractAddresses = {
erc20Proxy: erc20Proxy.address,
erc721Proxy: NULL_ADDRESS,
erc1155Proxy: NULL_ADDRESS,
zrxToken: zrxToken.address,
etherToken: etherToken.address,
exchange: NULL_ADDRESS,
assetProxyOwner: NULL_ADDRESS,
erc20BridgeProxy: NULL_ADDRESS,
zeroExGovernor: NULL_ADDRESS,
forwarder: NULL_ADDRESS,
coordinatorRegistry: NULL_ADDRESS,
coordinator: NULL_ADDRESS,
multiAssetProxy: NULL_ADDRESS,
staticCallProxy: NULL_ADDRESS,
devUtils: NULL_ADDRESS,
exchangeV2: NULL_ADDRESS,
zrxVault: zrxVault.address,
staking: stakingLogic.address,
stakingProxy: stakingProxy.address,
erc20BridgeSampler: NULL_ADDRESS,
chaiBridge: NULL_ADDRESS,
dydxBridge: NULL_ADDRESS,
godsUnchainedValidator: NULL_ADDRESS,
broker: NULL_ADDRESS,
chainlinkStopLimit: NULL_ADDRESS,
maximumGasPrice: NULL_ADDRESS,
dexForwarderBridge: NULL_ADDRESS,
exchangeProxyGovernor: NULL_ADDRESS,
exchangeProxy: exchangeProxy.address,
exchangeProxyTransformerDeployer: txDefaults.from,
exchangeProxyFlashWallet: exchangeProxyFlashWalletAddress,
exchangeProxyLiquidityProviderSandbox: NULL_ADDRESS,
zrxTreasury: NULL_ADDRESS,
transformers: {
wethTransformer: wethTransformer.address,
payTakerTransformer: payTakerTransformer.address,
fillQuoteTransformer: fillQuoteTransformer.address,
affiliateFeeTransformer: affiliateFeeTransformer.address,
positiveSlippageFeeTransformer: positiveSlippageFeeTransformer.address,
},
};
return contractAddresses;
}
let _cachedContractAddresses: ContractAddresses;
/**
* Exactly like runMigrationsAsync but will only run the migrations the first
* time it is called. Any subsequent calls will return the cached contract
* addresses.
* @param provider Web3 provider instance. Your provider instance should connect to the testnet you want to deploy to.
* @param txDefaults Default transaction values to use when deploying contracts (e.g., specify the desired contract creator with the `from` parameter).
* @returns The addresses of the contracts that were deployed.
*/
export async function runMigrationsOnceAsync(
provider: Web3ProviderEngine,
txDefaults: TxData,
): Promise<ContractAddresses> {
if (_cachedContractAddresses !== undefined) {
return _cachedContractAddresses;
}
_cachedContractAddresses = await runMigrationsAsync(provider, txDefaults);
return _cachedContractAddresses;
}

View File

@@ -1,198 +0,0 @@
#!/usr/bin/env node
import { getContractAddressesForChainOrThrow } from '@0x/contract-addresses';
import { ERC20ProxyContract } from '@0x/contracts-asset-proxy';
import { ZeroExGovernorContract } from '@0x/contracts-multisig';
import { StakingContract, StakingProxyContract, ZrxVaultContract } from '@0x/contracts-staking';
import { EmptyWalletSubprovider, RPCSubprovider, Web3ProviderEngine } from '@0x/subproviders';
import { logUtils, providerUtils } from '@0x/utils';
import { Web3Wrapper } from '@0x/web3-wrapper';
import { SupportedProvider } from 'ethereum-types';
import { getConfigsByChainId } from './utils/configs_by_chain';
import { getTimelockRegistrationsByChainId } from './utils/timelocks';
// NOTE: add your own Infura Project ID to RPC urls before running
const INFURA_PROJECT_ID = '';
const networkIdToRpcUrl = {
1: `https://mainnet.infura.io/v3/${INFURA_PROJECT_ID}`,
3: `https://ropsten.infura.io/v3/${INFURA_PROJECT_ID}`,
4: `https://rinkeby.infura.io/v3/${INFURA_PROJECT_ID}`,
42: `https://kovan.infura.io/v3/${INFURA_PROJECT_ID}`,
};
// tslint:disable:custom-no-magic-numbers
async function testContractConfigsAsync(provider: SupportedProvider): Promise<void> {
const web3Wrapper = new Web3Wrapper(provider);
const chainId = await web3Wrapper.getChainIdAsync();
const addresses = getContractAddressesForChainOrThrow(chainId);
const configs = getConfigsByChainId(chainId);
function warnIfMismatch(actual: any, expected: any, message: string): void {
if (actual !== expected) {
logUtils.warn(`${message}: actual: ${actual}, expected: ${expected}, chainId: ${chainId}`);
}
}
const erc20Proxy = new ERC20ProxyContract(addresses.erc20Proxy, provider);
const erc20BridgeProxy = new ERC20ProxyContract(addresses.erc20BridgeProxy, provider);
const governor = new ZeroExGovernorContract(addresses.zeroExGovernor, provider);
const stakingProxy = new StakingProxyContract(addresses.stakingProxy, provider);
const stakingContract = new StakingContract(addresses.stakingProxy, provider);
const zrxVault = new ZrxVaultContract(addresses.zrxVault, provider);
async function verifyAssetProxyConfigsAsync(): Promise<void> {
// Verify ERC20Proxy configs
const erc20ProxyOwner = await erc20Proxy.owner().callAsync();
warnIfMismatch(erc20ProxyOwner, governor.address, 'Unexpected ERC20Proxy owner');
const erc20AuthorizedAddresses = await erc20Proxy.getAuthorizedAddresses().callAsync();
warnIfMismatch(erc20AuthorizedAddresses.length, 4, 'Unexpected number of authorized addresses in ERC20Proxy');
const isZrxVaultAuthorizedInER20Proxy = await erc20Proxy.authorized(zrxVault.address).callAsync();
warnIfMismatch(isZrxVaultAuthorizedInER20Proxy, true, 'ZrxVault not authorized in ERC20Proxy');
// Verify ERC20BridgeProxy configs
const erc20BridgeProxyOwner = await erc20BridgeProxy.owner().callAsync();
warnIfMismatch(erc20BridgeProxyOwner, governor.address, 'Unexpected ERC20BridgeProxy owner');
const erc20BridgeAuthorizedAddresses = await erc20BridgeProxy.getAuthorizedAddresses().callAsync();
warnIfMismatch(
erc20BridgeAuthorizedAddresses.length,
2,
'Unexpected number of authorized addresses in ERC20BridgeProxy',
);
}
async function verifyStakingConfigsAsync(): Promise<void> {
const stakingLogicAddress = await stakingProxy.stakingContract().callAsync();
warnIfMismatch(stakingLogicAddress, addresses.staking, 'Unexpected Staking contract attached to StakingProxy');
const isExchangeRegistered = await stakingContract.validExchanges(addresses.exchange).callAsync();
warnIfMismatch(isExchangeRegistered, true, 'Exchange not registered in StakingProxy');
const zrxVaultAddress = await stakingContract.getZrxVault().callAsync();
warnIfMismatch(zrxVaultAddress, addresses.zrxVault, 'Unexpected ZrxVault set in StakingProxy');
const wethAddress = await stakingContract.getWethContract().callAsync();
warnIfMismatch(wethAddress, addresses.etherToken, 'Unexpected WETH contract set in StakingProxy');
const stakingProxyOwner = await stakingProxy.owner().callAsync();
warnIfMismatch(stakingProxyOwner, addresses.zeroExGovernor, 'Unexpected StakingProxy owner');
const stakingProxyAuthorizedAddresses = await stakingProxy.getAuthorizedAddresses().callAsync();
warnIfMismatch(
stakingProxyAuthorizedAddresses.length,
1,
'Unexpected number of authorized addresses in StakingProxy',
);
const isGovernorAuthorizedInStakingProxy = await stakingProxy.authorized(addresses.zeroExGovernor).callAsync();
warnIfMismatch(isGovernorAuthorizedInStakingProxy, true, 'ZeroExGovernor not authorized in StakingProxy');
const zrxVaultOwner = await zrxVault.owner().callAsync();
warnIfMismatch(zrxVaultOwner, addresses.zeroExGovernor, 'Unexpected ZrxVault owner');
const zrxVaultAuthorizedAddresses = await zrxVault.getAuthorizedAddresses().callAsync();
warnIfMismatch(zrxVaultAuthorizedAddresses.length, 1, 'Unexpected number of authorized addresses in ZrxVault');
const isGovernorAuthorizedInZrxVault = await zrxVault.authorized(addresses.zeroExGovernor).callAsync();
warnIfMismatch(isGovernorAuthorizedInZrxVault, true, 'ZeroExGovernor not authorized in ZrxVault');
const zrxAssetProxy = await zrxVault.zrxAssetProxy().callAsync();
warnIfMismatch(zrxAssetProxy, addresses.erc20Proxy, 'Unexpected ERC20Proxy set in ZrxVault');
const zrxVaultStakingProxy = await zrxVault.stakingProxyAddress().callAsync();
warnIfMismatch(zrxVaultStakingProxy, addresses.stakingProxy, 'Unexpected StakingProxy set in ZrxVault');
const params = await stakingContract.getParams().callAsync();
warnIfMismatch(
params[0].toNumber(),
configs.staking.epochDurationInSeconds.toNumber(),
'Unexpected epoch duration in StakingProxy',
);
warnIfMismatch(
params[1].toString(),
configs.staking.rewardDelegatedStakeWeight.toString(),
'Unexpected delegated stake weight in StakingProxy',
);
warnIfMismatch(
params[2].toNumber(),
configs.staking.minimumPoolStake.toNumber(),
'Unexpected minimum pool stake in StakingProxy',
);
warnIfMismatch(
params[3].toString(),
configs.staking.cobbDouglasAlphaNumerator.toString(),
'Unexpected alpha numerator in StakingProxy',
);
warnIfMismatch(
params[4].toString(),
configs.staking.cobbDouglasAlphaDenominator.toString(),
'Unexpected alpha denominator in StakingProxy',
);
}
async function verifyZeroExGovernorConfigsAsync(): Promise<void> {
const timelockRegistrations = getTimelockRegistrationsByChainId(chainId);
for (const timelockRegistration of timelockRegistrations) {
const actualRegistration = await governor
.functionCallTimeLocks(timelockRegistration.functionSelector, timelockRegistration.destination)
.callAsync();
warnIfMismatch(
actualRegistration[0],
true,
`Function ${timelockRegistration.functionSelector} at address ${timelockRegistration.destination} not registered in ZeroExGovernor`,
);
warnIfMismatch(
actualRegistration[1].toNumber(),
timelockRegistration.secondsTimeLocked.toNumber(),
`Timelock for function ${timelockRegistration.functionSelector} at address ${timelockRegistration.destination} in ZeroExGovernor`,
);
}
const owners = await governor.getOwners().callAsync();
warnIfMismatch(
owners.length,
configs.zeroExGovernor.owners.length,
'Unexpected number of owners in ZeroExGovernor',
);
owners.forEach((owner, i) => {
warnIfMismatch(
owners[i],
configs.zeroExGovernor.owners[i],
`Unexpected owner in ZeroExGovernor at index ${i}`,
);
});
const secondsTimeLocked = await governor.secondsTimeLocked().callAsync();
warnIfMismatch(
secondsTimeLocked.toNumber(),
configs.zeroExGovernor.secondsTimeLocked.toNumber(),
'Unexpected secondsTimeLocked in ZeroExGovernor',
);
const confirmationsRequired = await governor.required().callAsync();
warnIfMismatch(
confirmationsRequired.toNumber(),
configs.zeroExGovernor.required.toNumber(),
'Unexpected number of confirmations required in ZeroExGovernor',
);
}
await verifyStakingConfigsAsync();
await verifyAssetProxyConfigsAsync();
await verifyZeroExGovernorConfigsAsync();
}
(async () => {
for (const rpcUrl of Object.values(networkIdToRpcUrl)) {
const provider = new Web3ProviderEngine();
provider.addProvider(new EmptyWalletSubprovider());
provider.addProvider(new RPCSubprovider(rpcUrl));
providerUtils.startProviderEngine(provider);
await testContractConfigsAsync(provider);
}
})().catch(err => {
logUtils.log(err);
process.exit(1);
});

View File

@@ -1,154 +0,0 @@
import { getContractAddressesForChainOrThrow } from '@0x/contract-addresses';
import {
artifacts as multisigArtifacts,
ZeroExGovernorContract,
ZeroExGovernorSubmissionEventArgs,
} from '@0x/contracts-multisig';
import {
artifacts as stakingArtifacts,
StakingContract,
StakingProxyContract,
ZrxVaultContract,
} from '@0x/contracts-staking';
import { IAuthorizableContract, IOwnableContract } from '@0x/contracts-utils';
import { AbiEncoder, BigNumber, logUtils, providerUtils } from '@0x/utils';
import { LogWithDecodedArgs, SupportedProvider, TxData } from 'ethereum-types';
import { getConfigsByChainId } from './utils/configs_by_chain';
import { constants } from './utils/constants';
import { providerFactory } from './utils/provider_factory';
import { getTimelockRegistrationsByChainId } from './utils/timelocks';
async function submitAndExecuteTransactionAsync(
governor: ZeroExGovernorContract,
destination: string,
data: string,
): Promise<void> {
const { logs } = await governor
.submitTransaction(destination, constants.ZERO_AMOUNT, data)
.awaitTransactionSuccessAsync();
// tslint:disable-next-line:no-unnecessary-type-assertion
const txId = (logs[0] as LogWithDecodedArgs<ZeroExGovernorSubmissionEventArgs>).args.transactionId;
logUtils.log(`${txId} submitted`);
await governor.executeTransaction(txId).awaitTransactionSuccessAsync();
logUtils.log(`${txId} executed`);
}
/**
* Deploys all 3.0 contracts and reconfigures existing 2.0 contracts.
* @param supportedProvider Web3 provider instance. Your provider instance should connect to the testnet you want to deploy to.
* @param txDefaults Default transaction values to use when deploying contracts (e.g., specify the desired contract creator with the `from` parameter).
*/
export async function runMigrationsAsync(supportedProvider: SupportedProvider, txDefaults: TxData): Promise<void> {
const provider = providerUtils.standardizeOrThrow(supportedProvider);
const chainId = new BigNumber(await providerUtils.getChainIdAsync(provider));
const deployedAddresses = getContractAddressesForChainOrThrow(chainId.toNumber());
const configs = getConfigsByChainId(chainId.toNumber());
// NOTE: This must be deployed before running these migrations, since its address is hard coded in the
// staking logic contract.
const zrxVault = new ZrxVaultContract(deployedAddresses.zrxVault, provider, txDefaults);
const stakingLogic = await StakingContract.deployFrom0xArtifactAsync(
stakingArtifacts.Staking,
provider,
txDefaults,
stakingArtifacts,
);
const stakingProxy = await StakingProxyContract.deployFrom0xArtifactAsync(
stakingArtifacts.StakingProxy,
provider,
txDefaults,
stakingArtifacts,
stakingLogic.address,
);
const authorizableInterface = new IAuthorizableContract(constants.NULL_ADDRESS, provider, txDefaults);
const ownableInterface = new IOwnableContract(constants.NULL_ADDRESS, provider, txDefaults);
const customTimeLocks = getTimelockRegistrationsByChainId(chainId.toNumber());
const governor = await ZeroExGovernorContract.deployFrom0xArtifactAsync(
multisigArtifacts.ZeroExGovernor,
provider,
txDefaults,
multisigArtifacts,
customTimeLocks.map(timeLockInfo => timeLockInfo.functionSelector),
customTimeLocks.map(timeLockInfo => timeLockInfo.destination),
customTimeLocks.map(timeLockInfo => timeLockInfo.secondsTimeLocked),
configs.zeroExGovernor.owners,
configs.zeroExGovernor.required,
configs.zeroExGovernor.secondsTimeLocked,
);
logUtils.log('Configuring ZrxVault...');
await zrxVault.addAuthorizedAddress(txDefaults.from).awaitTransactionSuccessAsync();
await zrxVault.setStakingProxy(stakingProxy.address).awaitTransactionSuccessAsync();
await zrxVault.removeAuthorizedAddress(txDefaults.from).awaitTransactionSuccessAsync();
await zrxVault.addAuthorizedAddress(governor.address).awaitTransactionSuccessAsync();
await zrxVault.transferOwnership(governor.address).awaitTransactionSuccessAsync();
logUtils.log('ZrxVault configured!');
logUtils.log('Configuring StakingProxy...');
await stakingProxy.addAuthorizedAddress(txDefaults.from).awaitTransactionSuccessAsync();
await stakingProxy.removeAuthorizedAddress(txDefaults.from).awaitTransactionSuccessAsync();
await stakingProxy.addAuthorizedAddress(governor.address).awaitTransactionSuccessAsync();
await stakingProxy.transferOwnership(governor.address).awaitTransactionSuccessAsync();
logUtils.log('StakingProxy configured!');
logUtils.log('Transfering ownership of 2.0 contracts...');
const oldAssetProxyOwner = new ZeroExGovernorContract(deployedAddresses.assetProxyOwner, provider, txDefaults);
await submitAndExecuteTransactionAsync(
oldAssetProxyOwner,
deployedAddresses.exchangeV2, // Exchange 2.1 address
ownableInterface.transferOwnership(governor.address).getABIEncodedTransactionData(),
);
await submitAndExecuteTransactionAsync(
oldAssetProxyOwner,
deployedAddresses.erc20Proxy,
ownableInterface.transferOwnership(governor.address).getABIEncodedTransactionData(),
);
await submitAndExecuteTransactionAsync(
oldAssetProxyOwner,
deployedAddresses.erc721Proxy,
ownableInterface.transferOwnership(governor.address).getABIEncodedTransactionData(),
);
await submitAndExecuteTransactionAsync(
oldAssetProxyOwner,
deployedAddresses.erc1155Proxy,
ownableInterface.transferOwnership(governor.address).getABIEncodedTransactionData(),
);
await submitAndExecuteTransactionAsync(
oldAssetProxyOwner,
deployedAddresses.multiAssetProxy,
ownableInterface.transferOwnership(governor.address).getABIEncodedTransactionData(),
);
logUtils.log('Ownership transferred!');
const functionCalls = [
// AssetProxy configs
{
destination: deployedAddresses.erc20Proxy,
data: authorizableInterface.addAuthorizedAddress(zrxVault.address).getABIEncodedTransactionData(),
},
];
const batchTransactionEncoder = AbiEncoder.create('(bytes[],address[],uint256[])');
const batchTransactionData = batchTransactionEncoder.encode([
functionCalls.map(item => item.data),
functionCalls.map(item => item.destination),
functionCalls.map(() => constants.ZERO_AMOUNT),
]);
await submitAndExecuteTransactionAsync(governor, governor.address, batchTransactionData);
}
(async () => {
const networkId = 1;
const rpcUrl = 'https://mainnet.infura.io/v3/';
const provider = await providerFactory.getLedgerProviderAsync(networkId, rpcUrl);
await runMigrationsAsync(provider, { from: '0x3b39078f2a3e1512eecc8d6792fdc7f33e1cd2cf', gasPrice: 10000000001 });
})().catch(err => {
logUtils.log(err);
process.exit(1);
});

View File

@@ -1,29 +0,0 @@
import { BigNumber } from '@0x/utils';
export interface ERC20Token {
address?: string;
name: string;
symbol: string;
decimals: BigNumber;
ipfsHash: string;
swarmHash: string;
}
export interface ERC721Token {
name: string;
symbol: string;
}
export enum ContractName {
TokenTransferProxy = 'TokenTransferProxy',
TokenRegistry = 'TokenRegistry',
MultiSigWalletWithTimeLock = 'MultiSigWalletWithTimeLock',
Exchange = 'Exchange',
ZRXToken = 'ZRXToken',
DummyToken = 'DummyToken',
WETH9 = 'WETH9',
MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress = 'MultiSigWalletWithTimeLockExceptRemoveAuthorizedAddress',
AccountLevels = 'AccountLevels',
EtherDelta = 'EtherDelta',
Arbitrage = 'Arbitrage',
}

View File

@@ -1,59 +0,0 @@
import { BigNumber } from '@0x/utils';
import { constants } from './constants';
export interface ConfigsByChain {
zeroExGovernor: { owners: string[]; secondsTimeLocked: BigNumber; required: BigNumber };
staking: {
epochDurationInSeconds: BigNumber;
rewardDelegatedStakeWeight: number;
minimumPoolStake: BigNumber;
cobbDouglasAlphaNumerator: number;
cobbDouglasAlphaDenominator: number;
};
}
// tslint:disable custom-no-magic-numbers
/**
* Gets configs that correspond to the given chainId.
* @param chainId Id of the netowrk.
*/
export function getConfigsByChainId(chainId: number): ConfigsByChain {
const mainnetConfigs = {
zeroExGovernor: {
owners: [
'0x257619b7155d247e43c8b6d90c8c17278ae481f0',
'0x5ee2a00f8f01d099451844af7f894f26a57fcbf2',
'0x894d623e0e0e8ed12c4a73dada999e275684a37d',
],
secondsTimeLocked: constants.TWO_WEEKS_IN_SEC,
required: new BigNumber(2),
},
staking: {
epochDurationInSeconds: constants.TEN_DAYS_IN_SEC,
rewardDelegatedStakeWeight: 10 ** 6 * 0.9,
minimumPoolStake: new BigNumber(10).pow(18).times(100),
cobbDouglasAlphaNumerator: 2,
cobbDouglasAlphaDenominator: 3,
},
};
const testnetConfigs = {
zeroExGovernor: {
owners: [
'0x9df8137872ac09a8fee71d0da5c7539923fb9bf0',
'0xcf34d44db312d188789f43a63d11cf2bebb4da15',
'0x73fd50f2a6beac9cdac9fe87ef68a18edc415831',
],
secondsTimeLocked: constants.ZERO_AMOUNT,
required: new BigNumber(1),
},
staking: {
epochDurationInSeconds: constants.TEN_DAYS_IN_SEC.dividedToIntegerBy(2),
rewardDelegatedStakeWeight: 10 ** 6 * 0.9,
minimumPoolStake: new BigNumber(10).pow(18).times(100),
cobbDouglasAlphaNumerator: 2,
cobbDouglasAlphaDenominator: 3,
},
};
return chainId === constants.MAINNET_CHAIN_ID ? mainnetConfigs : testnetConfigs;
}

View File

@@ -1,20 +0,0 @@
import { BigNumber } from '@0x/utils';
// tslint:disable custom-no-magic-numbers
export const constants = {
NULL_ADDRESS: '0x0000000000000000000000000000000000000000',
MAINNET_CHAIN_ID: 1,
ZERO_AMOUNT: new BigNumber(0),
TWO_WEEKS_IN_SEC: new BigNumber(14)
.times(24)
.times(60)
.times(60),
TEN_DAYS_IN_SEC: new BigNumber(10)
.times(24)
.times(60)
.times(60),
TWENTY_DAYS_IN_SEC: new BigNumber(20)
.times(24)
.times(60)
.times(60),
};

View File

@@ -1,26 +0,0 @@
import { LedgerEthereumClient, LedgerSubprovider, RPCSubprovider, Web3ProviderEngine } from '@0x/subproviders';
import { providerUtils } from '@0x/utils';
import Eth from '@ledgerhq/hw-app-eth';
// tslint:disable:no-implicit-dependencies
import TransportNodeHid from '@ledgerhq/hw-transport-node-hid';
import { Provider } from 'ethereum-types';
async function ledgerEthereumNodeJsClientFactoryAsync(): Promise<LedgerEthereumClient> {
const ledgerConnection = await TransportNodeHid.create();
const ledgerEthClient = new Eth(ledgerConnection);
return ledgerEthClient;
}
export const providerFactory = {
async getLedgerProviderAsync(networkId: number, rpcUrl: string): Promise<Provider> {
const provider = new Web3ProviderEngine();
const ledgerWalletConfigs = {
networkId,
ledgerEthereumClientFactoryAsync: ledgerEthereumNodeJsClientFactoryAsync,
};
const ledgerSubprovider = new LedgerSubprovider(ledgerWalletConfigs);
provider.addProvider(ledgerSubprovider);
provider.addProvider(new RPCSubprovider(rpcUrl));
providerUtils.startProviderEngine(provider);
return provider;
},
};

View File

@@ -1,145 +0,0 @@
import { getContractAddressesForChainOrThrow } from '@0x/contract-addresses';
import { StakingContract, StakingProxyContract, ZrxVaultContract } from '@0x/contracts-staking';
import { IAuthorizableContract, IOwnableContract } from '@0x/contracts-utils';
import { Web3ProviderEngine } from '@0x/subproviders';
import { BigNumber } from '@0x/utils';
import { constants } from './constants';
export interface TimelockRegistration {
functionSelector: string;
destination: string;
secondsTimeLocked: BigNumber;
}
/**
* Gets the custom timelock configs that correspond the the network of the given provider.
* @param provider Web3 provider instance.
*/
export function getTimelockRegistrationsByChainId(chainId: number): TimelockRegistration[] {
const deployedAddresses = getContractAddressesForChainOrThrow(chainId);
const provider = new Web3ProviderEngine();
const authorizableInterface = new IAuthorizableContract(constants.NULL_ADDRESS, provider);
const ownableInterface = new IOwnableContract(constants.NULL_ADDRESS, provider);
const zrxVault = new ZrxVaultContract(constants.NULL_ADDRESS, provider);
const stakingProxy = new StakingProxyContract(constants.NULL_ADDRESS, provider);
const stakingLogic = new StakingContract(constants.NULL_ADDRESS, provider);
const noTimelockRegistrations = [
// AssetProxy timelocks
{
destination: deployedAddresses.erc20Proxy,
functionSelector: authorizableInterface.getSelector('removeAuthorizedAddress'),
secondsTimeLocked: constants.ZERO_AMOUNT,
},
{
destination: deployedAddresses.erc20Proxy,
functionSelector: authorizableInterface.getSelector('removeAuthorizedAddressAtIndex'),
secondsTimeLocked: constants.ZERO_AMOUNT,
},
// ZrxVault timelocks
{
destination: deployedAddresses.zrxVault,
functionSelector: zrxVault.getSelector('enterCatastrophicFailure'),
secondsTimeLocked: constants.ZERO_AMOUNT,
},
];
const customTimelockRegistrations = [
// ZrxVault timelocks
{
destination: deployedAddresses.zrxVault,
functionSelector: zrxVault.getSelector('setStakingProxy'),
secondsTimeLocked:
chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT,
},
{
destination: deployedAddresses.zrxVault,
functionSelector: zrxVault.getSelector('setZrxProxy'),
secondsTimeLocked:
chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT,
},
{
destination: deployedAddresses.zrxVault,
functionSelector: ownableInterface.getSelector('transferOwnership'),
secondsTimeLocked:
chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT,
},
{
destination: deployedAddresses.zrxVault,
functionSelector: authorizableInterface.getSelector('addAuthorizedAddress'),
secondsTimeLocked:
chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT,
},
{
destination: deployedAddresses.zrxVault,
functionSelector: authorizableInterface.getSelector('removeAuthorizedAddress'),
secondsTimeLocked:
chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT,
},
{
destination: deployedAddresses.zrxVault,
functionSelector: authorizableInterface.getSelector('removeAuthorizedAddressAtIndex'),
secondsTimeLocked:
chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT,
},
// StakingProxy timelocks
{
destination: deployedAddresses.stakingProxy,
functionSelector: stakingProxy.getSelector('attachStakingContract'),
secondsTimeLocked:
chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT,
},
{
destination: deployedAddresses.stakingProxy,
functionSelector: stakingProxy.getSelector('detachStakingContract'),
secondsTimeLocked:
chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT,
},
{
destination: deployedAddresses.stakingProxy,
functionSelector: stakingLogic.getSelector('setParams'),
secondsTimeLocked:
chainId === constants.MAINNET_CHAIN_ID ? constants.TEN_DAYS_IN_SEC : constants.ZERO_AMOUNT,
},
{
destination: deployedAddresses.stakingProxy,
functionSelector: stakingLogic.getSelector('addExchangeAddress'),
secondsTimeLocked:
chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT,
},
{
destination: deployedAddresses.stakingProxy,
functionSelector: stakingLogic.getSelector('removeExchangeAddress'),
secondsTimeLocked:
chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT,
},
{
destination: deployedAddresses.stakingProxy,
functionSelector: ownableInterface.getSelector('transferOwnership'),
secondsTimeLocked:
chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT,
},
{
destination: deployedAddresses.stakingProxy,
functionSelector: authorizableInterface.getSelector('addAuthorizedAddress'),
secondsTimeLocked:
chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT,
},
{
destination: deployedAddresses.stakingProxy,
functionSelector: authorizableInterface.getSelector('removeAuthorizedAddress'),
secondsTimeLocked:
chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT,
},
{
destination: deployedAddresses.stakingProxy,
functionSelector: authorizableInterface.getSelector('removeAuthorizedAddressAtIndex'),
secondsTimeLocked:
chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT,
},
];
return [...noTimelockRegistrations, ...customTimelockRegistrations];
}

Some files were not shown because too many files have changed in this diff Show More