Python doc polish (#1757)

* Exercise doctests as a test not as a linter

* Add a contract artifact doctest, and exercise it

* Clean up linter issues

* Change asset data decoding output type

Previously, it was a TypedDict, but that was causing problems.  Sphinx
seems to be broken, such that none of the fields of the class were being
rendered into the doc.

Thinking on it further, I decided that a NamedTuple makes more sense
here anyways, since tuples are immutable and this output value isn't
something someone should ever build or modify.  And, NamedTuple is
getting its fields properly rendered by Sphinx.

* Add type annotations to JSON schemas docs

* Add doc publish metadata file for middlewares pkg

* Improve documentation

Note that none of the changes to .py files impact functionality in any
way, because the changes are restricted to "docstrings", which to the
Python interpreter are simply no-op statements.

However, one caveat to that is that much of these docstring changes DO
affect the functionality of automated test runs, because all of the code
examples (blocks beginning with `>>> `) are "doctests", which are
exercised via the test framework.

The index.rst files are the top-level templates for generating the
documentation, and the "automodule"/"autoclass"/etc statements pull in
the docstrings from the source code.

* correct package name in doc URL

* Move sra_client module into zero_ex namespace

* Add functions to encode asset data to bytes

* Fix: SRA client was deserializing orders weirdly

The generated code was transforming the order structure, from the camel
case field name format in the spec, into the snake case field name
format expected by Python convention.  With this problem in place, the
only way to take an order from a relayer and send it to a contract (for
fill, cancel, etc) was to manually transform the field names, one by
one, into a new structure.

* Fix problem with Web3/JSON order conversion utils

* doctest: maker, trade ZRX for WETH, not vice versa

* Remove redundant test

* Construct order in native Python, not JSON

Then convert it to JSON before sending it to the relayer.

* doctest: simplify asset units

* Add doctests for filling and cancelling

* Minor doctetst copy edits; whitespace

* Rename function, and add optional parameter

* Tweak docstrings on JSON conversion functions.

* Demo asset data decoding to view asset pairs

* Demo selecting an order from the order book

And have taker take it.

* Rename variable

* Abstract ganache from examples

Doing that exposed excessive use of the verbose
NETWORK_TO_ADDRESSES[NetworkId.Ganache] construct, so simplified that,
which ripped into eliminating other temporary variables that had been
used to hold specific contract addresses.

Also cleaned up some misplaced import statements.

* Add missing SRA client doc publication metadata

* Ran prettier on new SRA client doc pub metadata

* Remove local env customizations in doc metadata

* Eliminate temporary variable

* Rename variable

* Show `pip install` in every package's doc

* Doc NetorkID & pagination params as int, not float

* Clean up unmatched parenthesis in docs
This commit is contained in:
F. Eugene Aumson
2019-04-30 07:44:51 -04:00
committed by GitHub
parent b896f82282
commit 0564ac1530
61 changed files with 1174 additions and 965 deletions

View File

@@ -0,0 +1,12 @@
{
"domain": "0x-sra-client-py",
"build_command": "python setup.py build_sphinx",
"upload_directory": "build/docs/html",
"index_key": "index.html",
"error_key": "index.html",
"cache": 3600,
"aws_profile": "default",
"aws_region": "us-east-1",
"cdn": false,
"dns_configured": true
}

View File

@@ -97,17 +97,20 @@ class LintCommand(distutils.command.build_py.build_py):
def run(self):
"""Run linter shell commands."""
lint_targets = "test src/zero_ex/sra_client/__init__.py setup.py"
lint_commands = [
# formatter:
"black --line-length 79 --check --diff test sra_client/__init__.py setup.py".split(), # noqa: E501 (line too long)
(
f"black --line-length 79 --check --diff test {lint_targets}"
).split(),
# style guide checker (formerly pep8):
"pycodestyle test sra_client/__init__.py setup.py".split(),
f"pycodestyle {lint_targets}".split(),
# docstring style checker:
"pydocstyle src test sra_client/__init__.py setup.py".split(),
f"pydocstyle {lint_targets}".split(),
# static type checker:
"bandit -r test sra_client/__init__.py setup.py".split(),
f"bandit -r {lint_targets}".split(),
# general linter:
"pylint test sra_client/__init__.py setup.py".split(),
f"pylint {lint_targets}".split(),
# pylint takes relatively long to run, so it runs last, to enable
# fast failures.
]
@@ -134,7 +137,7 @@ class PublishDocsCommand(distutils.command.build_py.build_py):
description = (
"Publish docs to "
+ "http://0x-sra-demos-py.s3-website-us-east-1.amazonaws.com/"
+ "http://0x-sra-client-py.s3-website-us-east-1.amazonaws.com/"
)
def run(self):
@@ -150,7 +153,9 @@ setup(
url="https://github.com/0xproject/0x-monorepo/python-packages/sra_client",
keywords=["OpenAPI", "OpenAPI-Generator", "Standard Relayer REST API"],
install_requires=REQUIRES,
packages=find_packages(),
namespace_packages=["zero_ex"],
packages=find_packages("src"),
package_dir={"": "src"},
include_package_data=True,
long_description=README_MD,
long_description_content_type="text/markdown",
@@ -183,7 +188,7 @@ setup(
},
command_options={
"build_sphinx": {
"source_dir": ("setup.py", "."),
"source_dir": ("setup.py", "src"),
"build_dir": ("setup.py", "build/docs"),
}
},

View File

@@ -1,236 +0,0 @@
# coding: utf-8
# flake8: noqa
"""Python api client to interact with SRA compatible 0x relayers.
0x Protocol is an open standard. Many relayers opt-in to implementing a set of
`standard relayer API endpoints <http://sra-spec.s3-website-us-east-1.amazonaws.com/>`_
to make it easier for anyone to source liquidity that conforms to the 0x order format.
Here, we will show you how you can use our `sra_client
<https://github.com/0xProject/0x-monorepo/tree/development/python-packages/sra_client#0x-sra-client>`_
module to interact with 0x relayers that implements the Standard Relayer API.
Setup
=====
Install the sra-client package with pip:
`pip install 0x-sra-client`:code:
To interact with a 0x Relayer, you need the HTTP endpoint of the Relayer you'd like to
connect to (i.e. https://api.radarrelay.com/0x/v2).
For local testing one can use the `0x-launch-kit
<https://github.com/0xProject/0x-launch-kit#table-of-contents/>`_
to host orders locally. For convenience, a docker container is provided
for just this purpose. To start it:
`docker run -d -p 3000:3000 0xorg/launch-kit-ci`:code:
and then connect to the http server running at http://localhost:3000.
----
Configure and create an API client instance
--------------------------------------------
>>> from sra_client import ApiClient, Configuration
>>> from sra_client.api import DefaultApi
>>> config = Configuration()
>>> config.host = "http://localhost:3000"
>>> relayer_api = DefaultApi(ApiClient(config))
Wrapping ETH
------------
>>> from web3 import HTTPProvider, Web3
>>> from zero_ex.contract_addresses import (
... NETWORK_TO_ADDRESSES, NetworkId)
>>> from zero_ex.contract_artifacts import abi_by_name
>>> provider = HTTPProvider("http://localhost:8545")
>>> maker_address = "0x5409ed021d9299bf6814279a6a1411a7e866a631"
>>> erc20_proxy = NETWORK_TO_ADDRESSES[NetworkId.GANACHE].erc20_proxy
>>> weth_address = NETWORK_TO_ADDRESSES[NetworkId.GANACHE].ether_token
>>> weth_instance = Web3(provider).eth.contract(
... address=Web3.toChecksumAddress(weth_address),
... abi=abi_by_name("WETH9"))
>>> tx = weth_instance.functions.deposit().transact(
... {"from": Web3.toChecksumAddress(maker_address), "value": 1000000000000000000})
>>> tx = weth_instance.functions.approve(
... Web3.toChecksumAddress(erc20_proxy),
... 1000000000000000000).transact(
... {"from": Web3.toChecksumAddress(maker_address)})
Post Order
-----------
Post an order to an SRA-compliant Relayer.
>>> from zero_ex.order_utils import (
... asset_data_utils,
... generate_order_hash_hex,
... jsdict_order_to_struct,
... sign_hash)
>>> exchange_address = NETWORK_TO_ADDRESSES[NetworkId.GANACHE].exchange
>>> zrx_address = NETWORK_TO_ADDRESSES[NetworkId.GANACHE].zrx_token
>>> weth_asset_data = asset_data_utils.encode_erc20_asset_data(weth_address)
>>> zrx_asset_data = asset_data_utils.encode_erc20_asset_data(zrx_address)
>>> example_order = {
... "makerAddress": maker_address,
... "takerAddress": "0x0000000000000000000000000000000000000000",
... "senderAddress": "0x0000000000000000000000000000000000000000",
... "exchangeAddress": exchange_address,
... "feeRecipientAddress":
... "0x0000000000000000000000000000000000000000",
... "makerAssetData": weth_asset_data,
... "takerAssetData": zrx_asset_data,
... "salt": "2362734632784682376287462",
... "makerFee": "0",
... "takerFee": "0",
... "makerAssetAmount": "1000000000000000000",
... "takerAssetAmount": "500000000000000000000",
... "expirationTimeSeconds": "999999999999999999999"}
>>> order_hash = generate_order_hash_hex(
... jsdict_order_to_struct(example_order), exchange_address)
>>> example_order["signature"] = sign_hash(
... provider, Web3.toChecksumAddress(maker_address), order_hash)
>>> relayer_api.post_order_with_http_info(
... network_id=50, signed_order_schema=example_order)[1]
200
Get Orders
-----------
Get orders from an SRA-compliant Relayer.
>>> relayer_api.get_orders()
{'records': [{'meta_data': {},
'order': {'exchange_address': '0x48bacb9266a570d521063ef5dd96e61686dbe788',
'expiration_time_seconds': '1000000000000000000000',
'fee_recipient_address': '0x0000000000000000000000000000000000000000',
'maker_address': '0x5409ed021d9299bf6814279a6a1411a7e866a631',
'maker_asset_amount': '1000000000000000000',
'maker_asset_data': '0xf47261b00000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082',
'maker_fee': '0',
'salt': '2362734632784682376287462',
'sender_address': '0x0000000000000000000000000000000000000000',
'taker_address': '0x0000000000000000000000000000000000000000',
'taker_asset_amount': '500000000000000000000',
'taker_asset_data': '0xf47261b0000000000000000000000000871dd7c2b4b25e1aa18728e9d5f2af4c4e431f5c',
'taker_fee': '0'}}]}
Get Order
---------
Get an order by hash from an SRA-compliant Relayer.
>>> relayer_api.get_order("0x" + order_hash)
{'meta_data': {},
'order': {'exchange_address': '0x48bacb9266a570d521063ef5dd96e61686dbe788',
'expiration_time_seconds': '1000000000000000000000',
'fee_recipient_address': '0x0000000000000000000000000000000000000000',
'maker_address': '0x5409ed021d9299bf6814279a6a1411a7e866a631',
'maker_asset_amount': '1000000000000000000',
'maker_asset_data': '0xf47261b00000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082',
'maker_fee': '0',
'salt': '2362734632784682376287462',
'sender_address': '0x0000000000000000000000000000000000000000',
'taker_address': '0x0000000000000000000000000000000000000000',
'taker_asset_amount': '500000000000000000000',
'taker_asset_data': '0xf47261b0000000000000000000000000871dd7c2b4b25e1aa18728e9d5f2af4c4e431f5c',
'taker_fee': '0'}}
Get Asset Pair
---------------
Get available asset pairs from an SRA-compliant Relayer.
>>> relayer_api.get_asset_pairs()
{'records': [{'assetDataA': {'assetData': '0xf47261b00000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082',
'maxAmount': '115792089237316195423570985008687907853269984665640564039457584007913129639936',
'minAmount': '0',
'precision': 18},
'assetDataB': {'assetData': '0xf47261b0000000000000000000000000871dd7c2b4b25e1aa18728e9d5f2af4c4e431f5c',
'maxAmount': '115792089237316195423570985008687907853269984665640564039457584007913129639936',
'minAmount': '0',
'precision': 18}}]}
Get Orderbook
-------------
Get the orderbook for the WETH/ZRX asset pair from an SRA-compliant Relayer.
>>> relayer_api.get_orderbook(
... base_asset_data=weth_asset_data,
... quote_asset_data=zrx_asset_data)
{'asks': {'records': [{'meta_data': {},
'order': {'exchange_address': '0x48bacb9266a570d521063ef5dd96e61686dbe788',
'expiration_time_seconds': '1000000000000000000000',
'fee_recipient_address': '0x0000000000000000000000000000000000000000',
'maker_address': '0x5409ed021d9299bf6814279a6a1411a7e866a631',
'maker_asset_amount': '1000000000000000000',
'maker_asset_data': '0xf47261b00000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082',
'maker_fee': '0',
'salt': '2362734632784682376287462',
'sender_address': '0x0000000000000000000000000000000000000000',
'taker_address': '0x0000000000000000000000000000000000000000',
'taker_asset_amount': '500000000000000000000',
'taker_asset_data': '0xf47261b0000000000000000000000000871dd7c2b4b25e1aa18728e9d5f2af4c4e431f5c',
'taker_fee': '0'}}]},
'bids': {'records': []}}
""" # noqa: E501 (line too long)
# NOTE: Bug in get_order method.
# Sra_client not deserialzing order from server properly, need fix!
from __future__ import absolute_import
__version__ = "1.0.0"
# import apis into sdk package
from sra_client.api.default_api import DefaultApi
# import ApiClient
from sra_client.api_client import ApiClient
from sra_client.configuration import Configuration
# import models into sdk package
from sra_client.models.order_schema import OrderSchema
from sra_client.models.paginated_collection_schema import (
PaginatedCollectionSchema,
)
from sra_client.models.relayer_api_asset_data_pairs_response_schema import (
RelayerApiAssetDataPairsResponseSchema,
)
from sra_client.models.relayer_api_asset_data_trade_info_schema import (
RelayerApiAssetDataTradeInfoSchema,
)
from sra_client.models.relayer_api_error_response_schema import (
RelayerApiErrorResponseSchema,
)
from sra_client.models.relayer_api_error_response_schema_validation_errors import ( # noqa: E501 (line too long)
RelayerApiErrorResponseSchemaValidationErrors,
)
from sra_client.models.relayer_api_fee_recipients_response_schema import (
RelayerApiFeeRecipientsResponseSchema,
)
from sra_client.models.relayer_api_order_config_payload_schema import (
RelayerApiOrderConfigPayloadSchema,
)
from sra_client.models.relayer_api_order_config_response_schema import (
RelayerApiOrderConfigResponseSchema,
)
from sra_client.models.relayer_api_order_schema import RelayerApiOrderSchema
from sra_client.models.relayer_api_orderbook_response_schema import (
RelayerApiOrderbookResponseSchema,
)
from sra_client.models.relayer_api_orders_channel_subscribe_payload_schema import ( # noqa: E501 (line too long)
RelayerApiOrdersChannelSubscribePayloadSchema,
)
from sra_client.models.relayer_api_orders_channel_subscribe_schema import (
RelayerApiOrdersChannelSubscribeSchema,
)
from sra_client.models.relayer_api_orders_channel_update_schema import (
RelayerApiOrdersChannelUpdateSchema,
)
from sra_client.models.relayer_api_orders_response_schema import (
RelayerApiOrdersResponseSchema,
)
from sra_client.models.signed_order_schema import SignedOrderSchema

View File

@@ -1,49 +0,0 @@
# coding: utf-8
# flake8: noqa
from __future__ import absolute_import
# import models into model package
from sra_client.models.order_schema import OrderSchema
from sra_client.models.paginated_collection_schema import (
PaginatedCollectionSchema,
)
from sra_client.models.relayer_api_asset_data_pairs_response_schema import (
RelayerApiAssetDataPairsResponseSchema,
)
from sra_client.models.relayer_api_asset_data_trade_info_schema import (
RelayerApiAssetDataTradeInfoSchema,
)
from sra_client.models.relayer_api_error_response_schema import (
RelayerApiErrorResponseSchema,
)
from sra_client.models.relayer_api_error_response_schema_validation_errors import (
RelayerApiErrorResponseSchemaValidationErrors,
)
from sra_client.models.relayer_api_fee_recipients_response_schema import (
RelayerApiFeeRecipientsResponseSchema,
)
from sra_client.models.relayer_api_order_config_payload_schema import (
RelayerApiOrderConfigPayloadSchema,
)
from sra_client.models.relayer_api_order_config_response_schema import (
RelayerApiOrderConfigResponseSchema,
)
from sra_client.models.relayer_api_order_schema import RelayerApiOrderSchema
from sra_client.models.relayer_api_orderbook_response_schema import (
RelayerApiOrderbookResponseSchema,
)
from sra_client.models.relayer_api_orders_channel_subscribe_payload_schema import (
RelayerApiOrdersChannelSubscribePayloadSchema,
)
from sra_client.models.relayer_api_orders_channel_subscribe_schema import (
RelayerApiOrdersChannelSubscribeSchema,
)
from sra_client.models.relayer_api_orders_channel_update_schema import (
RelayerApiOrdersChannelUpdateSchema,
)
from sra_client.models.relayer_api_orders_response_schema import (
RelayerApiOrdersResponseSchema,
)
from sra_client.models.signed_order_schema import SignedOrderSchema

View File

@@ -1,20 +1,18 @@
.. source for the sphinx-generated build/docs/web/index.html
Python zero_ex.sra_client.api_client
====================================
Python zero_ex.sra_client
=========================
.. toctree::
:maxdepth: 2
:caption: Contents:
.. automodule:: sra_client
.. automodule:: zero_ex.sra_client
----
zero_ex.sra_client.DefaultApi
=============================
API
---
.. automodule:: sra_client.api.default_api
.. autoclass:: zero_ex.sra_client.DefaultApi
:members:
Indices and tables

View File

@@ -0,0 +1,2 @@
"""0x Python API."""
__import__("pkg_resources").declare_namespace(__name__)

View File

@@ -0,0 +1,392 @@
# coding: utf-8
# flake8: noqa
r"""A Python client for interacting with SRA-compatible Relayers.
0x Protocol is an open standard. Many Relayers opt to implementing a set of
`Standard Relayer API (SRA)
<http://sra-spec.s3-website-us-east-1.amazonaws.com/>`_ endpoints, to make it
easier for anyone to source liquidity that conforms to the 0x order format.
Here, we will show you how you can use the `0x-sra-client`:code: module to
interact with 0x relayers that implement the SRA specification.
Setup
-----
Install the package with pip::
pip install 0x-sra-client
To interact with a 0x Relayer, you need the HTTP endpoint of the Relayer you'd
like to connect to (eg https://api.radarrelay.com/0x/v2).
For testing one can use the `0x-launch-kit
<https://github.com/0xProject/0x-launch-kit#table-of-contents/>`_ to host
orders locally. The examples below assume that this server is running locally
and listening on port 3000, so the Relayer URL they use is
`http://localhost:3000`:code:.
By default, Launch Kit will connect to Kovan via Infura. However, it can be
configured to connect to any JSON-RPC endpoint, on any network. The examples
below assume that Launch Kit is connected to a Ganache development network
accessible at `http://localhost:8545`:code:.
To replicate this setup, one could run the following commands:
::
docker run -d -p 8545:8545 0xorg/ganache-cli
docker run -d --network host \
-e RPC_URL=http://localhost:8545 \
-e NETWORK_ID=50 \
-e WHITELIST_ALL_TOKENS=True \
0xorg/launch-kit-ci
(Note: This will only work on Linux, because `--network host`:code: only works
on Linux. For other platforms one would have to clone `the 0x-launch-kit
repository <https://github.com/0xProject/0x-launch-kit>`_ and build and start
the server.)
Configure and create an API client instance
-------------------------------------------
>>> from zero_ex.sra_client import ApiClient, Configuration, DefaultApi
>>> config = Configuration()
>>> config.host = "http://localhost:3000"
>>> relayer = DefaultApi(ApiClient(config))
Preparing to trade
------------------
Making and taking orders induces the SRA endpoint to deal with the Ethereum
network. Before we can start trading, we need to do a few things with the
network directly.
To start, connect to the Ethereum network:
>>> from web3 import HTTPProvider, Web3
>>> eth_node = HTTPProvider("http://localhost:8545")
What network is it?
>>> from zero_ex.contract_addresses import NetworkId
>>> network_id = NetworkId.GANACHE # you might use .MAINNET or .KOVAN
For our Maker role, we'll just use the first address available in the node:
>>> maker_address = Web3(eth_node).eth.accounts[0].lower()
The 0x Ganache snapshot loaded into our eth_node has a pre-loaded ZRX balance
for this account, so the example orders below have the maker trading away ZRX.
Before such an order can be valid, though, the maker must give the 0x contracts
permission to trade their ZRX tokens:
>>> from zero_ex.contract_addresses import NETWORK_TO_ADDRESSES
>>> contract_addresses = NETWORK_TO_ADDRESSES[network_id]
>>>
>>> from zero_ex.contract_artifacts import abi_by_name
>>> zrx_token_contract = Web3(eth_node).eth.contract(
... address=Web3.toChecksumAddress(contract_addresses.zrx_token),
... abi=abi_by_name("ZRXToken")
... )
>>>
>>> zrx_token_contract.functions.approve(
... Web3.toChecksumAddress(contract_addresses.erc20_proxy),
... 1000000000000000000
... ).transact(
... {"from": Web3.toChecksumAddress(maker_address)}
... )
HexBytes('0x...')
Post Order
-----------
Post an order for our Maker to trade ZRX for WETH:
>>> from zero_ex.order_utils import (
... asset_data_utils,
... Order,
... order_to_jsdict,
... sign_hash)
>>> import random
>>> from datetime import datetime, timedelta
>>> order = Order(
... makerAddress=maker_address,
... takerAddress="0x0000000000000000000000000000000000000000",
... senderAddress="0x0000000000000000000000000000000000000000",
... exchangeAddress=contract_addresses.exchange,
... feeRecipientAddress="0x0000000000000000000000000000000000000000",
... makerAssetData=asset_data_utils.encode_erc20(
... contract_addresses.zrx_token
... ),
... takerAssetData=asset_data_utils.encode_erc20(
... contract_addresses.ether_token
... ),
... salt=random.randint(1, 100000000000000000),
... makerFee=0,
... takerFee=0,
... makerAssetAmount=2,
... takerAssetAmount=2,
... expirationTimeSeconds=round(
... (datetime.utcnow() + timedelta(days=1)).timestamp()
... )
... )
>>> from zero_ex.order_utils import generate_order_hash_hex
>>> order_hash_hex = generate_order_hash_hex(
... order, contract_addresses.exchange
... )
>>> relayer.post_order_with_http_info(
... network_id=network_id.value,
... signed_order_schema=order_to_jsdict(
... order=order,
... exchange_address=contract_addresses.exchange,
... signature=sign_hash(
... eth_node, Web3.toChecksumAddress(maker_address), order_hash_hex
... )
... )
... )[1]
200
Get Order
---------
Retrieve the order we just posted:
>>> relayer.get_order("0x" + order_hash_hex)
{'meta_data': {},
'order': {'exchangeAddress': '0x...',
'expirationTimeSeconds': '...',
'feeRecipientAddress': '0x0000000000000000000000000000000000000000',
'makerAddress': '0x...',
'makerAssetAmount': '2',
'makerAssetData': '0xf47261b0000000000000000000000000...',
'makerFee': '0',
'salt': '...',
'senderAddress': '0x0000000000000000000000000000000000000000',
'signature': '0x...',
'takerAddress': '0x0000000000000000000000000000000000000000',
'takerAssetAmount': '2',
'takerAssetData': '0xf47261b0000000000000000000000000...',
'takerFee': '0'}}
Get Orders
-----------
Retrieve all of the Relayer's orders, a set which at this point consists solely
of the one we just posted:
>>> relayer.get_orders()
{'records': [{'meta_data': {},
'order': {'exchangeAddress': '0x...',
'expirationTimeSeconds': '...',
'feeRecipientAddress': '0x0000000000000000000000000000000000000000',
'makerAddress': '0x...',
'makerAssetAmount': '2',
'makerAssetData': '0xf47261b000000000000000000000000...',
'makerFee': '0',
'salt': '...',
'senderAddress': '0x0000000000000000000000000000000000000000',
'signature': '0x...',
'takerAddress': '0x0000000000000000000000000000000000000000',
'takerAssetAmount': '2',
'takerAssetData': '0xf47261b0000000000000000000000000...',
'takerFee': '0'}}]}
Get Asset Pairs
---------------
Get all of the Relayer's available asset pairs, which here means just WETH and
ZRX, since that's all there is on this Relayer's order book:
>>> relayer.get_asset_pairs()
{'records': [{'assetDataA': {'assetData': '0xf47261b0000000000000000000000000...',
'maxAmount': '115792089237316195423570985008687907853269984665640564039457584007913129639936',
'minAmount': '0',
'precision': 18},
'assetDataB': {'assetData': '0xf47261b0000000000000000000000000...',
'maxAmount': '115792089237316195423570985008687907853269984665640564039457584007913129639936',
'minAmount': '0',
'precision': 18}}]}
>>> asset_data_utils.decode_erc20_asset_data(
... relayer.get_asset_pairs().records[0]['assetDataA']['assetData']
... ).token_address == contract_addresses.zrx_token
True
>>> asset_data_utils.decode_erc20_asset_data(
... relayer.get_asset_pairs().records[0]['assetDataB']['assetData']
... ).token_address == contract_addresses.ether_token
True
Get Orderbook
-------------
Get the Relayer's order book for the WETH/ZRX asset pair (which, again,
consists just of our order):
>>> orderbook = relayer.get_orderbook(
... base_asset_data= "0x" + asset_data_utils.encode_erc20(
... contract_addresses.ether_token
... ).hex(),
... quote_asset_data= "0x" + asset_data_utils.encode_erc20(
... contract_addresses.zrx_token
... ).hex(),
... )
>>> orderbook
{'asks': {'records': []},
'bids': {'records': [{'meta_data': {},
'order': {'exchangeAddress': '0x...',
'expirationTimeSeconds': '...',
'feeRecipientAddress': '0x0000000000000000000000000000000000000000',
'makerAddress': '0x...',
'makerAssetAmount': '2',
'makerAssetData': '0xf47261b0000000000000000000000000...',
'makerFee': '0',
'salt': '...',
'senderAddress': '0x0000000000000000000000000000000000000000',
'signature': '0x...',
'takerAddress': '0x0000000000000000000000000000000000000000',
'takerAssetAmount': '2',
'takerAssetData': '0xf47261b0000000000000000000000000...',
'takerFee': '0'}}]}}
Select an order from the orderbook
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>>> from zero_ex.order_utils import jsdict_to_order
>>> order = jsdict_to_order(orderbook.bids.records[0].order)
>>> from pprint import pprint
>>> pprint(order)
{'expirationTimeSeconds': ...,
'feeRecipientAddress': '0x0000000000000000000000000000000000000000',
'makerAddress': '0x...',
'makerAssetAmount': 2,
'makerAssetData': b...
'makerFee': 0,
'salt': ...,
'senderAddress': '0x0000000000000000000000000000000000000000',
'signature': '0x...',
'takerAddress': '0x0000000000000000000000000000000000000000',
'takerAssetAmount': 2,
'takerAssetData': b...
'takerFee': 0}
Filling or Cancelling an Order
------------------------------
Fills and cancels are triggered by dealing directly with the 0x Exchange
contract, not by going through a Relayer.
See `the 0x-contract-wrappers documentation
<http://0x-contract-wrappers-py.s3-website-us-east-1.amazonaws.com/>`_ for more
examples.
Filling
^^^^^^^
>>> taker_address = Web3(eth_node).eth.accounts[1].lower()
Our taker will take a ZRX/WETH order, but it doesn't have any WETH yet. By
depositing some ether into the WETH contract, it will be given some WETH to
trade with:
>>> weth_instance = Web3(eth_node).eth.contract(
... address=Web3.toChecksumAddress(contract_addresses.ether_token),
... abi=abi_by_name("WETH9")
... )
>>> weth_instance.functions.deposit().transact(
... {"from": Web3.toChecksumAddress(taker_address),
... "value": 1000000000000000000}
... )
HexBytes('0x...')
Next the taker needs to give the 0x contracts permission to trade their WETH:
>>> weth_instance.functions.approve(
... Web3.toChecksumAddress(contract_addresses.erc20_proxy),
... 1000000000000000000).transact(
... {"from": Web3.toChecksumAddress(taker_address)})
HexBytes('0x...')
Now the taker is ready to trade.
Recall that in a previous example we selected a specific order from the order
book. Now let's have the taker fill it:
>>> from zero_ex.contract_wrappers import Exchange, TxParams
>>> from zero_ex.order_utils import Order
>>> Exchange(eth_node).fill_order(
... order=order,
... taker_amount=order['makerAssetAmount']/2, # note the half fill
... signature=order['signature'],
... tx_params=TxParams(from_=taker_address)
... )
HexBytes('0x...')
Cancelling
^^^^^^^^^^
Note that the above fill was partial: it only filled half of the order. Now
we'll have our maker cancel the remaining order:
>>> Exchange(eth_node).cancel_order(
... order=order,
... tx_params=TxParams(from_=maker_address)
... )
HexBytes('0x...')
""" # noqa: E501 (line too long)
from __future__ import absolute_import
__version__ = "1.0.0"
# import apis into sdk package
from .api.default_api import DefaultApi
# import ApiClient
from .api_client import ApiClient
from .configuration import Configuration
# import models into sdk package
from .models.order_schema import OrderSchema
from .models.paginated_collection_schema import PaginatedCollectionSchema
from .models.relayer_api_asset_data_pairs_response_schema import (
RelayerApiAssetDataPairsResponseSchema,
)
from .models.relayer_api_asset_data_trade_info_schema import (
RelayerApiAssetDataTradeInfoSchema,
)
from .models.relayer_api_error_response_schema import (
RelayerApiErrorResponseSchema,
)
from .models.relayer_api_error_response_schema_validation_errors import (
RelayerApiErrorResponseSchemaValidationErrors,
)
from .models.relayer_api_fee_recipients_response_schema import (
RelayerApiFeeRecipientsResponseSchema,
)
from .models.relayer_api_order_config_payload_schema import (
RelayerApiOrderConfigPayloadSchema,
)
from .models.relayer_api_order_config_response_schema import (
RelayerApiOrderConfigResponseSchema,
)
from .models.relayer_api_order_schema import RelayerApiOrderSchema
from .models.relayer_api_orderbook_response_schema import (
RelayerApiOrderbookResponseSchema,
)
from .models.relayer_api_orders_channel_subscribe_payload_schema import (
RelayerApiOrdersChannelSubscribePayloadSchema,
)
from .models.relayer_api_orders_channel_subscribe_schema import (
RelayerApiOrdersChannelSubscribeSchema,
)
from .models.relayer_api_orders_channel_update_schema import (
RelayerApiOrdersChannelUpdateSchema,
)
from .models.relayer_api_orders_response_schema import (
RelayerApiOrdersResponseSchema,
)
from .models.signed_order_schema import SignedOrderSchema

View File

@@ -3,4 +3,4 @@ from __future__ import absolute_import
# flake8: noqa
# import apis into api package
from sra_client.api.default_api import DefaultApi
from zero_ex.sra_client.api.default_api import DefaultApi

View File

@@ -8,8 +8,8 @@ import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from sra_client.api_client import ApiClient
from sra_client.models.relayer_api_order_config_payload_schema import (
from zero_ex.sra_client.api_client import ApiClient
from zero_ex.sra_client.models.relayer_api_order_config_payload_schema import (
RelayerApiOrderConfigPayloadSchema,
)
@@ -42,9 +42,9 @@ class DefaultApi(object):
:param bool async_req: Whether request should be asynchronous.
:param str asset_data_a: The assetData value for the first asset in the pair.
:param str asset_data_b: The assetData value for the second asset in the pair.
:param float network_id: The id of the Ethereum network
:param float page: The number of the page to request in the collection.
:param float per_page: The number of records to return per page.
:param int network_id: The id of the Ethereum network
:param int page: The number of the page to request in the collection.
:param int per_page: The number of records to return per page.
:return: :class:`RelayerApiAssetDataPairsResponseSchema`.
If the method is called asynchronously returns the request thread.
@@ -71,12 +71,14 @@ class DefaultApi(object):
:param bool async_req: Whether request should be asynchronous.
:param str asset_data_a: The assetData value for the first asset in the pair.
:param str asset_data_b: The assetData value for the second asset in the pair.
:param float network_id: The id of the Ethereum network
:param float page: The number of the page to request in the collection.
:param float per_page: The number of records to return per page.
:param int network_id: The id of the Ethereum network
:param int page: The number of the page to request in the collection.
:param int per_page: The number of records to return per page.
:return: :class:`RelayerApiAssetDataPairsResponseSchema`.
If the method is called asynchronously returns the request thread.
:return: A tuple consisting of a
:class:`RelayerApiAssetDataPairsResponseSchema`, an HTTP status
code integer, and a collection of HTTP headers. If the method is
called asynchronously returns the request thread.
"""
local_var_params = locals()
@@ -168,9 +170,9 @@ class DefaultApi(object):
>>> result = thread.get() # doctest: +SKIP
:param bool async_req: Whether request should be asynchronous.
:param float network_id: The id of the Ethereum network
:param float page: The number of the page to request in the collection.
:param float per_page: The number of records to return per page.
:param int network_id: The id of the Ethereum network
:param int page: The number of the page to request in the collection.
:param int per_page: The number of records to return per page.
:return: :class:`RelayerApiFeeRecipientsResponseSchema`.
If the method is called asynchronously, returns the request thread.
@@ -194,12 +196,14 @@ class DefaultApi(object):
>>> result = thread.get() # doctest: +SKIP
:param bool async_req: Whether request should be asynchronous.
:param float network_id: The id of the Ethereum network
:param float page: The number of the page to request in the collection.
:param float per_page: The number of records to return per page.
:param int network_id: The id of the Ethereum network
:param int page: The number of the page to request in the collection.
:param int per_page: The number of records to return per page.
:return: :class:`RelayerApiFeeRecipientsResponseSchema`.
If the method is called asynchronously, returns the request thread.
:return: A tuple consisting of a
:class:`RelayerApiFeeRecipientsResponseSchema`, an HTTP status
code integer, and a collection of HTTP headers. If the method is
called asynchronously returns the request thread.
"""
local_var_params = locals()
@@ -277,7 +281,7 @@ class DefaultApi(object):
:param bool async_req: Whether request should be asynchronous.
:param str order_hash: The hash of the desired 0x order. (required)
:param float network_id: The id of the Ethereum network
:param int network_id: The id of the Ethereum network
:return: :class:`RelayerApiOrderSchema`.
If the method is called asynchronously, returns the request thread.
@@ -301,10 +305,12 @@ class DefaultApi(object):
:param bool async_req: Whether request should be asynchronous.
:param str order_hash: The hash of the desired 0x order. (required)
:param float network_id: The id of the Ethereum network
:param int network_id: The id of the Ethereum network
:return: :class:`RelayerApiOrderSchema`.
If the method is called asynchronously returns the request thread.
:return: A tuple consisting of a
:class:`RelayerApiOrderSchema`, an HTTP status code integer, and a
collection of HTTP headers. If the method is called
asynchronously returns the request thread.
"""
local_var_params = locals()
@@ -395,7 +401,7 @@ class DefaultApi(object):
>>> result = thread.get() # doctest: +SKIP
:param bool async_req: Whether request should be asynchronous.
:param float network_id: The id of the Ethereum network
:param int network_id: The id of the Ethereum network
:param relayer_api_order_config_payload_schema: instance of
:class:`RelayerApiOrderConfigPayloadSchema`. The fields of a 0x
order the relayer may want to decide what configuration to send
@@ -430,14 +436,16 @@ class DefaultApi(object):
>>> result = thread.get() # doctest: +SKIP
:param bool async_req: Whether request should be asynchronous.
:param float network_id: The id of the Ethereum network
:param int network_id: The id of the Ethereum network
:param relayer_api_order_config_payload_schema: instance of
:class: `RelayerApiOrderConfigPayloadSchema`. The fields of a 0x
order the relayer may want to decide what configuration to send
back.
:return: :class:`RelayerApiOrderConfigResponseSchema`.
If the method is called asynchronously returns the request thread.
:return: A tuple consisting of a
:class:`RelayerApiOrderConfigResponseSchema`, an HTTP status code
integer, and a collection of HTTP headers. If the method is
called asynchronously returns the request thread.
"""
local_var_params = locals()
@@ -537,9 +545,9 @@ class DefaultApi(object):
:param str quote_asset_data: assetData (makerAssetData or
takerAssetData) designated as the quote currency in the currency
pair calculation of price. (required)
:param float network_id: The id of the Ethereum network
:param float page: The number of the page to request in the collection.
:param float per_page: The number of records to return per page.
:param int network_id: The id of the Ethereum network
:param int page: The number of the page to request in the collection.
:param int per_page: The number of records to return per page.
:return: :class:`RelayerApiOrderbookResponseSchema`.
If the method is called asynchronously, returns the request thread.
@@ -586,12 +594,14 @@ class DefaultApi(object):
:param str quote_asset_data: assetData (makerAssetData or
takerAssetData) designated as the quote currency in the currency
pair calculation of price. (required)
:param float network_id: The id of the Ethereum network
:param float page: The number of the page to request in the collection.
:param float per_page: The number of records to return per page.
:param int network_id: The id of the Ethereum network
:param int page: The number of the page to request in the collection.
:param int per_page: The number of records to return per page.
:return: :class:`RelayerApiOrderbookResponseSchema`.
If the method is called asynchronously, returns the request thread.
:return: A tuple consisting of a
:class:`RelayerApiOrderbookResponseSchema`, an HTTP status code
integer, and a collection of HTTP headers. If the method is
called asynchronously returns the request thread.
"""
local_var_params = locals()
@@ -752,9 +762,9 @@ class DefaultApi(object):
`0x Protocol v2 Specification
<https://github.com/0xProject/0x-protocol-specification/blob/
master/v2/v2-specification.md#order-message-format>`__
:param float network_id: The id of the Ethereum network
:param float page: The number of the page to request in the collection.
:param float per_page: The number of records to return per page.
:param int network_id: The id of the Ethereum network
:param int page: The number of the page to request in the collection.
:param int per_page: The number of records to return per page.
:return: :class:`RelayerApiOrdersResponseSchema`.
If the method is called asynchronously, returns the request thread.
@@ -829,12 +839,14 @@ class DefaultApi(object):
`0x Protocol v2 Specification
<https://github.com/0xProject/0x-protocol-specification/blob/
master/v2/v2-specification.md#order-message-format>`__
:param float network_id: The id of the Ethereum network
:param float page: The number of the page to request in the collection.
:param float per_page: The number of records to return per page.
:param int network_id: The id of the Ethereum network
:param int page: The number of the page to request in the collection.
:param int per_page: The number of records to return per page.
:return: RelayerApiOrdersResponseSchema.
If the method is called asynchronously, returns the request thread.
:return: A tuple consisting of a
:class:`RelayerApiOrdersResponseSchema`, an HTTP status code
integer, and a collection of HTTP headers. If the method is
called asynchronously returns the request thread.
"""
local_var_params = locals()
@@ -983,7 +995,7 @@ class DefaultApi(object):
>>> result = thread.get() # doctest: +SKIP
:param bool async_req: Whether request should be asynchronous.
:param float network_id: The id of the Ethereum network
:param int network_id: The id of the Ethereum network
:param signed_order_schema: Instance of :class:`SignedOrderSchema`.
A valid signed 0x order based on the schema.
@@ -1008,12 +1020,14 @@ class DefaultApi(object):
>>> result = thread.get() # doctest: +SKIP
:param bool async_req: Whether request should be asynchronous.
:param float network_id: The id of the Ethereum network
:param int network_id: The id of the Ethereum network
:param signed_order_schema: Instance of :class:`SignedOrderSchema`
A valid signed 0x order based on the schema.
:return: None.
If the method is called asynchronously, returns the request thread.
:return: A tuple consisting of the response data (always empty for this
method), an HTTP status code integer, and a collection of HTTP
headers. If the method is called asynchronously returns the
request thread.
"""
local_var_params = locals()

View File

@@ -14,9 +14,9 @@ import tempfile
import six
from six.moves.urllib.parse import quote
from sra_client.configuration import Configuration
import sra_client.models
from sra_client import rest
from zero_ex.sra_client.configuration import Configuration
import zero_ex.sra_client.models
from zero_ex.sra_client import rest
class ApiClient(object):
@@ -300,7 +300,7 @@ class ApiClient(object):
if klass in self.NATIVE_TYPES_MAPPING:
klass = self.NATIVE_TYPES_MAPPING[klass]
else:
klass = getattr(sra_client.models, klass)
klass = getattr(zero_ex.sra_client.models, klass)
if klass in self.PRIMITIVE_TYPES:
return self.__deserialize_primitive(data, klass)

View File

@@ -0,0 +1,49 @@
# coding: utf-8
# flake8: noqa
from __future__ import absolute_import
# import models into model package
from zero_ex.sra_client.models.order_schema import OrderSchema
from zero_ex.sra_client.models.paginated_collection_schema import (
PaginatedCollectionSchema,
)
from zero_ex.sra_client.models.relayer_api_asset_data_pairs_response_schema import (
RelayerApiAssetDataPairsResponseSchema,
)
from zero_ex.sra_client.models.relayer_api_asset_data_trade_info_schema import (
RelayerApiAssetDataTradeInfoSchema,
)
from zero_ex.sra_client.models.relayer_api_error_response_schema import (
RelayerApiErrorResponseSchema,
)
from zero_ex.sra_client.models.relayer_api_error_response_schema_validation_errors import (
RelayerApiErrorResponseSchemaValidationErrors,
)
from zero_ex.sra_client.models.relayer_api_fee_recipients_response_schema import (
RelayerApiFeeRecipientsResponseSchema,
)
from zero_ex.sra_client.models.relayer_api_order_config_payload_schema import (
RelayerApiOrderConfigPayloadSchema,
)
from zero_ex.sra_client.models.relayer_api_order_config_response_schema import (
RelayerApiOrderConfigResponseSchema,
)
from zero_ex.sra_client.models.relayer_api_order_schema import RelayerApiOrderSchema
from zero_ex.sra_client.models.relayer_api_orderbook_response_schema import (
RelayerApiOrderbookResponseSchema,
)
from zero_ex.sra_client.models.relayer_api_orders_channel_subscribe_payload_schema import (
RelayerApiOrdersChannelSubscribePayloadSchema,
)
from zero_ex.sra_client.models.relayer_api_orders_channel_subscribe_schema import (
RelayerApiOrdersChannelSubscribeSchema,
)
from zero_ex.sra_client.models.relayer_api_orders_channel_update_schema import (
RelayerApiOrdersChannelUpdateSchema,
)
from zero_ex.sra_client.models.relayer_api_orders_response_schema import (
RelayerApiOrdersResponseSchema,
)
from zero_ex.sra_client.models.signed_order_schema import SignedOrderSchema

View File

@@ -21,21 +21,7 @@ class OrderSchema(object):
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
"maker_address": "str",
"taker_address": "str",
"maker_fee": "str",
"taker_fee": "str",
"sender_address": "str",
"maker_asset_amount": "str",
"taker_asset_amount": "str",
"maker_asset_data": "str",
"taker_asset_data": "str",
"salt": "str",
"exchange_address": "str",
"fee_recipient_address": "str",
"expiration_time_seconds": "str",
}
openapi_types = {}
attribute_map = {
"maker_address": "makerAddress",

View File

@@ -1,98 +0,0 @@
"""Test the default api client"""
# coding: utf-8
from __future__ import absolute_import
import unittest
from sra_client import ApiClient, Configuration
from sra_client.api import DefaultApi
class TestDefaultApi(unittest.TestCase):
"""DefaultApi unit test stubs"""
def setUp(self):
config = Configuration()
config.host = "http://localhost:3000"
self.api = DefaultApi(ApiClient(config))
def tearDown(self):
pass
# pylint: disable=too-many-locals
def test_get_asset_pairs(self):
"""Test case for get_asset_pairs
"""
expected = {
"records": [
{
"assetDataA": {
"assetData": "0xf47261b00000000000000000000000000"
"b1ba0af832d7c05fd64161e0db78e85978e8082",
"maxAmount": "115792089237316195423570985008687907853"
"269984665640564039457584007913129639936",
"minAmount": "0",
"precision": 18,
},
"assetDataB": {
"assetData": "0xf47261b0000000000000000000000000"
"871dd7c2b4b25e1aa18728e9d5f2af4c4e431f5c",
"maxAmount": "115792089237316195423570985008687907853"
"269984665640564039457584007913129639936",
"minAmount": "0",
"precision": 18,
},
}
]
}
actual = self.api.get_asset_pairs()
acutal_asset_data_a = actual.records[0]["assetDataA"]["assetData"]
expected_asset_data_a = expected["records"][0]["assetDataA"][
"assetData"
]
self.assertEqual(acutal_asset_data_a, expected_asset_data_a)
acutal_max_amount_a = actual.records[0]["assetDataA"]["maxAmount"]
expected_max_amount_a = expected["records"][0]["assetDataA"][
"maxAmount"
]
self.assertEqual(acutal_max_amount_a, expected_max_amount_a)
acutal_min_amount_a = actual.records[0]["assetDataA"]["minAmount"]
expected_min_amount_a = expected["records"][0]["assetDataA"][
"minAmount"
]
self.assertEqual(acutal_min_amount_a, expected_min_amount_a)
acutal_precision_a = actual.records[0]["assetDataA"]["precision"]
expected_precision_a = expected["records"][0]["assetDataA"][
"precision"
]
self.assertEqual(acutal_precision_a, expected_precision_a)
acutal_asset_data_b = actual.records[0]["assetDataB"]["assetData"]
expected_asset_data_b = expected["records"][0]["assetDataB"][
"assetData"
]
self.assertEqual(acutal_asset_data_b, expected_asset_data_b)
acutal_max_amount_b = actual.records[0]["assetDataB"]["maxAmount"]
expected_max_amount_b = expected["records"][0]["assetDataB"][
"maxAmount"
]
self.assertEqual(acutal_max_amount_b, expected_max_amount_b)
acutal_min_amount_b = actual.records[0]["assetDataB"]["minAmount"]
expected_min_amount_b = expected["records"][0]["assetDataB"][
"minAmount"
]
self.assertEqual(acutal_min_amount_b, expected_min_amount_b)
acutal_precision_b = actual.records[0]["assetDataB"]["precision"]
expected_precision_b = expected["records"][0]["assetDataB"][
"precision"
]
self.assertEqual(acutal_precision_b, expected_precision_b)
if __name__ == "__main__":
unittest.main()