Compare commits

..

23 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
103 changed files with 2261 additions and 5092 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

@@ -20,17 +20,22 @@
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import '@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol';
import '../libs/LibSignature.sol';
import '../libs/LibNativeOrder.sol';
import './INativeOrdersEvents.sol';
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "../libs/LibSignature.sol";
import "../libs/LibNativeOrder.sol";
import "./INativeOrdersEvents.sol";
/// @dev Feature for interacting with limit orders.
interface INativeOrdersFeature is INativeOrdersEvents {
interface INativeOrdersFeature is
INativeOrdersEvents
{
/// @dev Transfers protocol fees from the `FeeCollector` pools into
/// the staking contract.
/// @param poolIds Staking pool IDs
function transferProtocolFeesForPools(bytes32[] calldata poolIds) external;
function transferProtocolFeesForPools(bytes32[] calldata poolIds)
external;
/// @dev Fill a limit order. The taker and sender will be the caller.
/// @param order The limit order. ETH protocol fees can be
@@ -44,7 +49,10 @@ interface INativeOrdersFeature is INativeOrdersEvents {
LibNativeOrder.LimitOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount
) external payable returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
)
external
payable
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Fill an RFQ order for up to `takerTokenFillAmount` taker tokens.
/// The taker will be the caller.
@@ -57,7 +65,9 @@ interface INativeOrdersFeature is INativeOrdersEvents {
LibNativeOrder.RfqOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount
) external returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
)
external
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Fill an RFQ order for exactly `takerTokenFillAmount` taker tokens.
/// The taker will be the caller. ETH protocol fees can be
@@ -71,7 +81,10 @@ interface INativeOrdersFeature is INativeOrdersEvents {
LibNativeOrder.LimitOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount
) external payable returns (uint128 makerTokenFilledAmount);
)
external
payable
returns (uint128 makerTokenFilledAmount);
/// @dev Fill an RFQ order for exactly `takerTokenFillAmount` taker tokens.
/// The taker will be the caller.
@@ -83,7 +96,9 @@ interface INativeOrdersFeature is INativeOrdersEvents {
LibNativeOrder.RfqOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount
) external returns (uint128 makerTokenFilledAmount);
)
external
returns (uint128 makerTokenFilledAmount);
/// @dev Fill a limit order. Internal variant. ETH protocol fees can be
/// attached to this call. Any unspent ETH will be refunded to
@@ -101,7 +116,10 @@ interface INativeOrdersFeature is INativeOrdersEvents {
uint128 takerTokenFillAmount,
address taker,
address sender
) external payable returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
)
external
payable
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Fill an RFQ order. Internal variant.
/// @param order The RFQ order.
@@ -120,33 +138,40 @@ interface INativeOrdersFeature is INativeOrdersEvents {
address taker,
bool useSelfBalance,
address recipient
) external returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
)
external
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Cancel a single limit order. The caller must be the maker or a valid order signer.
/// Silently succeeds if the order has already been cancelled.
/// @param order The limit order.
function cancelLimitOrder(LibNativeOrder.LimitOrder calldata order) external;
function cancelLimitOrder(LibNativeOrder.LimitOrder calldata order)
external;
/// @dev Cancel a single RFQ order. The caller must be the maker or a valid order signer.
/// Silently succeeds if the order has already been cancelled.
/// @param order The RFQ order.
function cancelRfqOrder(LibNativeOrder.RfqOrder calldata order) external;
function cancelRfqOrder(LibNativeOrder.RfqOrder calldata order)
external;
/// @dev Mark what tx.origin addresses are allowed to fill an order that
/// specifies the message sender as its txOrigin.
/// @param origins An array of origin addresses to update.
/// @param allowed True to register, false to unregister.
function registerAllowedRfqOrigins(address[] memory origins, bool allowed) external;
function registerAllowedRfqOrigins(address[] memory origins, bool allowed)
external;
/// @dev Cancel multiple limit orders. The caller must be the maker or a valid order signer.
/// Silently succeeds if the order has already been cancelled.
/// @param orders The limit orders.
function batchCancelLimitOrders(LibNativeOrder.LimitOrder[] calldata orders) external;
function batchCancelLimitOrders(LibNativeOrder.LimitOrder[] calldata orders)
external;
/// @dev Cancel multiple RFQ orders. The caller must be the maker or a valid order signer.
/// Silently succeeds if the order has already been cancelled.
/// @param orders The RFQ orders.
function batchCancelRfqOrders(LibNativeOrder.RfqOrder[] calldata orders) external;
function batchCancelRfqOrders(LibNativeOrder.RfqOrder[] calldata orders)
external;
/// @dev Cancel all limit orders for a given maker and pair with a salt less
/// than the value provided. The caller must be the maker. Subsequent
@@ -159,7 +184,8 @@ interface INativeOrdersFeature is INativeOrdersEvents {
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
uint256 minValidSalt
) external;
)
external;
/// @dev Cancel all limit orders for a given maker and pair with a salt less
/// than the value provided. The caller must be a signer registered to the maker.
@@ -174,7 +200,8 @@ interface INativeOrdersFeature is INativeOrdersEvents {
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
uint256 minValidSalt
) external;
)
external;
/// @dev Cancel all limit orders for a given maker and pairs with salts less
/// than the values provided. The caller must be the maker. Subsequent
@@ -187,7 +214,8 @@ interface INativeOrdersFeature is INativeOrdersEvents {
IERC20TokenV06[] calldata makerTokens,
IERC20TokenV06[] calldata takerTokens,
uint256[] calldata minValidSalts
) external;
)
external;
/// @dev Cancel all limit orders for a given maker and pairs with salts less
/// than the values provided. The caller must be a signer registered to the maker.
@@ -202,7 +230,8 @@ interface INativeOrdersFeature is INativeOrdersEvents {
IERC20TokenV06[] memory makerTokens,
IERC20TokenV06[] memory takerTokens,
uint256[] memory minValidSalts
) external;
)
external;
/// @dev Cancel all RFQ orders for a given maker and pair with a salt less
/// than the value provided. The caller must be the maker. Subsequent
@@ -215,7 +244,8 @@ interface INativeOrdersFeature is INativeOrdersEvents {
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
uint256 minValidSalt
) external;
)
external;
/// @dev Cancel all RFQ orders for a given maker and pair with a salt less
/// than the value provided. The caller must be a signer registered to the maker.
@@ -230,7 +260,8 @@ interface INativeOrdersFeature is INativeOrdersEvents {
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
uint256 minValidSalt
) external;
)
external;
/// @dev Cancel all RFQ orders for a given maker and pairs with salts less
/// than the values provided. The caller must be the maker. Subsequent
@@ -243,7 +274,8 @@ interface INativeOrdersFeature is INativeOrdersEvents {
IERC20TokenV06[] calldata makerTokens,
IERC20TokenV06[] calldata takerTokens,
uint256[] calldata minValidSalts
) external;
)
external;
/// @dev Cancel all RFQ orders for a given maker and pairs with salts less
/// than the values provided. The caller must be a signer registered to the maker.
@@ -258,7 +290,8 @@ interface INativeOrdersFeature is INativeOrdersEvents {
IERC20TokenV06[] memory makerTokens,
IERC20TokenV06[] memory takerTokens,
uint256[] memory minValidSalts
) external;
)
external;
/// @dev Get the order info for a limit order.
/// @param order The limit order.
@@ -279,17 +312,26 @@ interface INativeOrdersFeature is INativeOrdersEvents {
/// @dev Get the canonical hash of a limit order.
/// @param order The limit order.
/// @return orderHash The order hash.
function getLimitOrderHash(LibNativeOrder.LimitOrder calldata order) external view returns (bytes32 orderHash);
function getLimitOrderHash(LibNativeOrder.LimitOrder calldata order)
external
view
returns (bytes32 orderHash);
/// @dev Get the canonical hash of an RFQ order.
/// @param order The RFQ order.
/// @return orderHash The order hash.
function getRfqOrderHash(LibNativeOrder.RfqOrder calldata order) external view returns (bytes32 orderHash);
function getRfqOrderHash(LibNativeOrder.RfqOrder calldata order)
external
view
returns (bytes32 orderHash);
/// @dev Get the protocol fee multiplier. This should be multiplied by the
/// gas price to arrive at the required protocol fee to fill a native order.
/// @return multiplier The protocol fee multiplier.
function getProtocolFeeMultiplier() external view returns (uint32 multiplier);
function getProtocolFeeMultiplier()
external
view
returns (uint32 multiplier);
/// @dev Get order info, fillable amount, and signature validity for a limit order.
/// Fillable amount is determined using balances and allowances of the maker.
@@ -319,7 +361,10 @@ interface INativeOrdersFeature is INativeOrdersEvents {
/// @return actualFillableTakerTokenAmount How much of the order is fillable
/// based on maker funds, in taker tokens.
/// @return isSignatureValid Whether the signature is valid.
function getRfqOrderRelevantState(LibNativeOrder.RfqOrder calldata order, LibSignature.Signature calldata signature)
function getRfqOrderRelevantState(
LibNativeOrder.RfqOrder calldata order,
LibSignature.Signature calldata signature
)
external
view
returns (
@@ -374,10 +419,20 @@ interface INativeOrdersFeature is INativeOrdersEvents {
/// This allows one to sign on behalf of a contract that calls this function
/// @param signer The address from which you plan to generate signatures
/// @param allowed True to register, false to unregister.
function registerAllowedOrderSigner(address signer, bool allowed) external;
function registerAllowedOrderSigner(
address signer,
bool allowed
)
external;
/// @dev checks if a given address is registered to sign on behalf of a maker address
/// @param maker The maker address encoded in an order (can be a contract)
/// @param signer The address that is providing a signature
function isValidOrderSigner(address maker, address signer) external view returns (bool isAllowed);
function isValidOrderSigner(
address maker,
address signer
)
external
view
returns (bool isAllowed);
}

View File

@@ -20,22 +20,23 @@
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import '@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol';
import '@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol';
import '@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol';
import '@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol';
import '@0x/contracts-utils/contracts/src/v06/LibMathV06.sol';
import '../errors/LibTransformERC20RichErrors.sol';
import '../features/interfaces/INativeOrdersFeature.sol';
import '../features/libs/LibNativeOrder.sol';
import './bridges/IBridgeAdapter.sol';
import './Transformer.sol';
import './LibERC20Transformer.sol';
import '../IZeroEx.sol';
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibMathV06.sol";
import "../errors/LibTransformERC20RichErrors.sol";
import "../features/interfaces/INativeOrdersFeature.sol";
import "../features/libs/LibNativeOrder.sol";
import "./bridges/IBridgeAdapter.sol";
import "./Transformer.sol";
import "./LibERC20Transformer.sol";
/// @dev A transformer that fills an ERC20 market sell/buy quote.
/// This transformer shortcuts bridge orders and fills them directly
contract FillQuoteTransformer is Transformer {
contract FillQuoteTransformer is
Transformer
{
using LibERC20TokenV06 for IERC20TokenV06;
using LibERC20Transformer for IERC20TokenV06;
using LibSafeMathV06 for uint256;
@@ -51,8 +52,7 @@ contract FillQuoteTransformer is Transformer {
enum OrderType {
Bridge,
Limit,
Rfq,
Otc
Rfq
}
struct LimitOrderInfo {
@@ -69,13 +69,6 @@ contract FillQuoteTransformer is Transformer {
uint256 maxTakerTokenFillAmount;
}
struct OtcOrderInfo {
LibNativeOrder.OtcOrder order;
LibSignature.Signature signature;
// Maximum taker token amount of this limit order to fill.
uint256 maxTakerTokenFillAmount;
}
/// @dev Transform data to ABI-encode and pass into `transform()`.
struct TransformData {
// Whether we are performing a market sell or buy.
@@ -86,24 +79,26 @@ contract FillQuoteTransformer is Transformer {
// The token being bought.
// This should be an actual token, not the ETH pseudo-token.
IERC20TokenV06 buyToken;
// External liquidity bridge orders. Sorted by fill sequence.
IBridgeAdapter.BridgeOrder[] bridgeOrders;
// Native limit orders. Sorted by fill sequence.
LimitOrderInfo[] limitOrders;
// Native RFQ orders. Sorted by fill sequence.
RfqOrderInfo[] rfqOrders;
// Otc orders.
OtcOrderInfo[] otcOrders;
// The sequence to fill the orders in. Each item will fill the next
// order of that type in either `bridgeOrders`, `limitOrders`,
// `rfqOrders`, or `otcOrders.`
// or `rfqOrders.`
OrderType[] fillSequence;
// Amount of `sellToken` to sell or `buyToken` to buy.
// For sells, setting the high-bit indicates that
// `sellAmount & LOW_BITS` should be treated as a `1e18` fraction of
// the current balance of `sellToken`, where
// `1e18+ == 100%` and `0.5e18 == 50%`, etc.
uint256 fillAmount;
// Who to transfer unused protocol fees to.
// May be a valid address or one of:
// `address(0)`: Stay in flash wallet.
@@ -128,7 +123,7 @@ contract FillQuoteTransformer is Transformer {
uint256 soldAmount;
uint256 protocolFee;
uint256 takerTokenBalanceRemaining;
uint256[4] currentIndices;
uint256[3] currentIndices;
OrderType currentOrderType;
}
@@ -138,7 +133,7 @@ contract FillQuoteTransformer is Transformer {
event ProtocolFeeUnfunded(bytes32 orderHash);
/// @dev The highest bit of a uint256 value.
uint256 private constant HIGH_BIT = 2**255;
uint256 private constant HIGH_BIT = 2 ** 255;
/// @dev Mask of the lower 255 bits of a uint256 value.
uint256 private constant LOWER_255_BITS = HIGH_BIT - 1;
/// @dev If `refundReceiver` is set to this address, unpsent
@@ -152,12 +147,15 @@ contract FillQuoteTransformer is Transformer {
IBridgeAdapter public immutable bridgeAdapter;
/// @dev The exchange proxy contract.
IZeroEx public immutable zeroEx;
INativeOrdersFeature public immutable zeroEx;
/// @dev Create this contract.
/// @param bridgeAdapter_ The bridge adapter contract.
/// @param zeroEx_ The Exchange Proxy contract.
constructor(IBridgeAdapter bridgeAdapter_, IZeroEx zeroEx_) public Transformer() {
constructor(IBridgeAdapter bridgeAdapter_, INativeOrdersFeature zeroEx_)
public
Transformer()
{
bridgeAdapter = bridgeAdapter_;
zeroEx = zeroEx_;
}
@@ -167,27 +165,30 @@ contract FillQuoteTransformer is Transformer {
/// to this call. `buyToken` and excess ETH will be transferred back to the caller.
/// @param context Context information.
/// @return magicBytes The success bytes (`LibERC20Transformer.TRANSFORMER_SUCCESS`).
function transform(TransformContext calldata context) external override returns (bytes4 magicBytes) {
function transform(TransformContext calldata context)
external
override
returns (bytes4 magicBytes)
{
TransformData memory data = abi.decode(context.data, (TransformData));
FillState memory state;
// Validate data fields.
if (data.sellToken.isTokenETH() || data.buyToken.isTokenETH()) {
LibTransformERC20RichErrors
.InvalidTransformDataError(
LibTransformERC20RichErrors.InvalidTransformDataErrorCode.INVALID_TOKENS,
context.data
)
.rrevert();
LibTransformERC20RichErrors.InvalidTransformDataError(
LibTransformERC20RichErrors.InvalidTransformDataErrorCode.INVALID_TOKENS,
context.data
).rrevert();
}
if (data.bridgeOrders.length + data.limitOrders.length + data.rfqOrders.length != data.fillSequence.length) {
LibTransformERC20RichErrors
.InvalidTransformDataError(
LibTransformERC20RichErrors.InvalidTransformDataErrorCode.INVALID_ARRAY_LENGTH,
context.data
)
.rrevert();
if (data.bridgeOrders.length
+ data.limitOrders.length
+ data.rfqOrders.length != data.fillSequence.length
) {
LibTransformERC20RichErrors.InvalidTransformDataError(
LibTransformERC20RichErrors.InvalidTransformDataErrorCode.INVALID_ARRAY_LENGTH,
context.data
).rrevert();
}
state.takerTokenBalanceRemaining = data.sellToken.getTokenBalanceOf(address(this));
@@ -201,7 +202,8 @@ contract FillQuoteTransformer is Transformer {
data.sellToken.approveIfBelow(address(zeroEx), data.fillAmount);
// Compute the protocol fee if a limit order is present.
if (data.limitOrders.length != 0) {
state.protocolFee = uint256(zeroEx.getProtocolFeeMultiplier()).safeMul(tx.gasprice);
state.protocolFee = uint256(zeroEx.getProtocolFeeMultiplier())
.safeMul(tx.gasprice);
}
}
@@ -212,14 +214,10 @@ contract FillQuoteTransformer is Transformer {
// Check if we've hit our targets.
if (data.side == Side.Sell) {
// Market sell check.
if (state.soldAmount >= data.fillAmount) {
break;
}
if (state.soldAmount >= data.fillAmount) { break; }
} else {
// Market buy check.
if (state.boughtAmount >= data.fillAmount) {
break;
}
if (state.boughtAmount >= data.fillAmount) { break; }
}
state.currentOrderType = OrderType(data.fillSequence[i]);
@@ -232,17 +230,19 @@ contract FillQuoteTransformer is Transformer {
results = _fillLimitOrder(data.limitOrders[orderIndex], data, state);
} else if (state.currentOrderType == OrderType.Rfq) {
results = _fillRfqOrder(data.rfqOrders[orderIndex], data, state);
} else if (state.currentOrderType == OrderType.Otc) {
results = _fillOtcOrder(data.otcOrders[orderIndex], data, state);
} else {
revert('INVALID_ORDER_TYPE');
revert("INVALID_ORDER_TYPE");
}
// Accumulate totals.
state.soldAmount = state.soldAmount.safeAdd(results.takerTokenSoldAmount);
state.boughtAmount = state.boughtAmount.safeAdd(results.makerTokenBoughtAmount);
state.ethRemaining = state.ethRemaining.safeSub(results.protocolFeePaid);
state.takerTokenBalanceRemaining = state.takerTokenBalanceRemaining.safeSub(results.takerTokenSoldAmount);
state.soldAmount = state.soldAmount
.safeAdd(results.takerTokenSoldAmount);
state.boughtAmount = state.boughtAmount
.safeAdd(results.makerTokenBoughtAmount);
state.ethRemaining = state.ethRemaining
.safeSub(results.protocolFeePaid);
state.takerTokenBalanceRemaining = state.takerTokenBalanceRemaining
.safeSub(results.takerTokenSoldAmount);
state.currentIndices[uint256(state.currentOrderType)]++;
}
@@ -251,15 +251,21 @@ contract FillQuoteTransformer is Transformer {
// Market sell check.
if (state.soldAmount < data.fillAmount) {
LibTransformERC20RichErrors
.IncompleteFillSellQuoteError(address(data.sellToken), state.soldAmount, data.fillAmount)
.rrevert();
.IncompleteFillSellQuoteError(
address(data.sellToken),
state.soldAmount,
data.fillAmount
).rrevert();
}
} else {
// Market buy check.
if (state.boughtAmount < data.fillAmount) {
LibTransformERC20RichErrors
.IncompleteFillBuyQuoteError(address(data.buyToken), state.boughtAmount, data.fillAmount)
.rrevert();
.IncompleteFillBuyQuoteError(
address(data.buyToken),
state.boughtAmount,
data.fillAmount
).rrevert();
}
}
@@ -267,13 +273,13 @@ contract FillQuoteTransformer is Transformer {
if (state.ethRemaining > 0 && data.refundReceiver != address(0)) {
bool transferSuccess;
if (data.refundReceiver == REFUND_RECEIVER_RECIPIENT) {
(transferSuccess, ) = context.recipient.call{ value: state.ethRemaining }('');
(transferSuccess,) = context.recipient.call{value: state.ethRemaining}("");
} else if (data.refundReceiver == REFUND_RECEIVER_SENDER) {
(transferSuccess, ) = context.sender.call{ value: state.ethRemaining }('');
(transferSuccess,) = context.sender.call{value: state.ethRemaining}("");
} else {
(transferSuccess, ) = data.refundReceiver.call{ value: state.ethRemaining }('');
(transferSuccess,) = data.refundReceiver.call{value: state.ethRemaining}("");
}
require(transferSuccess, 'FillQuoteTransformer/ETHER_TRANSFER_FALIED');
require(transferSuccess, "FillQuoteTransformer/ETHER_TRANSFER_FALIED");
}
return LibERC20Transformer.TRANSFORMER_SUCCESS;
}
@@ -283,7 +289,10 @@ contract FillQuoteTransformer is Transformer {
IBridgeAdapter.BridgeOrder memory order,
TransformData memory data,
FillState memory state
) private returns (FillOrderResults memory results) {
)
private
returns (FillOrderResults memory results)
{
uint256 takerTokenFillAmount = _computeTakerTokenFillAmount(
data,
state,
@@ -312,7 +321,10 @@ contract FillQuoteTransformer is Transformer {
LimitOrderInfo memory orderInfo,
TransformData memory data,
FillState memory state
) private returns (FillOrderResults memory results) {
)
private
returns (FillOrderResults memory results)
{
uint256 takerTokenFillAmount = LibSafeMathV06.min256(
_computeTakerTokenFillAmount(
data,
@@ -332,21 +344,22 @@ contract FillQuoteTransformer is Transformer {
}
try
zeroEx.fillLimitOrder{ value: state.protocolFee }(
orderInfo.order,
orderInfo.signature,
takerTokenFillAmount.safeDowncastToUint128()
)
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) {
zeroEx.fillLimitOrder
{value: state.protocolFee}
(
orderInfo.order,
orderInfo.signature,
takerTokenFillAmount.safeDowncastToUint128()
)
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount)
{
if (orderInfo.order.takerTokenFeeAmount > 0) {
takerTokenFilledAmount = takerTokenFilledAmount.safeAdd128(
LibMathV06
.getPartialAmountFloor(
takerTokenFilledAmount,
orderInfo.order.takerAmount,
orderInfo.order.takerTokenFeeAmount
)
.safeDowncastToUint128()
LibMathV06.getPartialAmountFloor(
takerTokenFilledAmount,
orderInfo.order.takerAmount,
orderInfo.order.takerTokenFeeAmount
).safeDowncastToUint128()
);
}
results.takerTokenSoldAmount = takerTokenFilledAmount;
@@ -360,34 +373,30 @@ contract FillQuoteTransformer is Transformer {
RfqOrderInfo memory orderInfo,
TransformData memory data,
FillState memory state
) private returns (FillOrderResults memory results) {
)
private
returns (FillOrderResults memory results)
{
uint256 takerTokenFillAmount = LibSafeMathV06.min256(
_computeTakerTokenFillAmount(data, state, orderInfo.order.takerAmount, orderInfo.order.makerAmount, 0),
_computeTakerTokenFillAmount(
data,
state,
orderInfo.order.takerAmount,
orderInfo.order.makerAmount,
0
),
orderInfo.maxTakerTokenFillAmount
);
try
zeroEx.fillRfqOrder(orderInfo.order, orderInfo.signature, takerTokenFillAmount.safeDowncastToUint128())
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) {
results.takerTokenSoldAmount = takerTokenFilledAmount;
results.makerTokenBoughtAmount = makerTokenFilledAmount;
} catch {}
}
// Fill a single OTC order.
function _fillOtcOrder(
OtcOrderInfo memory orderInfo,
TransformData memory data,
FillState memory state
) private returns (FillOrderResults memory results) {
uint256 takerTokenFillAmount = LibSafeMathV06.min256(
_computeTakerTokenFillAmount(data, state, orderInfo.order.takerAmount, orderInfo.order.makerAmount, 0),
orderInfo.maxTakerTokenFillAmount
);
try
zeroEx.fillOtcOrder(orderInfo.order, orderInfo.signature, takerTokenFillAmount.safeDowncastToUint128())
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount) {
zeroEx.fillRfqOrder
(
orderInfo.order,
orderInfo.signature,
takerTokenFillAmount.safeDowncastToUint128()
)
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount)
{
results.takerTokenSoldAmount = takerTokenFilledAmount;
results.makerTokenBoughtAmount = makerTokenFilledAmount;
} catch {}
@@ -400,7 +409,11 @@ contract FillQuoteTransformer is Transformer {
uint256 orderTakerAmount,
uint256 orderMakerAmount,
uint256 orderTakerTokenFeeAmount
) private pure returns (uint256 takerTokenFillAmount) {
)
private
pure
returns (uint256 takerTokenFillAmount)
{
if (data.side == Side.Sell) {
takerTokenFillAmount = data.fillAmount.safeSub(state.soldAmount);
if (orderTakerTokenFeeAmount != 0) {
@@ -410,31 +423,34 @@ contract FillQuoteTransformer is Transformer {
orderTakerAmount
);
}
} else {
// Buy
} else { // Buy
takerTokenFillAmount = LibMathV06.getPartialAmountCeil(
data.fillAmount.safeSub(state.boughtAmount),
orderMakerAmount,
orderTakerAmount
);
}
return
LibSafeMathV06.min256(
LibSafeMathV06.min256(takerTokenFillAmount, orderTakerAmount),
state.takerTokenBalanceRemaining
);
return LibSafeMathV06.min256(
LibSafeMathV06.min256(takerTokenFillAmount, orderTakerAmount),
state.takerTokenBalanceRemaining
);
}
// Convert possible proportional values to absolute quantities.
function _normalizeFillAmount(uint256 rawAmount, uint256 balance) private pure returns (uint256 normalized) {
function _normalizeFillAmount(uint256 rawAmount, uint256 balance)
private
pure
returns (uint256 normalized)
{
if ((rawAmount & HIGH_BIT) == HIGH_BIT) {
// If the high bit of `rawAmount` is set then the lower 255 bits
// specify a fraction of `balance`.
return
LibSafeMathV06.min256(
(balance * LibSafeMathV06.min256(rawAmount & LOWER_255_BITS, 1e18)) / 1e18,
balance
);
return LibSafeMathV06.min256(
balance
* LibSafeMathV06.min256(rawAmount & LOWER_255_BITS, 1e18)
/ 1e18,
balance
);
}
return rawAmount;
}

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

@@ -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,54 +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/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,
MixinPlatypus,
MixinShell,
MixinUniswap,
MixinUniswapV2,
@@ -76,42 +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()
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,
@@ -119,6 +104,7 @@ contract BridgeAdapter is
order.bridgeData
);
} else if (protocolId == BridgeProtocols.CURVEV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeCurveV2(
sellToken,
buyToken,
@@ -126,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,
@@ -145,6 +134,7 @@ contract BridgeAdapter is
order.bridgeData
);
} else if (protocolId == BridgeProtocols.BALANCER) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeBalancer(
sellToken,
buyToken,
@@ -152,6 +142,7 @@ contract BridgeAdapter is
order.bridgeData
);
} else if (protocolId == BridgeProtocols.BALANCERV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeBalancerV2(
sellToken,
buyToken,
@@ -159,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,
@@ -171,6 +164,7 @@ contract BridgeAdapter is
order.bridgeData
);
} else if (protocolId == BridgeProtocols.MOONISWAP) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeMooniswap(
sellToken,
buyToken,
@@ -178,6 +172,7 @@ contract BridgeAdapter is
order.bridgeData
);
} else if (protocolId == BridgeProtocols.MSTABLE) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeMStable(
sellToken,
buyToken,
@@ -185,6 +180,7 @@ contract BridgeAdapter is
order.bridgeData
);
} else if (protocolId == BridgeProtocols.SHELL) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeShell(
sellToken,
buyToken,
@@ -192,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,
@@ -235,6 +238,7 @@ contract BridgeAdapter is
order.bridgeData
);
} else if (protocolId == BridgeProtocols.AAVEV2) {
if (dryRun) { return (0, true); }
boughtAmount = _tradeAaveV2(
sellToken,
buyToken,
@@ -242,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

@@ -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,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|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|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,8 +83,7 @@
},
"dependencies": {
"@0x/base-contract": "^6.5.0",
"@0x/contracts-utils": "^4.8.12",
"@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,6 +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 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';
@@ -136,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';
@@ -307,14 +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,
MixinBancorV3: MixinBancorV3 as ContractArtifact,
MixinCompound: MixinCompound as ContractArtifact,
MixinCryptoCom: MixinCryptoCom as ContractArtifact,
MixinCurve: MixinCurve as ContractArtifact,

View File

@@ -16,8 +16,6 @@ import {
FillQuoteTransformerSide as Side,
LimitOrder,
LimitOrderFields,
OtcOrder,
OtcOrderFields,
RfqOrder,
RfqOrderFields,
Signature,
@@ -28,11 +26,10 @@ import * as _ from 'lodash';
import { artifacts } from '../artifacts';
import { TestFillQuoteTransformerBridgeContract } from '../generated-wrappers/test_fill_quote_transformer_bridge';
import { getRandomLimitOrder, getRandomRfqOrder, getRandomOtcOrder } from '../utils/orders';
import { getRandomLimitOrder, getRandomRfqOrder } from '../utils/orders';
import {
BridgeAdapterContract,
EthereumBridgeAdapterContract,
FillQuoteTransformerContract,
OtcOrdersFeatureContract,
TestFillQuoteTransformerExchangeContract,
TestFillQuoteTransformerHostContract,
TestMintableERC20TokenContract,
@@ -55,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');
@@ -67,22 +65,13 @@ 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,
NULL_ADDRESS,
);
const otcOrder = await OtcOrdersFeatureContract.deployFrom0xArtifactAsync(
artifacts.OtcOrdersFeature,
env.provider,
env.txDefaults,
artifacts,
NULL_ADDRESS,
NULL_ADDRESS, // weth
);
transformer = await FillQuoteTransformerContract.deployFrom0xArtifactAsync(
artifacts.FillQuoteTransformer,
env.provider,
@@ -90,7 +79,6 @@ blockchainTests.resets('FillQuoteTransformer', env => {
artifacts,
bridgeAdapter.address,
exchange.address,
otcOrder.address
);
host = await TestFillQuoteTransformerHostContract.deployFrom0xArtifactAsync(
artifacts.TestFillQuoteTransformerHost,
@@ -154,18 +142,6 @@ blockchainTests.resets('FillQuoteTransformer', env => {
};
}
function createOTCBridgeOrder(fields: Partial<OtcOrderFields> = {}): OtcOrder {
return getRandomOtcOrder({
makerToken: makerToken.address,
takerToken: takerToken.address,
makerAmount: getRandomInteger('0.1e18', '1e18'),
takerAmount: getRandomInteger('0.1e18', '1e18'),
maker,
taker,
...fields,
});
}
function createOrderSignature(preFilledTakerAmount: Numberish = 0): Signature {
return {
// The r field of the signature is the pre-filled amount.
@@ -296,24 +272,6 @@ blockchainTests.resets('FillQuoteTransformer', env => {
};
}
function fillOtcOrder(oi: FillQuoteTransformerRfqOrderInfo): FillOrderResults {
const preFilledTakerAmount = orderSignatureToPreFilledTakerAmount(oi.signature);
if (preFilledTakerAmount.gte(oi.order.takerAmount) || preFilledTakerAmount.eq(REVERT_AMOUNT)) {
return EMPTY_FILL_ORDER_RESULTS;
}
const takerTokenFillAmount = BigNumber.min(
computeTakerTokenFillAmount(oi.order.takerAmount, oi.order.makerAmount),
oi.order.takerAmount.minus(preFilledTakerAmount),
oi.maxTakerTokenFillAmount,
);
const fillRatio = takerTokenFillAmount.div(oi.order.takerAmount);
return {
...EMPTY_FILL_ORDER_RESULTS,
takerTokenSoldAmount: takerTokenFillAmount,
makerTokenBoughtAmount: fillRatio.times(oi.order.makerAmount).integerValue(BigNumber.ROUND_DOWN),
};
}
// tslint:disable-next-line: prefer-for-of
for (let i = 0; i < data.fillSequence.length; ++i) {
const orderType = data.fillSequence[i];

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,6 +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_bancor_v3';
export * from '../test/generated-wrappers/mixin_compound';
export * from '../test/generated-wrappers/mixin_crypto_com';
export * from '../test/generated-wrappers/mixin_curve';
@@ -134,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,6 +145,7 @@
"test/generated-artifacts/MixinBalancerV2.json",
"test/generated-artifacts/MixinBalancerV2Batch.json",
"test/generated-artifacts/MixinBancor.json",
"test/generated-artifacts/MixinBancorV3.json",
"test/generated-artifacts/MixinCompound.json",
"test/generated-artifacts/MixinCryptoCom.json",
"test/generated-artifacts/MixinCurve.json",
@@ -167,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

@@ -2,11 +2,20 @@
{
"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",

View File

@@ -5,6 +5,12 @@ 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)

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,6 +24,7 @@ import "./BalancerSampler.sol";
import "./BalancerV2Sampler.sol";
import "./BalancerV2BatchSampler.sol";
import "./BancorSampler.sol";
import "./BancorV3Sampler.sol";
import "./CompoundSampler.sol";
import "./CurveSampler.sol";
import "./DODOSampler.sol";
@@ -51,6 +52,7 @@ contract ERC20BridgeSampler is
BalancerV2Sampler,
BalancerV2BatchSampler,
BancorSampler,
BancorV3Sampler,
CompoundSampler,
CurveSampler,
DODOSampler,

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,6 +1,6 @@
{
"name": "@0x/asset-swapper",
"version": "16.60.1",
"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|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",
"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,15 +61,14 @@
"dependencies": {
"@0x/assert": "^3.0.34",
"@0x/base-contract": "^6.5.0",
"@0x/contract-addresses": "^6.16.0",
"@0x/contract-wrappers": "^13.20.4",
"@0x/contracts-erc20": "^3.3.32",
"@0x/contracts-test-utils": "^5.4.23",
"@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",
@@ -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

@@ -42,7 +42,6 @@ import {
FinalUniswapV3FillData,
LiquidityProviderFillData,
MooniswapFillData,
NativeOtcOrderFillData,
NativeRfqOrderFillData,
OptimizedMarketBridgeOrder,
OptimizedMarketOrder,
@@ -378,66 +377,7 @@ export class ExchangeProxySwapQuoteConsumer implements SwapQuoteConsumerBase {
gasOverhead: ZERO_AMOUNT,
};
}
if (
// select for all chains OtcOrders exists on
[ChainId.Mainnet].includes(this.chainId) &&
quote.orders.length == 1 &&
quote.orders.every(o => o.type === FillQuoteTransformerOrderType.Otc) &&
!requiresTransformERC20(optsWithDefaults)
) {
const otcOrdersData = quote.orders.map(o => o.fillData as NativeOtcOrderFillData);
const fillAmountPerOrder = (() => {
// Don't think order taker amounts are clipped to actual sell amount
// (the last one might be too large) so figure them out manually.
let remaining = sellAmount;
const fillAmounts = [];
for (const o of quote.orders) {
const fillAmount = BigNumber.min(o.takerAmount, remaining);
fillAmounts.push(fillAmount);
remaining = remaining.minus(fillAmount);
}
return fillAmounts;
})();
// grab the amount to fill on each OtcOrder (if more than 1)
let calldata;
if(isFromETH){
calldata = this._exchangeProxy.fillOtcOrderWithEth(
otcOrdersData[0].order, otcOrdersData[0].signature
).getABIEncodedTransactionData();
}
if(isToETH){
calldata = this._exchangeProxy.fillOtcOrderForEth(
otcOrdersData[0].order, otcOrdersData[0].signature, fillAmountPerOrder[0]
).getABIEncodedTransactionData();
}
else{
calldata = this._exchangeProxy.fillOtcOrder(
otcOrdersData[0].order, otcOrdersData[0].signature, fillAmountPerOrder[0]
).getABIEncodedTransactionData();
}
if (
this.chainId === ChainId.Mainnet &&
isMultiplexBatchFillCompatible(quote, optsWithDefaults)) {
// return {
// calldataHexString: this._encodeMultiplexBatchFillCalldata(
// ...
// };
}
// if isToETH
// encode for fillOtcOrderForEth
// if isFromETH
// encode for fillOtcOrderWithEth
// else
// fillOtcOrder
// contracts/zero-ex/contracts/src/features/OtcOrdersFeature.sol
// if more than 1 OTCOrder, bail and use the BatchMultiPlex encode below
}
if (this.chainId === ChainId.Mainnet && isMultiplexBatchFillCompatible(quote, optsWithDefaults)) {
return {
calldataHexString: this._encodeMultiplexBatchFillCalldata(

View File

@@ -5,7 +5,6 @@ import {
LimitOrderFields,
RfqOrder,
RfqOrderFields,
OtcOrderFields,
Signature,
} from '@0x/protocol-utils';
import { TakerRequestQueryParamsUnnested, V4SignedRfqOrder } from '@0x/quote-server';
@@ -35,11 +34,11 @@ export interface OrderPrunerOpts {
export interface SignedOrder<T> {
order: T;
type: FillQuoteTransformerOrderType.Limit | FillQuoteTransformerOrderType.Rfq | FillQuoteTransformerOrderType.Otc;
type: FillQuoteTransformerOrderType.Limit | FillQuoteTransformerOrderType.Rfq;
signature: Signature;
}
export type SignedNativeOrder = SignedOrder<LimitOrderFields> | SignedOrder<RfqOrderFields> | SignedOrder<OtcOrderFields>;
export type SignedNativeOrder = SignedOrder<LimitOrderFields> | SignedOrder<RfqOrderFields>;
export type NativeOrderWithFillableAmounts = SignedNativeOrder & NativeOrderFillableAmountFields;
/**

View File

@@ -1,4 +1,4 @@
import { OtcOrder, RfqOrder, Signature } from '@0x/protocol-utils';
import { RfqOrder, Signature } from '@0x/protocol-utils';
import { BigNumber } from '@0x/utils';
import { AltRfqMakerAssetOfferings } from '../types';
@@ -43,48 +43,6 @@ export interface RfqClientV1QuoteResponse {
quotes: RfqClientV1Quote[];
}
export interface RfqClientV2PriceRequest {
assetFillAmount: BigNumber;
chainId: number;
comparisonPrice: BigNumber | undefined;
integratorId: string;
intentOnFilling: boolean;
makerToken: string;
marketOperation: 'Sell' | 'Buy';
takerAddress: string;
takerToken: string;
txOrigin: string;
}
export interface RfqClientV2QuoteRequest extends RfqClientV2PriceRequest {}
export interface RfqClientV2Price {
expiry: BigNumber;
maker: string;
makerAmount: BigNumber;
makerToken: string;
makerUri: string;
takerAmount: BigNumber;
takerToken: string;
}
export interface RfqClientV2PriceResponse {
prices: RfqClientV2Price[];
}
export interface RfqClientV2Quote {
makerUri: string;
order: OtcOrder;
signature: Signature;
fillableMakerAmount: BigNumber;
fillableTakerAmount: BigNumber;
fillableTakerFeeAmount: BigNumber;
}
export interface RfqClientV2QuoteResponse {
quotes: RfqClientV2Quote[];
}
/**
* IRfqClient is an interface that defines how to connect with an Rfq system.
*/
@@ -98,14 +56,4 @@ export interface IRfqClient {
* Fetches a list of "firm quotes" or signed quotes from a remote Rfq server.
*/
getV1QuotesAsync(request: RfqClientV1QuoteRequest): Promise<RfqClientV1QuoteResponse>;
/**
* Fetches a list of "v2 indicative quotes" or prices from a remote Rfq server
*/
getV2PricesAsync(request: RfqClientV2PriceRequest): Promise<RfqClientV2PriceResponse>;
/**
* Fetches a list of "v2 firm quotes" or signed quotes from a remote Rfq server.
*/
getV2QuotesAsync(request: RfqClientV2QuoteRequest): Promise<RfqClientV2QuoteResponse>;
}

View File

@@ -29,6 +29,7 @@ import {
JETSWAP_ROUTER_BY_CHAIN_ID,
JULSWAP_ROUTER_BY_CHAIN_ID,
MAX_DODOV2_POOLS_QUERIED,
MESHSWAP_ROUTER_BY_CHAIN_ID,
MOBIUSMONEY_CELO_INFOS,
MORPHEUSSWAP_ROUTER_BY_CHAIN_ID,
MSTABLE_POOLS_BY_CHAIN_ID,
@@ -543,7 +544,8 @@ export function uniswapV2LikeRouterAddress(
| ERC20BridgeSource.SpookySwap
| ERC20BridgeSource.SpiritSwap
| ERC20BridgeSource.BiSwap
| ERC20BridgeSource.Yoshi,
| ERC20BridgeSource.Yoshi
| ERC20BridgeSource.MeshSwap,
): string {
switch (source) {
case ERC20BridgeSource.UniswapV2:
@@ -596,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,6 +22,7 @@ import {
GeistFillData,
GetMarketOrdersOpts,
isFinalUniswapV3FillData,
LidoFillData,
LidoInfo,
LiquidityProviderFillData,
LiquidityProviderRegistry,
@@ -83,6 +84,7 @@ export const SELL_SOURCE_FILTER_BY_CHAIN_ID = valueByChainId<SourceFilters>(
ERC20BridgeSource.Balancer,
ERC20BridgeSource.BalancerV2,
ERC20BridgeSource.Bancor,
ERC20BridgeSource.BancorV3,
ERC20BridgeSource.MStable,
ERC20BridgeSource.Mooniswap,
ERC20BridgeSource.SushiSwap,
@@ -169,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,
@@ -227,6 +230,7 @@ export const BUY_SOURCE_FILTER_BY_CHAIN_ID = valueByChainId<SourceFilters>(
ERC20BridgeSource.Balancer,
ERC20BridgeSource.BalancerV2,
// ERC20BridgeSource.Bancor, // FIXME: Bancor Buys not implemented in Sampler
ERC20BridgeSource.BancorV3,
ERC20BridgeSource.MStable,
ERC20BridgeSource.Mooniswap,
ERC20BridgeSource.Shell,
@@ -288,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([
@@ -314,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,
@@ -449,6 +453,7 @@ export const MAINNET_TOKENS = {
sEUR: '0xd71ecff9342a5ced620049e616c5035f1db98620',
sETH: '0x5e74c9036fb86bd7ecdcb084a0673efc32ea31cb',
stETH: '0xae7ab96520de3a18e5e111b5eaab095312d7fe84',
wstETH: '0x7f39c581f595b53c5cb19bd0b3f8da6c935e2ca0',
LINK: '0x514910771af9ca656af840dff83e8264ecf986ca',
MANA: '0x0f5d2fb29fb7d3cfee444a200298f468908cc942',
KNC: '0xdefa4e8a7bcba345f687a2f1456f5edd9ce97202',
@@ -641,7 +646,6 @@ export const OPTIMISM_TOKENS = {
WBTC: '0x68f180fcce6836688e9084f035309e29bf0a2095',
nETH: '0x809dc529f07651bd43a172e8db6f4a7a0d771036',
sWETH: '0x121ab82b49b2bc4c7901ca46b8277962b4350204',
nUSD: '0x67C10C397dD0Ba417329543c1a40eb48AAa7cd00',
};
export const CURVE_POOLS = {
@@ -771,7 +775,6 @@ export const SYNAPSE_MAINNET_POOLS = {
export const SYNAPSE_OPTIMISM_POOLS = {
nETHLP: '0xe27bff97ce92c3e1ff7aa9f86781fdd6d48f5ee9',
nUSDLP: '0xF44938b0125A6662f9536281aD2CD6c499F22004',
};
export const SYNAPSE_BSC_POOLS = {
@@ -785,7 +788,6 @@ export const SYNAPSE_POLYGON_POOLS = {
export const SYNAPSE_FANTOM_POOLS = {
nUSDLP: '0x2913e812cf0dcca30fb28e6cac3d2dcff4497688',
nETHLP: '0x8d9ba570d6cb60c7e3e0f31343efe75ab8e65fb1',
fUSDTLP: '0x85662fd123280827e11c59973ac9fcbe838dc3b4',
};
export const SYNAPSE_AVALANCHE_POOLS = {
@@ -935,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(),
@@ -1657,24 +1663,6 @@ export const SYNAPSE_FANTOM_INFOS: { [name: string]: CurveInfo } = {
metaTokens: undefined,
gasSchedule: 140e3,
},
[SYNAPSE_FANTOM_POOLS.fUSDTLP]: {
exchangeFunctionSelector: CurveFunctionSelectors.swap,
sellQuoteFunctionSelector: CurveFunctionSelectors.calculateSwap,
buyQuoteFunctionSelector: CurveFunctionSelectors.None,
poolAddress: SYNAPSE_FANTOM_POOLS.fUSDTLP,
tokens: [FANTOM_TOKENS.USDC, FANTOM_TOKENS.fUSDT, FANTOM_TOKENS.nUSD],
metaTokens: undefined,
gasSchedule: 140e3,
},
[SYNAPSE_FANTOM_POOLS.nETHLP]: {
exchangeFunctionSelector: CurveFunctionSelectors.swap,
sellQuoteFunctionSelector: CurveFunctionSelectors.calculateSwap,
buyQuoteFunctionSelector: CurveFunctionSelectors.None,
poolAddress: SYNAPSE_FANTOM_POOLS.nETHLP,
tokens: [FANTOM_TOKENS.WETH, FANTOM_TOKENS.nETH],
metaTokens: undefined,
gasSchedule: 140e3,
},
};
export const SYNAPSE_MAINNET_INFOS: { [name: string]: CurveInfo } = {
@@ -1699,15 +1687,6 @@ export const SYNAPSE_OPTIMISM_INFOS: { [name: string]: CurveInfo } = {
metaTokens: undefined,
gasSchedule: 140e3,
},
[SYNAPSE_OPTIMISM_POOLS.nUSDLP]: {
exchangeFunctionSelector: CurveFunctionSelectors.swap,
sellQuoteFunctionSelector: CurveFunctionSelectors.calculateSwap,
buyQuoteFunctionSelector: CurveFunctionSelectors.None,
poolAddress: SYNAPSE_OPTIMISM_POOLS.nUSDLP,
tokens: [OPTIMISM_TOKENS.nUSD, OPTIMISM_TOKENS.USDC],
metaTokens: undefined,
gasSchedule: 140e3,
},
};
export const SYNAPSE_POLYGON_INFOS: { [name: string]: CurveInfo } = {
@@ -2081,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]: {
@@ -2156,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,
},
@@ -2317,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',
@@ -2516,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;
@@ -2555,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
@@ -2597,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

@@ -747,26 +747,6 @@ export class MarketOperationUtils {
wholeOrderPrice,
rfqt,
);
const otcQuotes = await rfqt.rfqClient?.getV2QuotesAsync({
assetFillAmount: amount,
chainId: this._sampler.chainId,
integratorId: rfqt.integrator.integratorId,
intentOnFilling: rfqt.intentOnFilling,
makerToken,
marketOperation: side,
takerAddress: rfqt.takerAddress,
takerToken,
txOrigin: rfqt.txOrigin,
});
const otcQuotesWithFillableAmounts: NativeOrderWithFillableAmounts[] =
otcQuotes === undefined
? []
: otcQuotes.quotes.map(q => ({
...q,
type: FillQuoteTransformerOrderType.Otc,
}));
const deltaTime = new Date().getTime() - timeStart;
DEFAULT_INFO_LOGGER({
rfqQuoteType: 'firm',
@@ -797,7 +777,6 @@ export class MarketOperationUtils {
);
marketSideLiquidity.quotes.nativeOrders = [
...quotesWithOrderFillableAmounts,
...otcQuotesWithFillableAmounts,
...marketSideLiquidity.quotes.nativeOrders,
];

View File

@@ -206,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);
}
@@ -297,6 +301,7 @@ 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;
@@ -351,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;
@@ -382,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);
}
@@ -506,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,
@@ -517,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,
@@ -568,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

@@ -25,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,
@@ -36,6 +38,7 @@ import {
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,
@@ -709,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,
@@ -1106,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,
@@ -1124,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,
@@ -1411,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 [];
@@ -1603,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: {
@@ -1677,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}`);
}
@@ -1685,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,
@@ -1732,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 [];
@@ -1924,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: {
@@ -1993,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

@@ -2,7 +2,6 @@ import {
FillQuoteTransformerLimitOrderInfo,
FillQuoteTransformerOrderType,
FillQuoteTransformerRfqOrderInfo,
FillQuoteTransformerOtcOrderInfo
} from '@0x/protocol-utils';
import { MarketOperation } from '@0x/types';
import { BigNumber } from '@0x/utils';
@@ -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;
}
/**
@@ -196,9 +198,7 @@ export interface FillData {}
// `FillData` for native fills. Represents a single native order
export type NativeRfqOrderFillData = FillQuoteTransformerRfqOrderInfo;
export type NativeLimitOrderFillData = FillQuoteTransformerLimitOrderInfo;
export type NativeOtcOrderFillData = FillQuoteTransformerOtcOrderInfo;
export type NativeFillData = NativeRfqOrderFillData | NativeLimitOrderFillData | NativeOtcOrderFillData;
export type NativeFillData = NativeRfqOrderFillData | NativeLimitOrderFillData;
// Represents an individual DEX sample from the sampler contract
export interface DexSample<TFillData extends FillData = FillData> {
@@ -264,6 +264,11 @@ export interface BancorFillData extends FillData {
networkAddress: string;
}
export interface BancorV3FillData extends FillData {
path: string[];
networkAddress: string;
}
export interface MooniswapFillData extends FillData {
poolAddress: string;
}
@@ -328,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 {
@@ -388,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;
@@ -457,19 +464,13 @@ export interface OptimizedRfqOrder extends OptimizedMarketOrderBase<NativeRfqOrd
fillData: NativeRfqOrderFillData;
}
export interface OptimizedOtcOrder extends OptimizedMarketOrderBase<NativeOtcOrderFillData> {
type: FillQuoteTransformerOrderType.Otc;
fillData: NativeOtcOrderFillData;
}
/**
* Optimized orders to fill.
*/
export type OptimizedMarketOrder =
| OptimizedMarketBridgeOrder<FillData>
| OptimizedMarketOrderBase<NativeLimitOrderFillData>
| OptimizedMarketOrderBase<NativeRfqOrderFillData>
| OptimizedMarketOrderBase<NativeOtcOrderFillData>;
| OptimizedMarketOrderBase<NativeRfqOrderFillData>;
export interface GetMarketOrdersRfqOpts extends RfqRequestOpts {
rfqClient?: IRfqClient;

View File

@@ -13,7 +13,6 @@ import {
NativeCollapsedFill,
NativeFillData,
NativeLimitOrderFillData,
NativeOtcOrderFillData,
NativeRfqOrderFillData,
RawQuotes,
} from './market_operation_utils/types';
@@ -354,7 +353,7 @@ function _isNativeOrderFromCollapsedFill(cf: CollapsedFill): cf is NativeCollaps
*/
export function nativeOrderToReportEntry(
type: FillQuoteTransformerOrderType,
fillData: NativeLimitOrderFillData | NativeRfqOrderFillData | NativeOtcOrderFillData,
fillData: NativeLimitOrderFillData | NativeRfqOrderFillData,
fillableAmount: BigNumber,
comparisonPrice?: BigNumber | undefined,
quoteRequestor?: QuoteRequestor,

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,6 +23,7 @@ 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 IMooniswap from '../test/generated-artifacts/IMooniswap.json';
@@ -57,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,
@@ -83,6 +86,7 @@ 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,
IMStable: IMStable as ContractArtifact,

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

@@ -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,6 +21,7 @@ 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_m_stable';
export * from '../test/generated-wrappers/i_mooniswap';

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,6 +24,7 @@
"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/IMStable.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];
}

View File

@@ -1,62 +0,0 @@
import { BigNumber, NULL_BYTES } from '@0x/utils';
import { ERC20Token, ERC721Token } from '../types';
export const etherTokenByChain: { [chainId: number]: { address: string } } = {
3: {
address: '0xc778417e063141139fce010982780140aa0cd5ab',
},
4: {
address: '0xc778417e063141139fce010982780140aa0cd5ab',
},
42: {
address: '0xd0a1e359811322d97991e03f863a0c30c2cf029c',
},
1337: {
address: '',
},
};
export const erc20TokenInfo: ERC20Token[] = [
{
name: 'Augur Reputation Token',
symbol: 'REP',
decimals: new BigNumber(18),
ipfsHash: NULL_BYTES,
swarmHash: NULL_BYTES,
},
{
name: 'Dai',
symbol: 'DAI',
decimals: new BigNumber(18),
ipfsHash: NULL_BYTES,
swarmHash: NULL_BYTES,
},
{
name: 'Golem Network Token',
symbol: 'GNT',
decimals: new BigNumber(18),
ipfsHash: NULL_BYTES,
swarmHash: NULL_BYTES,
},
{
name: 'MakerDAO',
symbol: 'MKR',
decimals: new BigNumber(18),
ipfsHash: NULL_BYTES,
swarmHash: NULL_BYTES,
},
{
name: 'Melon Token',
symbol: 'MLN',
decimals: new BigNumber(18),
ipfsHash: NULL_BYTES,
swarmHash: NULL_BYTES,
},
];
export const erc721TokenInfo: ERC721Token[] = [
{
name: '0xen ERC721',
symbol: '0xen',
},
];

View File

@@ -1,24 +0,0 @@
import { ChainId, getContractAddressesForChainOrThrow } from '@0x/contract-addresses';
import { devConstants, web3Factory } from '@0x/dev-utils';
import * as chai from 'chai';
import * as dirtyChai from 'dirty-chai';
import 'mocha';
import { runMigrationsAsync } from '../src/migration';
chai.use(dirtyChai);
const expect = chai.expect;
describe('addresses', () => {
it('should contain the same addresses as contract-addresses', async () => {
const providerConfigs = { shouldUseInProcessGanache: true };
const provider = web3Factory.getRpcProvider(providerConfigs);
const txDefaults = {
from: devConstants.TESTRPC_FIRST_ADDRESS,
};
const migrationAddresses = await runMigrationsAsync(provider, txDefaults);
const expectedAddresses = getContractAddressesForChainOrThrow(ChainId.Ganache);
expect(migrationAddresses).to.deep.eq(expectedAddresses);
});
});

View File

@@ -1,8 +0,0 @@
{
"extends": "../../tsconfig",
"compilerOptions": {
"outDir": "lib",
"rootDir": "."
},
"include": ["src/**/*", "test/**/*"]
}

View File

@@ -1,3 +0,0 @@
{
"extends": ["@0x/tslint-config"]
}

View File

@@ -1,7 +0,0 @@
{
"extends": "../../typedoc-tsconfig",
"compilerOptions": {
"outDir": "lib"
},
"include": ["./src/**/*", "./test/**/*"]
}

View File

@@ -1,4 +1,14 @@
[
{
"version": "11.14.0",
"changes": [
{
"note": "Adds Support for BancorV3 on Ethereum",
"pr": 492
}
],
"timestamp": 1654284040
},
{
"version": "11.13.0",
"changes": [

View File

@@ -5,6 +5,10 @@ Edit the package's CHANGELOG.json file only.
CHANGELOG
## v11.14.0 - _June 3, 2022_
* Adds Support for BancorV3 on Ethereum (#492)
## v11.13.0 - _May 19, 2022_
* Added Support for GMX and Platypus on Avalanche (#478)

View File

@@ -1,6 +1,6 @@
{
"name": "@0x/protocol-utils",
"version": "11.13.0",
"version": "11.14.0",
"engines": {
"node": ">=6.12"
},
@@ -63,8 +63,8 @@
},
"dependencies": {
"@0x/assert": "^3.0.34",
"@0x/contract-addresses": "^6.16.0",
"@0x/contract-wrappers": "^13.20.2",
"@0x/contract-addresses": "^6.15.0",
"@0x/contract-wrappers": "^13.20.3",
"@0x/json-schemas": "^6.4.4",
"@0x/subproviders": "^6.6.5",
"@0x/utils": "^6.5.3",

View File

@@ -63,7 +63,7 @@ export type LimitOrderFields = typeof LIMIT_ORDER_DEFAULT_VALUES;
export type RfqOrderFields = typeof RFQ_ORDER_DEFAULT_VALUES;
export type OtcOrderFields = typeof OTC_ORDER_DEFAULT_VALUES;
export type BridgeOrderFields = typeof BRIDGE_ORDER_DEFAULT_VALUES;
export type NativeOrder = RfqOrder | LimitOrder | OtcOrder;
export type NativeOrder = RfqOrder | LimitOrder;
export enum OrderStatus {
Invalid = 0,

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