diff options
Diffstat (limited to 'python-packages')
82 files changed, 7453 insertions, 82 deletions
diff --git a/python-packages/json_schemas/.discharge.json b/python-packages/json_schemas/.discharge.json new file mode 100644 index 000000000..66d95679f --- /dev/null +++ b/python-packages/json_schemas/.discharge.json @@ -0,0 +1,13 @@ +{ + "domain": "0x-json-schemas-py", + "build_command": "python setup.py build_sphinx", + "upload_directory": "build/docs/html", + "index_key": "index.html", + "error_key": "index.html", + "trailing_slashes": true, + "cache": 3600, + "aws_profile": "default", + "aws_region": "us-east-1", + "cdn": false, + "dns_configured": true +} diff --git a/python-packages/json_schemas/.pylintrc b/python-packages/json_schemas/.pylintrc new file mode 100644 index 000000000..937bc6313 --- /dev/null +++ b/python-packages/json_schemas/.pylintrc @@ -0,0 +1,3 @@ +[MESSAGES CONTROL] +disable=C0330,line-too-long,fixme,too-few-public-methods,too-many-ancestors +# C0330 is "bad hanging indent". we use indents per `black`. diff --git a/python-packages/json_schemas/README.md b/python-packages/json_schemas/README.md new file mode 100644 index 000000000..ef8e888f3 --- /dev/null +++ b/python-packages/json_schemas/README.md @@ -0,0 +1,45 @@ +## 0x-json-schemas + +0x JSON schemas for those developing on top of 0x protocol. + +Read the [documentation](http://0x-json-schemas-py.s3-website-us-east-1.amazonaws.com/) + +## Installing + +```bash +pip install 0x-json-schemas +``` + +## 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 Code and Dependencies + +Ensure that you have installed Python >=3.6 and Docker. Then: + +```bash +pip install -e .[dev] +``` + +### Test + +Tests depend on a running ganache instance with the 0x contracts deployed in it. For convenience, a docker container is provided that has ganache-cli and a snapshot containing the necessary contracts. A shortcut is provided to run that docker container: `./setup.py ganache`. With that running, the tests can be run with `./setup.py test`. + +### Clean + +`./setup.py clean --all` + +### Lint + +`./setup.py lint` + +### Build Documentation + +`./setup.py build_sphinx` + +### More + +See `./setup.py --help-commands` for more info. diff --git a/python-packages/json_schemas/setup.py b/python-packages/json_schemas/setup.py new file mode 100755 index 000000000..7813f101f --- /dev/null +++ b/python-packages/json_schemas/setup.py @@ -0,0 +1,191 @@ +#!/usr/bin/env python + +"""setuptools module for json_schemas package.""" + +import distutils.command.build_py +from distutils.command.clean import clean +import subprocess # nosec +from shutil import rmtree +from os import environ, path +from sys import argv + +from setuptools import find_packages, setup +from setuptools.command.test import test as TestCommand + + +class TestCommandExtension(TestCommand): + """Run pytest tests.""" + + def run_tests(self): + """Invoke pytest.""" + import pytest + + exit(pytest.main()) + + +class LintCommand(distutils.command.build_py.build_py): + """Custom setuptools command class for running linters.""" + + description = "Run linters" + + def run(self): + """Run linter shell commands.""" + lint_commands = [ + # formatter: + "black --line-length 79 --check --diff src test setup.py".split(), + # style guide checker (formerly pep8): + "pycodestyle src test setup.py".split(), + # docstring style checker: + "pydocstyle src test setup.py".split(), + # static type checker: + "mypy src test setup.py".split(), + # security issue checker: + "bandit -r src ./setup.py".split(), + # general linter: + "pylint src test setup.py".split(), + # pylint takes relatively long to run, so it runs last, to enable + # fast failures. + ] + + # tell mypy where to find interface stubs for 3rd party libs + environ["MYPYPATH"] = path.join( + path.dirname(path.realpath(argv[0])), "stubs" + ) + + for lint_command in lint_commands: + print( + "Running lint command `", " ".join(lint_command).strip(), "`" + ) + subprocess.check_call(lint_command) # nosec + + +class CleanCommandExtension(clean): + """Custom command to do custom cleanup.""" + + def run(self): + """Run the regular clean, followed by our custom commands.""" + super().run() + rmtree("dist", ignore_errors=True) + rmtree(".mypy_cache", ignore_errors=True) + rmtree(".tox", ignore_errors=True) + rmtree(".pytest_cache", ignore_errors=True) + rmtree("src/*.egg-info", ignore_errors=True) + + +class TestPublishCommand(distutils.command.build_py.build_py): + """Custom command to publish to test.pypi.org.""" + + description = ( + "Publish dist/* to test.pypi.org. Run sdist & bdist_wheel first." + ) + + def run(self): + """Run twine to upload to test.pypi.org.""" + subprocess.check_call( # nosec + ( + "twine upload --repository-url https://test.pypi.org/legacy/" + + " --verbose dist/*" + ).split() + ) + + +class PublishCommand(distutils.command.build_py.build_py): + """Custom command to publish to pypi.org.""" + + description = "Publish dist/* to pypi.org. Run sdist & bdist_wheel first." + + def run(self): + """Run twine to upload to pypi.org.""" + subprocess.check_call("twine upload dist/*".split()) # nosec + + +class PublishDocsCommand(distutils.command.build_py.build_py): + """Custom command to publish docs to S3.""" + + description = ( + "Publish docs to " + + "http://0x-json-schemas-py.s3-website-us-east-1.amazonaws.com/" + ) + + def run(self): + """Run npm package `discharge` to build & upload docs.""" + subprocess.check_call("discharge deploy".split()) # nosec + + +with open("README.md", "r") as file_handle: + README_MD = file_handle.read() + + +setup( + name="0x-json-schemas", + version="1.0.0", + description="JSON schemas for 0x applications", + long_description=README_MD, + long_description_content_type="text/markdown", + url=( + "https://github.com/0xProject/0x-monorepo/tree/development" + + "/python-packages/json_schemas" + ), + author="F. Eugene Aumson", + author_email="feuGeneA@users.noreply.github.com", + cmdclass={ + "clean": CleanCommandExtension, + "lint": LintCommand, + "test": TestCommandExtension, + "test_publish": TestPublishCommand, + "publish": PublishCommand, + "publish_docs": PublishDocsCommand, + }, + install_requires=["jsonschema", "mypy_extensions", "stringcase"], + extras_require={ + "dev": [ + "bandit", + "black", + "coverage", + "coveralls", + "mypy", + "mypy_extensions", + "pycodestyle", + "pydocstyle", + "pylint", + "pytest", + "sphinx", + "tox", + "twine", + ] + }, + python_requires=">=3.6, <4", + package_data={"zero_ex.json_schemas": ["py.typed", "schemas/*"]}, + package_dir={"": "src"}, + license="Apache 2.0", + keywords=( + "ethereum cryptocurrency 0x decentralized blockchain dex exchange" + ), + namespace_packages=["zero_ex"], + packages=find_packages("src"), + classifiers=[ + "Development Status :: 2 - Pre-Alpha", + "Intended Audience :: Developers", + "Intended Audience :: Financial and Insurance Industry", + "License :: OSI Approved :: Apache Software License", + "Natural Language :: English", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Topic :: Internet :: WWW/HTTP", + "Topic :: Office/Business :: Financial", + "Topic :: Other/Nonlisted Topic", + "Topic :: Security :: Cryptography", + "Topic :: Software Development :: Libraries", + "Topic :: Utilities", + ], + zip_safe=False, # required per mypy + command_options={ + "build_sphinx": { + "source_dir": ("setup.py", "src"), + "build_dir": ("setup.py", "build/docs"), + } + }, +) diff --git a/python-packages/json_schemas/src/conf.py b/python-packages/json_schemas/src/conf.py new file mode 100644 index 000000000..1ae1493e3 --- /dev/null +++ b/python-packages/json_schemas/src/conf.py @@ -0,0 +1,54 @@ +"""Configuration file for the Sphinx documentation builder.""" + +# Reference: http://www.sphinx-doc.org/en/master/config + +from typing import List +import pkg_resources + + +# pylint: disable=invalid-name +# because these variables are not named in upper case, as globals should be. + +project = "0x-json-schemas" +# pylint: disable=redefined-builtin +copyright = "2018, ZeroEx, Intl." +author = "F. Eugene Aumson" +version = pkg_resources.get_distribution("0x-json-schemas").version +release = "" # The full version, including alpha/beta/rc tags + +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.doctest", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.viewcode", +] + +templates_path = ["doc_templates"] + +source_suffix = ".rst" +# eg: source_suffix = [".rst", ".md"] + +master_doc = "index" # The master toctree document. + +language = None + +exclude_patterns: List[str] = [] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = None + +html_theme = "alabaster" + +html_static_path = ["doc_static"] +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". + +# Output file base name for HTML help builder. +htmlhelp_basename = "json_schemaspydoc" + +# -- Extension configuration: + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = {"https://docs.python.org/": None} diff --git a/python-packages/order_utils/stubs/jsonschema/exceptions.pyi b/python-packages/json_schemas/src/doc_static/.gitkeep index e69de29bb..e69de29bb 100644 --- a/python-packages/order_utils/stubs/jsonschema/exceptions.pyi +++ b/python-packages/json_schemas/src/doc_static/.gitkeep diff --git a/python-packages/json_schemas/src/index.rst b/python-packages/json_schemas/src/index.rst new file mode 100644 index 000000000..3de809aa3 --- /dev/null +++ b/python-packages/json_schemas/src/index.rst @@ -0,0 +1,18 @@ +.. source for the sphinx-generated build/docs/web/index.html + +Python zero_ex.json_schemas +=========================== + +.. toctree:: + :maxdepth: 2 + :caption: Contents: + +.. automodule:: zero_ex.json_schemas + :members: + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/python-packages/json_schemas/src/zero_ex/__init__.py b/python-packages/json_schemas/src/zero_ex/__init__.py new file mode 100644 index 000000000..e90d833db --- /dev/null +++ b/python-packages/json_schemas/src/zero_ex/__init__.py @@ -0,0 +1,2 @@ +"""0x Python API.""" +__import__("pkg_resources").declare_namespace(__name__) diff --git a/python-packages/json_schemas/src/zero_ex/json_schemas/__init__.py b/python-packages/json_schemas/src/zero_ex/json_schemas/__init__.py new file mode 100644 index 000000000..10c564b99 --- /dev/null +++ b/python-packages/json_schemas/src/zero_ex/json_schemas/__init__.py @@ -0,0 +1,83 @@ +"""JSON schemas and associated utilities.""" + +from os import path +import json +from typing import Mapping + +from pkg_resources import resource_string +import jsonschema +from stringcase import snakecase + + +class _LocalRefResolver(jsonschema.RefResolver): + """Resolve package-local JSON schema id's.""" + + def __init__(self): + """Initialize a new instance.""" + jsonschema.RefResolver.__init__(self, "", "") + + @staticmethod + def resolve_from_url(url: str) -> str: + """Resolve the given URL. + + :param url: a string representing the URL of the JSON schema to fetch. + :returns: a string representing the deserialized JSON schema + :raises jsonschema.ValidationError: when the resource associated with + `url` does not exist. + """ + ref = url.replace("file://", "") + return json.loads( + resource_string( + "zero_ex.json_schemas", + f"schemas/{snakecase(ref.lstrip('/'))}.json", + ) + ) + + +# Instantiate the `_LocalRefResolver()` only once so that `assert_valid()` can +# perform multiple schema validations without reading from disk the schema +# every time. +_LOCAL_RESOLVER = _LocalRefResolver() + + +def assert_valid(data: Mapping, schema_id: str) -> None: + """Validate the given `data` against the specified `schema`. + + :param data: Python dictionary to be validated as a JSON object. + :param schema_id: id property of the JSON schema to validate against. Must + be one of those listed in `the 0x JSON schema files + <https://github.com/0xProject/0x-monorepo/tree/development/packages/json-schemas/schemas>`_. + + Raises an exception if validation fails. + + >>> assert_valid( + ... {'v': 27, 'r': '0x'+'f'*64, 's': '0x'+'f'*64}, + ... '/ecSignatureSchema', + ... ) + """ + # noqa + + _, schema = _LOCAL_RESOLVER.resolve(schema_id) + jsonschema.validate(data, schema, resolver=_LOCAL_RESOLVER) + + +def assert_valid_json(data: str, schema_id: str) -> None: + """Validate the given `data` against the specified `schema`. + + :param data: JSON string to be validated. + :param schema_id: id property of the JSON schema to validate against. Must + be one of those listed in `the 0x JSON schema files + <https://github.com/0xProject/0x-monorepo/tree/development/packages/json-schemas/schemas>`_. + + Raises an exception if validation fails. + + >>> assert_valid_json( + ... r'''{ + ... "v": 27, + ... "r": "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + ... "s": "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" + ... }''', + ... '/ecSignatureSchema', + ... ) + """ # noqa: E501 (line too long) + assert_valid(json.loads(data), schema_id) diff --git a/python-packages/json_schemas/src/zero_ex/json_schemas/py.typed b/python-packages/json_schemas/src/zero_ex/json_schemas/py.typed new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/python-packages/json_schemas/src/zero_ex/json_schemas/py.typed diff --git a/python-packages/order_utils/src/zero_ex/json_schemas/schemas b/python-packages/json_schemas/src/zero_ex/json_schemas/schemas index b8257372c..b8257372c 120000 --- a/python-packages/order_utils/src/zero_ex/json_schemas/schemas +++ b/python-packages/json_schemas/src/zero_ex/json_schemas/schemas diff --git a/python-packages/json_schemas/stubs/distutils/__init__.pyi b/python-packages/json_schemas/stubs/distutils/__init__.pyi new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/python-packages/json_schemas/stubs/distutils/__init__.pyi diff --git a/python-packages/json_schemas/stubs/distutils/command/__init__.pyi b/python-packages/json_schemas/stubs/distutils/command/__init__.pyi new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/python-packages/json_schemas/stubs/distutils/command/__init__.pyi diff --git a/python-packages/json_schemas/stubs/distutils/command/clean.pyi b/python-packages/json_schemas/stubs/distutils/command/clean.pyi new file mode 100644 index 000000000..46a42ddb1 --- /dev/null +++ b/python-packages/json_schemas/stubs/distutils/command/clean.pyi @@ -0,0 +1,7 @@ +from distutils.core import Command + +class clean(Command): + def initialize_options(self: clean) -> None: ... + def finalize_options(self: clean) -> None: ... + def run(self: clean) -> None: ... + ... diff --git a/python-packages/json_schemas/stubs/jsonschema/__init__.pyi b/python-packages/json_schemas/stubs/jsonschema/__init__.pyi new file mode 100644 index 000000000..442e2f65e --- /dev/null +++ b/python-packages/json_schemas/stubs/jsonschema/__init__.pyi @@ -0,0 +1,11 @@ +from typing import Any, Dict, Tuple + + +class RefResolver: + def resolve(self, url: str) -> Tuple[str, Dict]: + ... + + +class ValidationError(Exception): pass + +def validate(instance: Any, schema: Dict, cls=None, *args, **kwargs) -> None: pass diff --git a/python-packages/json_schemas/stubs/jsonschema/exceptions.pyi b/python-packages/json_schemas/stubs/jsonschema/exceptions.pyi new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/python-packages/json_schemas/stubs/jsonschema/exceptions.pyi diff --git a/python-packages/json_schemas/stubs/pytest/__init__.pyi b/python-packages/json_schemas/stubs/pytest/__init__.pyi new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/python-packages/json_schemas/stubs/pytest/__init__.pyi diff --git a/python-packages/json_schemas/stubs/pytest/raises.pyi b/python-packages/json_schemas/stubs/pytest/raises.pyi new file mode 100644 index 000000000..2e3b29f3d --- /dev/null +++ b/python-packages/json_schemas/stubs/pytest/raises.pyi @@ -0,0 +1 @@ +def raises(exception: Exception) -> ExceptionInfo: ... diff --git a/python-packages/json_schemas/stubs/setuptools/__init__.pyi b/python-packages/json_schemas/stubs/setuptools/__init__.pyi new file mode 100644 index 000000000..8ea8d32b7 --- /dev/null +++ b/python-packages/json_schemas/stubs/setuptools/__init__.pyi @@ -0,0 +1,8 @@ +from distutils.dist import Distribution +from typing import Any, List + +def setup(**attrs: Any) -> Distribution: ... + +class Command: ... + +def find_packages(where: str) -> List[str]: ... diff --git a/python-packages/json_schemas/stubs/setuptools/command/__init__.pyi b/python-packages/json_schemas/stubs/setuptools/command/__init__.pyi new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/python-packages/json_schemas/stubs/setuptools/command/__init__.pyi diff --git a/python-packages/json_schemas/stubs/setuptools/command/test.pyi b/python-packages/json_schemas/stubs/setuptools/command/test.pyi new file mode 100644 index 000000000..c5ec770ad --- /dev/null +++ b/python-packages/json_schemas/stubs/setuptools/command/test.pyi @@ -0,0 +1,3 @@ +from setuptools import Command + +class test(Command): ... diff --git a/python-packages/json_schemas/stubs/stringcase/__init__.pyi b/python-packages/json_schemas/stubs/stringcase/__init__.pyi new file mode 100644 index 000000000..56d784cf5 --- /dev/null +++ b/python-packages/json_schemas/stubs/stringcase/__init__.pyi @@ -0,0 +1,2 @@ +def snakecase(_: str): + ... diff --git a/python-packages/json_schemas/test/__init__.py b/python-packages/json_schemas/test/__init__.py new file mode 100644 index 000000000..ce724e180 --- /dev/null +++ b/python-packages/json_schemas/test/__init__.py @@ -0,0 +1 @@ +"""Tests of zero_ex.json_schemas.""" diff --git a/python-packages/json_schemas/test/test_doctest.py b/python-packages/json_schemas/test/test_doctest.py new file mode 100644 index 000000000..2aa576422 --- /dev/null +++ b/python-packages/json_schemas/test/test_doctest.py @@ -0,0 +1,25 @@ +"""Exercise doctests for all of our modules.""" + +from doctest import testmod +import pkgutil +import importlib + +import zero_ex.json_schemas + + +def test_all_doctests(): + """Gather zero_ex.json_schemas.* modules and doctest them.""" + # json_schemas module + module = "zero_ex.json_schemas" + print(module) + failure_count, _ = testmod(importlib.import_module(module)) + assert failure_count == 0 + + # any json_schemas.* sub-modules + for (_, modname, _) in pkgutil.walk_packages( + path=zero_ex.json_schemas.__path__, prefix="zero_ex.json_schemas" + ): + module = importlib.import_module(modname) + print(module) + (failure_count, _) = testmod(module) + assert failure_count == 0 diff --git a/python-packages/json_schemas/test/test_json_schemas.py b/python-packages/json_schemas/test/test_json_schemas.py new file mode 100644 index 000000000..d0e9840b3 --- /dev/null +++ b/python-packages/json_schemas/test/test_json_schemas.py @@ -0,0 +1,41 @@ +"""Tests of zero_ex.json_schemas""" + + +from zero_ex.json_schemas import _LOCAL_RESOLVER, assert_valid + + +NULL_ADDRESS = "0x0000000000000000000000000000000000000000" + +EMPTY_ORDER = { + "makerAddress": NULL_ADDRESS, + "takerAddress": NULL_ADDRESS, + "senderAddress": NULL_ADDRESS, + "feeRecipientAddress": NULL_ADDRESS, + "makerAssetData": NULL_ADDRESS, + "takerAssetData": NULL_ADDRESS, + "salt": "0", + "makerFee": "0", + "takerFee": "0", + "makerAssetAmount": "0", + "takerAssetAmount": "0", + "expirationTimeSeconds": "0", + "exchangeAddress": NULL_ADDRESS, +} + + +def test_assert_valid_caches_resources(): + """Test that the JSON ref resolver in `assert_valid()` caches resources + + In order to test the cache we much access the private class of + `json_schemas` and reset the LRU cache on `_LocalRefResolver`. + For this to happen, we need to disable errror `W0212` + on _LOCAL_RESOLVER + """ + _LOCAL_RESOLVER._remote_cache.cache_clear() # pylint: disable=W0212 + + assert_valid(EMPTY_ORDER, "/orderSchema") + cache_info = ( + _LOCAL_RESOLVER._remote_cache.cache_info() # pylint: disable=W0212 + ) + assert cache_info.currsize == 4 + assert cache_info.hits == 10 diff --git a/python-packages/json_schemas/tox.ini b/python-packages/json_schemas/tox.ini new file mode 100644 index 000000000..1d5de646e --- /dev/null +++ b/python-packages/json_schemas/tox.ini @@ -0,0 +1,25 @@ +# tox (https://tox.readthedocs.io/) is a tool for running tests +# in multiple virtualenvs. This configuration file will run the +# test suite on all supported python versions. To use it, "pip install tox" +# and then run "tox" from this directory. + +[tox] +envlist = py37 + +[testenv] +commands = + pip install -e .[dev] + python setup.py test + +[testenv:run_tests_against_test_deployment] +commands = + # install dependencies from real PyPI + pip install jsonschema mypy_extensions pytest + # install package-under-test from test PyPI + pip install --index-url https://test.pypi.org/legacy/ 0x-json-schemas + pytest test + +[testenv:run_tests_against_deployment] +commands = + pip install 0x-json-schemas + pytest test diff --git a/python-packages/order_utils/setup.py b/python-packages/order_utils/setup.py index 125de5ff7..06533e60a 100755 --- a/python-packages/order_utils/setup.py +++ b/python-packages/order_utils/setup.py @@ -137,14 +137,8 @@ class GanacheCommand(distutils.command.build_py.build_py): def run(self): """Run ganache.""" cmd_line = ( - "docker run -d -p 8545:8545 0xorg/ganache-cli --gasLimit" - + " 10000000 --db /snapshot --noVMErrorsOnRPCResponse -p 8545" - + " --networkId 50 -m" + "docker run -d -p 8545:8545 0xorg/ganache-cli:2.2.2" ).split() - cmd_line.append( - "concert load couple harbor equip island argue ramp clarify fence" - + " smart topic" - ) subprocess.call(cmd_line) # nosec @@ -171,9 +165,9 @@ setup( "ganache": GanacheCommand, }, install_requires=[ + "0x-json-schemas", "eth-abi", "eth_utils", - "jsonschema", "mypy_extensions", "web3", ], @@ -198,7 +192,6 @@ setup( package_data={ "zero_ex.order_utils": ["py.typed"], "zero_ex.contract_artifacts": ["artifacts/*"], - "zero_ex.json_schemas": ["schemas/*"], }, package_dir={"": "src"}, license="Apache 2.0", diff --git a/python-packages/order_utils/src/index.rst b/python-packages/order_utils/src/index.rst index 551487ab1..4d27a4b17 100644 --- a/python-packages/order_utils/src/index.rst +++ b/python-packages/order_utils/src/index.rst @@ -22,9 +22,6 @@ See source for class properties. Sphinx does not easily generate class property .. autoclass:: zero_ex.order_utils.asset_data_utils.ERC721AssetData -.. automodule:: zero_ex.json_schemas - :members: - Indices and tables ================== diff --git a/python-packages/order_utils/src/zero_ex/dev_utils/type_assertions.py b/python-packages/order_utils/src/zero_ex/dev_utils/type_assertions.py index 1dcfb39a9..4681315a8 100644 --- a/python-packages/order_utils/src/zero_ex/dev_utils/type_assertions.py +++ b/python-packages/order_utils/src/zero_ex/dev_utils/type_assertions.py @@ -80,8 +80,6 @@ def assert_is_provider(value: Any, name: str) -> None: If `value` isn't a Web3 provider, raise a TypeError. """ - # TODO: make this provider check more flexible. - # https://app.asana.com/0/684263176955174/901300863045491/f if not isinstance(value, BaseProvider): raise TypeError( f"Expected variable '{name}' to be an instance of a Web3 provider," diff --git a/python-packages/order_utils/src/zero_ex/json_schemas/__init__.py b/python-packages/order_utils/src/zero_ex/json_schemas/__init__.py deleted file mode 100644 index 2a1728b8a..000000000 --- a/python-packages/order_utils/src/zero_ex/json_schemas/__init__.py +++ /dev/null @@ -1,61 +0,0 @@ -"""JSON schemas and associated utilities.""" - -from os import path -import json -from typing import Mapping - -from pkg_resources import resource_string -import jsonschema - - -def assert_valid(data: Mapping, schema_id: str) -> None: - """Validate the given `data` against the specified `schema`. - - :param data: Python dictionary to be validated as a JSON object. - :param schema_id: id property of the JSON schema to validate against. Must - be one of those listed in `the 0x JSON schema files - <https://github.com/0xProject/0x-monorepo/tree/development/packages/json-schemas/schemas>`_. - - Raises an exception if validation fails. - - >>> assert_valid( - ... {'v': 27, 'r': '0x'+'f'*64, 's': '0x'+'f'*64}, - ... '/ECSignature', - ... ) - """ - # noqa - class LocalRefResolver(jsonschema.RefResolver): - """Resolve package-local JSON schema id's.""" - - def __init__(self): - self.ref_to_file = { - "/addressSchema": "address_schema.json", - "/hexSchema": "hex_schema.json", - "/orderSchema": "order_schema.json", - "/wholeNumberSchema": "whole_number_schema.json", - "/ECSignature": "ec_signature_schema.json", - "/ecSignatureParameterSchema": ( - "ec_signature_parameter_schema.json" + "" - ), - } - jsonschema.RefResolver.__init__(self, "", "") - - def resolve_from_url(self, url): - """Resolve the given URL.""" - ref = url.replace("file://", "") - if ref in self.ref_to_file: - return json.loads( - resource_string( - "zero_ex.json_schemas", - f"schemas/{self.ref_to_file[ref]}", - ) - ) - raise jsonschema.ValidationError( - f"Unknown ref '{ref}'. " - + f"Known refs: {list(self.ref_to_file.keys())}." - ) - - resolver = LocalRefResolver() - jsonschema.validate( - data, resolver.resolve_from_url(schema_id), resolver=resolver - ) diff --git a/python-packages/order_utils/stubs/jsonschema/__init__.pyi b/python-packages/order_utils/stubs/jsonschema/__init__.pyi deleted file mode 100644 index 762b58b22..000000000 --- a/python-packages/order_utils/stubs/jsonschema/__init__.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from typing import Any, Dict - -class RefResolver: pass - -def validate(instance: Any, schema: Dict, cls=None, *args, **kwargs) -> None: pass diff --git a/python-packages/order_utils/stubs/web3/__init___BASE_31011.pyi b/python-packages/order_utils/stubs/web3/__init___BASE_31011.pyi new file mode 100644 index 000000000..fcecc7434 --- /dev/null +++ b/python-packages/order_utils/stubs/web3/__init___BASE_31011.pyi @@ -0,0 +1,26 @@ +from typing import Dict, Optional, Union + +from web3.utils import datatypes + + +class Web3: + class HTTPProvider: ... + + def __init__(self, provider: HTTPProvider) -> None: ... + + @staticmethod + def sha3( + primitive: Optional[Union[bytes, int, None]] = None, + text: Optional[str] = None, + hexstr: Optional[str] = None + ) -> bytes: ... + + class net: + version: str + ... + + class eth: + @staticmethod + def contract(address: str, abi: Dict) -> datatypes.Contract: ... + ... + ... diff --git a/python-packages/order_utils/test/test_doctest.py b/python-packages/order_utils/test/test_doctest.py index f692b3b6c..297f75e75 100644 --- a/python-packages/order_utils/test/test_doctest.py +++ b/python-packages/order_utils/test/test_doctest.py @@ -2,16 +2,17 @@ from doctest import testmod import pkgutil +import importlib import zero_ex def test_all_doctests(): """Gather zero_ex.* modules and doctest them.""" - for (importer, modname, _) in pkgutil.walk_packages( + for (_, modname, _) in pkgutil.walk_packages( path=zero_ex.__path__, prefix="zero_ex." ): - module = importer.find_module(modname).load_module(modname) + module = importlib.import_module(modname) print(module) (failure_count, _) = testmod(module) assert failure_count == 0 diff --git a/python-packages/sra_client/README.md b/python-packages/sra_client/README.md new file mode 100644 index 000000000..279fb41a4 --- /dev/null +++ b/python-packages/sra_client/README.md @@ -0,0 +1,332 @@ +# 0x-sra-client + +A Python client for interacting with servers conforming to [the Standard Relayer API specification](https://github.com/0xProject/0x-monorepo/tree/development/packages/sra-spec). + +# Schemas + +The [JSON schemas](http://json-schema.org/) for the API payloads and responses can be found in [@0xproject/json-schemas](https://github.com/0xProject/0x.js/tree/development/packages/json-schemas). Examples of each payload and response can be found in the 0x.js library's [test suite](https://github.com/0xProject/0x.js/blob/development/packages/json-schemas/test/schema_test.ts#L1). + +```bash +pip install 0x-json-schemas +``` + +You can easily validate your API's payloads and responses using the [0x-json-schemas](https://github.com/0xProject/0x.js/tree/development/python-packages/json_schemas) package: + +```python +from zero_ex.json_schemas import assert_valid +from zero_ex.order_utils import Order + +order: Order = { + 'makerAddress': "0x0000000000000000000000000000000000000000", + 'takerAddress': "0x0000000000000000000000000000000000000000", + 'feeRecipientAddress': "0x0000000000000000000000000000000000000000", + 'senderAddress': "0x0000000000000000000000000000000000000000", + 'makerAssetAmount': "1000000000000000000", + 'takerAssetAmount': "1000000000000000000", + 'makerFee': "0", + 'takerFee': "0", + 'expirationTimeSeconds': "12345", + 'salt': "12345", + 'makerAssetData': "0x0000000000000000000000000000000000000000", + 'takerAssetData': "0x0000000000000000000000000000000000000000", + 'exchangeAddress': "0x0000000000000000000000000000000000000000", +} + +assert_valid(order, "/orderSchema") +``` + +# Pagination + +Requests that return potentially large collections should respond to the **?page** and **?perPage** parameters. For example: + +```bash +$ curl https://api.example-relayer.com/v2/asset_pairs?page=3&perPage=20 +``` + +Page numbering should be 1-indexed, not 0-indexed. If a query provides an unreasonable (ie. too high) `perPage` value, the response can return a validation error as specified in the [errors section](#section/Errors). If the query specifies a `page` that does not exist (ie. there are not enough `records`), the response should just return an empty `records` array. + +All endpoints that are paginated should return a `total`, `page`, `perPage` and a `records` value in the top level of the collection. The value of `total` should be the total number of records for a given query, whereas `records` should be an array representing the response to the query for that page. `page` and `perPage`, are the same values that were specified in the request. See the note in [miscellaneous](#section/Misc.) about formatting `snake_case` vs. `lowerCamelCase`. + +These requests include the [`/v2/asset_pairs`](#operation/getAssetPairs), [`/v2/orders`](#operation/getOrders), [`/v2/fee_recipients`](#operation/getFeeRecipients) and [`/v2/orderbook`](#operation/getOrderbook) endpoints. + +# Network Id + +All requests should be able to specify a **?networkId** query param for all supported networks. For example: + +```bash +$ curl https://api.example-relayer.com/v2/asset_pairs?networkId=1 +``` + +If the query param is not provided, it should default to **1** (mainnet). + +Networks and their Ids: + +| Network Id | Network Name | +| ---------- | ------------ | +| 1 | Mainnet | +| 42 | Kovan | +| 3 | Ropsten | +| 4 | Rinkeby | + +If a certain network is not supported, the response should **400** as specified in the [error response](#section/Errors) section. For example: + +```json +{ + \"code\": 100, + \"reason\": \"Validation failed\", + \"validationErrors\": [ + { + \"field\": \"networkId\", + \"code\": 1006, + \"reason\": \"Network id 42 is not supported\" + } + ] +} +``` + +# Link Header + +A [Link Header](https://tools.ietf.org/html/rfc5988) can be included in a response to provide clients with more context about paging +For example: + +```bash +Link: <https://api.example-relayer.com/v2/asset_pairs?page=3&perPage=20>; rel=\"next\", +<https://api.github.com/user/repos?page=10&perPage=20>; rel=\"last\" +``` + +This `Link` response header contains one or more Hypermedia link relations. + +The possible `rel` values are: + +| Name | Description | +| ----- | ------------------------------------------------------------- | +| next | The link relation for the immediate next page of results. | +| last | The link relation for the last page of results. | +| first | The link relation for the first page of results. | +| prev | The link relation for the immediate previous page of results. | + +# Rate Limits + +Rate limit guidance for clients can be optionally returned in the response headers: + +| Header Name | Description | +| --------------------- | ---------------------------------------------------------------------------- | +| X-RateLimit-Limit | The maximum number of requests you're permitted to make per hour. | +| X-RateLimit-Remaining | The number of requests remaining in the current rate limit window. | +| X-RateLimit-Reset | The time at which the current rate limit window resets in UTC epoch seconds. | + +For example: + +```bash +$ curl -i https://api.example-relayer.com/v2/asset_pairs +HTTP/1.1 200 OK +Date: Mon, 20 Oct 2017 12:30:06 GMT +Status: 200 OK +X-RateLimit-Limit: 60 +X-RateLimit-Remaining: 56 +X-RateLimit-Reset: 1372700873 +``` + +When a rate limit is exceeded, a status of **429 Too Many Requests** should be returned. + +# Errors + +Unless the spec defines otherwise, errors to bad requests should respond with HTTP 4xx or status codes. + +## Common error codes + +| Code | Reason | +| ---- | --------------------------------------- | +| 400 | Bad Request – Invalid request format | +| 404 | Not found | +| 429 | Too many requests - Rate limit exceeded | +| 500 | Internal Server Error | +| 501 | Not Implemented | + +## Error reporting format + +For all **400** responses, see the [error response schema](https://github.com/0xProject/0x-monorepo/blob/development/packages/json-schemas/schemas/relayer_api_error_response_schema.ts#L1). + +```json +{ + \"code\": 101, + \"reason\": \"Validation failed\", + \"validationErrors\": [ + { + \"field\": \"maker\", + \"code\": 1002, + \"reason\": \"Invalid address\" + } + ] +} +``` + +General error codes: + +```bash +100 - Validation Failed +101 - Malformed JSON +102 - Order submission disabled +103 - Throttled +``` + +Validation error codes: + +```bash +1000 - Required field +1001 - Incorrect format +1002 - Invalid address +1003 - Address not supported +1004 - Value out of range +1005 - Invalid signature or hash +1006 - Unsupported option +``` + +# Asset Data Encoding + +As we now support multiple [token transfer proxies](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#assetproxy), the identifier of which proxy to use for the token transfer must be encoded, along with the token information. Each proxy in 0x v2 has a unique identifier. If you're using 0x.js there will be helper methods for this [encoding](https://0xproject.com/docs/0x.js#zeroEx-encodeERC20AssetData) and [decoding](https://0xproject.com/docs/0x.js#zeroEx-decodeAssetProxyId). + +The identifier for the Proxy uses a similar scheme to [ABI function selectors](https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI#function-selector). + +```js +// ERC20 Proxy ID 0xf47261b0 +bytes4(keccak256('ERC20Token(address)')); +// ERC721 Proxy ID 0x02571792 +bytes4(keccak256('ERC721Token(address,uint256)')); +``` + +Asset data is encoded using [ABI encoding](https://solidity.readthedocs.io/en/develop/abi-spec.html). + +For example, encoding the ERC20 token contract (address: 0x1dc4c1cefef38a777b15aa20260a54e584b16c48) using the ERC20 Transfer Proxy (id: 0xf47261b0) would be: + +```bash +0xf47261b00000000000000000000000001dc4c1cefef38a777b15aa20260a54e584b16c48 +``` + +Encoding the ERC721 token contract (address: `0x371b13d97f4bf77d724e78c16b7dc74099f40e84`), token id (id: `99`, which hex encoded is `0x63`) and the ERC721 Transfer Proxy (id: 0x02571792) would be: + +```bash +0x02571792000000000000000000000000371b13d97f4bf77d724e78c16b7dc74099f40e840000000000000000000000000000000000000000000000000000000000000063 +``` + +For more information see [the Asset Proxy](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#erc20proxy) section of the v2 spec and the [Ethereum ABI Spec](https://solidity.readthedocs.io/en/develop/abi-spec.html). + +# Meta Data in Order Responses + +In v2 of the standard relayer API we added the `metaData` field. It is meant to provide a standard place for relayers to put optional, custom or non-standard fields that may of interest to the consumer of the API. + +A good example of such a field is `remainingTakerAssetAmount`, which is a convenience field that communicates how much of a 0x order is potentially left to be filled. Unlike the other fields in a 0x order, it is not guaranteed to be correct as it is derived from whatever mechanism the implementer (ie. the relayer) is using. While convenient for prototyping and low stakes situations, we recommend validating the value of the field by checking the state of the blockchain yourself, such as by using [Order Watcher](https://0xproject.com/wiki#0x-OrderWatcher). + +# Misc. + +* All requests and responses should be of **application/json** content type +* All token amounts are sent in amounts of the smallest level of precision (base units). (e.g if a token has 18 decimal places, selling 1 token would show up as selling `'1000000000000000000'` units by this API). +* All addresses are sent as lower-case (non-checksummed) Ethereum addresses with the `0x` prefix. +* All parameters are to be written in `lowerCamelCase`. + +This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +* API version: 2.0.0 +* Package version: 1.0.0 +* Build package: org.openapitools.codegen.languages.PythonClientCodegen + +## Requirements. + +Python 2.7 and 3.4+ + +## Installation & Usage + +### pip install + +If the python package is hosted on Github, you can install directly from Github + +```sh +pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git +``` + +(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git`) + +Then import the package: + +```python +import sra_client +``` + +### Setuptools + +Install via [Setuptools](http://pypi.python.org/pypi/setuptools). + +```sh +python setup.py install --user +``` + +(or `sudo python setup.py install` to install the package for all users) + +Then import the package: + +```python +import sra_client +``` + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```python +from __future__ import print_function +import time +import sra_client +from sra_client.rest import ApiException +from pprint import pprint + +# create an instance of the API class +api_instance = sra_client.DefaultApi(sra_client.ApiClient(configuration)) +asset_data_a = 0xf47261b04c32345ced77393b3530b1eed0f346429d # str | The assetData value for the first asset in the pair. (optional) +asset_data_b = 0x0257179264389b814a946f3e92105513705ca6b990 # str | The assetData value for the second asset in the pair. (optional) +network_id = 42 # float | The id of the Ethereum network (optional) (default to 1) +page = 3 # float | The number of the page to request in the collection. (optional) (default to 1) +per_page = 10 # float | The number of records to return per page. (optional) (default to 100) + +try: + api_response = api_instance.get_asset_pairs(asset_data_a=asset_data_a, asset_data_b=asset_data_b, network_id=network_id, page=page, per_page=per_page) + pprint(api_response) +except ApiException as e: + print("Exception when calling DefaultApi->get_asset_pairs: %s\n" % e) +``` + +## Documentation for API Endpoints + +All URIs are relative to _http://localhost_ + +| Class | Method | HTTP request | Description | +| ------------ | --------------------------------------------------------------- | ----------------------------- | ----------- | +| _DefaultApi_ | [**get_asset_pairs**](docs/DefaultApi.md#get_asset_pairs) | **GET** /v2/asset_pairs | +| _DefaultApi_ | [**get_fee_recipients**](docs/DefaultApi.md#get_fee_recipients) | **GET** /v2/fee_recipients | +| _DefaultApi_ | [**get_order**](docs/DefaultApi.md#get_order) | **GET** /v2/order/{orderHash} | +| _DefaultApi_ | [**get_order_config**](docs/DefaultApi.md#get_order_config) | **POST** /v2/order_config | +| _DefaultApi_ | [**get_orderbook**](docs/DefaultApi.md#get_orderbook) | **GET** /v2/orderbook | +| _DefaultApi_ | [**get_orders**](docs/DefaultApi.md#get_orders) | **GET** /v2/orders | +| _DefaultApi_ | [**post_order**](docs/DefaultApi.md#post_order) | **POST** /v2/order | + +## Documentation For Models + +* [OrderSchema](docs/OrderSchema.md) +* [PaginatedCollectionSchema](docs/PaginatedCollectionSchema.md) +* [RelayerApiAssetDataPairsResponseSchema](docs/RelayerApiAssetDataPairsResponseSchema.md) +* [RelayerApiAssetDataTradeInfoSchema](docs/RelayerApiAssetDataTradeInfoSchema.md) +* [RelayerApiErrorResponseSchema](docs/RelayerApiErrorResponseSchema.md) +* [RelayerApiErrorResponseSchemaValidationErrors](docs/RelayerApiErrorResponseSchemaValidationErrors.md) +* [RelayerApiFeeRecipientsResponseSchema](docs/RelayerApiFeeRecipientsResponseSchema.md) +* [RelayerApiOrderConfigPayloadSchema](docs/RelayerApiOrderConfigPayloadSchema.md) +* [RelayerApiOrderConfigResponseSchema](docs/RelayerApiOrderConfigResponseSchema.md) +* [RelayerApiOrderSchema](docs/RelayerApiOrderSchema.md) +* [RelayerApiOrderbookResponseSchema](docs/RelayerApiOrderbookResponseSchema.md) +* [RelayerApiOrdersChannelSubscribePayloadSchema](docs/RelayerApiOrdersChannelSubscribePayloadSchema.md) +* [RelayerApiOrdersChannelSubscribeSchema](docs/RelayerApiOrdersChannelSubscribeSchema.md) +* [RelayerApiOrdersChannelUpdateSchema](docs/RelayerApiOrdersChannelUpdateSchema.md) +* [RelayerApiOrdersResponseSchema](docs/RelayerApiOrdersResponseSchema.md) +* [SignedOrderSchema](docs/SignedOrderSchema.md) + +## Documentation For Authorization + +All endpoints do not require authorization. diff --git a/python-packages/sra_client/docs/DefaultApi.md b/python-packages/sra_client/docs/DefaultApi.md new file mode 100644 index 000000000..942188bc6 --- /dev/null +++ b/python-packages/sra_client/docs/DefaultApi.md @@ -0,0 +1,397 @@ +# sra_client.DefaultApi + +All URIs are relative to _http://localhost_ + +| Method | HTTP request | Description | +| ---------------------------------------------------------- | ----------------------------- | ----------- | +| [**get_asset_pairs**](DefaultApi.md#get_asset_pairs) | **GET** /v2/asset_pairs | +| [**get_fee_recipients**](DefaultApi.md#get_fee_recipients) | **GET** /v2/fee_recipients | +| [**get_order**](DefaultApi.md#get_order) | **GET** /v2/order/{orderHash} | +| [**get_order_config**](DefaultApi.md#get_order_config) | **POST** /v2/order_config | +| [**get_orderbook**](DefaultApi.md#get_orderbook) | **GET** /v2/orderbook | +| [**get_orders**](DefaultApi.md#get_orders) | **GET** /v2/orders | +| [**post_order**](DefaultApi.md#post_order) | **POST** /v2/order | + +# **get_asset_pairs** + +> RelayerApiAssetDataPairsResponseSchema get_asset_pairs(asset_data_a=asset_data_a, asset_data_b=asset_data_b, network_id=network_id, page=page, per_page=per_page) + +Retrieves a list of available asset pairs and the information required to trade them (in any order). Setting only `assetDataA` or `assetDataB` returns pairs filtered by that asset only. + +### Example + +```python +from __future__ import print_function +import time +import sra_client +from sra_client.rest import ApiException +from pprint import pprint + +# create an instance of the API class +api_instance = sra_client.DefaultApi() +asset_data_a = 0xf47261b04c32345ced77393b3530b1eed0f346429d # str | The assetData value for the first asset in the pair. (optional) +asset_data_b = 0x0257179264389b814a946f3e92105513705ca6b990 # str | The assetData value for the second asset in the pair. (optional) +network_id = 42 # float | The id of the Ethereum network (optional) (default to 1) +page = 3 # float | The number of the page to request in the collection. (optional) (default to 1) +per_page = 10 # float | The number of records to return per page. (optional) (default to 100) + +try: + api_response = api_instance.get_asset_pairs(asset_data_a=asset_data_a, asset_data_b=asset_data_b, network_id=network_id, page=page, per_page=per_page) + pprint(api_response) +except ApiException as e: + print("Exception when calling DefaultApi->get_asset_pairs: %s\n" % e) +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---------------- | --------- | ----------------------------------------------------- | -------------------------- | +| **asset_data_a** | **str** | The assetData value for the first asset in the pair. | [optional] | +| **asset_data_b** | **str** | The assetData value for the second asset in the pair. | [optional] | +| **network_id** | **float** | The id of the Ethereum network | [optional][default to 1] | +| **page** | **float** | The number of the page to request in the collection. | [optional][default to 1] | +| **per_page** | **float** | The number of records to return per page. | [optional][default to 100] | + +### Return type + +[**RelayerApiAssetDataPairsResponseSchema**](RelayerApiAssetDataPairsResponseSchema.md) + +### Authorization + +No authorization required + +### HTTP request headers + +* **Content-Type**: Not defined +* **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_fee_recipients** + +> RelayerApiFeeRecipientsResponseSchema get_fee_recipients(network_id=network_id, page=page, per_page=per_page) + +Retrieves a collection of all fee recipient addresses for a relayer. This endpoint should be [paginated](#section/Pagination). + +### Example + +```python +from __future__ import print_function +import time +import sra_client +from sra_client.rest import ApiException +from pprint import pprint + +# create an instance of the API class +api_instance = sra_client.DefaultApi() +network_id = 42 # float | The id of the Ethereum network (optional) (default to 1) +page = 3 # float | The number of the page to request in the collection. (optional) (default to 1) +per_page = 10 # float | The number of records to return per page. (optional) (default to 100) + +try: + api_response = api_instance.get_fee_recipients(network_id=network_id, page=page, per_page=per_page) + pprint(api_response) +except ApiException as e: + print("Exception when calling DefaultApi->get_fee_recipients: %s\n" % e) +``` + +### Parameters + +| Name | Type | Description | Notes | +| -------------- | --------- | ---------------------------------------------------- | -------------------------- | +| **network_id** | **float** | The id of the Ethereum network | [optional][default to 1] | +| **page** | **float** | The number of the page to request in the collection. | [optional][default to 1] | +| **per_page** | **float** | The number of records to return per page. | [optional][default to 100] | + +### Return type + +[**RelayerApiFeeRecipientsResponseSchema**](RelayerApiFeeRecipientsResponseSchema.md) + +### Authorization + +No authorization required + +### HTTP request headers + +* **Content-Type**: Not defined +* **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_order** + +> RelayerApiOrderSchema get_order(order_hash, network_id=network_id) + +Retrieves the 0x order with meta info that is associated with the hash. + +### Example + +```python +from __future__ import print_function +import time +import sra_client +from sra_client.rest import ApiException +from pprint import pprint + +# create an instance of the API class +api_instance = sra_client.DefaultApi() +order_hash = 0xd4b103c42d2512eef3fee775e097f044291615d25f5d71e0ac70dbd49d223591 # str | The hash of the desired 0x order. +network_id = 42 # float | The id of the Ethereum network (optional) (default to 1) + +try: + api_response = api_instance.get_order(order_hash, network_id=network_id) + pprint(api_response) +except ApiException as e: + print("Exception when calling DefaultApi->get_order: %s\n" % e) +``` + +### Parameters + +| Name | Type | Description | Notes | +| -------------- | --------- | --------------------------------- | ------------------------ | +| **order_hash** | **str** | The hash of the desired 0x order. | +| **network_id** | **float** | The id of the Ethereum network | [optional][default to 1] | + +### Return type + +[**RelayerApiOrderSchema**](RelayerApiOrderSchema.md) + +### Authorization + +No authorization required + +### HTTP request headers + +* **Content-Type**: Not defined +* **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_order_config** + +> RelayerApiOrderConfigResponseSchema get_order_config(network_id=network_id, relayer_api_order_config_payload_schema=relayer_api_order_config_payload_schema) + +Relayers have full discretion over the orders that they are willing to host on their orderbooks (e.g what fees they charge, etc...). In order for traders to discover their requirements programmatically, they can send an incomplete order to this endpoint and receive the missing fields, specifc to that order. This gives relayers a large amount of flexibility to tailor fees to unique traders, trading pairs and volume amounts. Submit a partial order and receive information required to complete the order: `senderAddress`, `feeRecipientAddress`, `makerFee`, `takerFee`. + +### Example + +```python +from __future__ import print_function +import time +import sra_client +from sra_client.rest import ApiException +from pprint import pprint + +# create an instance of the API class +api_instance = sra_client.DefaultApi() +network_id = 42 # float | The id of the Ethereum network (optional) (default to 1) +relayer_api_order_config_payload_schema = {"makerAddress":"0x9e56625509c2f60af937f23b7b532600390e8c8b","takerAddress":"0xa2b31dacf30a9c50ca473337c01d8a201ae33e32","makerAssetAmount":"10000000000000000","takerAssetAmount":"1","makerAssetData":"0xf47261b0000000000000000000000000e41d2489571d322189246dafa5ebde1f4699f498","takerAssetData":"0x02571792000000000000000000000000371b13d97f4bf77d724e78c16b7dc74099f40e840000000000000000000000000000000000000000000000000000000000000063","exchangeAddress":"0x12459c951127e0c374ff9105dda097662a027093","expirationTimeSeconds":"1532560590"} # RelayerApiOrderConfigPayloadSchema | The fields of a 0x order the relayer may want to decide what configuration to send back. (optional) + +try: + api_response = api_instance.get_order_config(network_id=network_id, relayer_api_order_config_payload_schema=relayer_api_order_config_payload_schema) + pprint(api_response) +except ApiException as e: + print("Exception when calling DefaultApi->get_order_config: %s\n" % e) +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------------------------------------- | ------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ------------------------ | +| **network_id** | **float** | The id of the Ethereum network | [optional][default to 1] | +| **relayer_api_order_config_payload_schema** | [**RelayerApiOrderConfigPayloadSchema**](RelayerApiOrderConfigPayloadSchema.md) | The fields of a 0x order the relayer may want to decide what configuration to send back. | [optional] | + +### Return type + +[**RelayerApiOrderConfigResponseSchema**](RelayerApiOrderConfigResponseSchema.md) + +### Authorization + +No authorization required + +### HTTP request headers + +* **Content-Type**: application/json +* **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_orderbook** + +> RelayerApiOrderbookResponseSchema get_orderbook(base_asset_data, quote_asset_data, network_id=network_id, page=page, per_page=per_page) + +Retrieves the orderbook for a given asset pair. This endpoint should be [paginated](#section/Pagination). Bids will be sorted in descending order by price, and asks will be sorted in ascending order by price. Within the price sorted orders, the orders are further sorted by _taker fee price_ which is defined as the **takerFee** divided by **takerTokenAmount**. After _taker fee price_, orders are to be sorted by expiration in ascending order. The way pagination works for this endpoint is that the **page** and **perPage** query params apply to both `bids` and `asks` collections, and if `page` \* `perPage` > `total` for a certain collection, the `records` for that collection should just be empty. + +### Example + +```python +from __future__ import print_function +import time +import sra_client +from sra_client.rest import ApiException +from pprint import pprint + +# create an instance of the API class +api_instance = sra_client.DefaultApi() +base_asset_data = 0xf47261b04c32345ced77393b3530b1eed0f346429d # str | assetData (makerAssetData or takerAssetData) designated as the base currency in the [currency pair calculation](https://en.wikipedia.org/wiki/Currency_pair) of price. +quote_asset_data = 0xf47261b04c32345ced77393b3530b1eed0f346429d # str | assetData (makerAssetData or takerAssetData) designated as the quote currency in the currency pair calculation of price (required). +network_id = 42 # float | The id of the Ethereum network (optional) (default to 1) +page = 3 # float | The number of the page to request in the collection. (optional) (default to 1) +per_page = 10 # float | The number of records to return per page. (optional) (default to 100) + +try: + api_response = api_instance.get_orderbook(base_asset_data, quote_asset_data, network_id=network_id, page=page, per_page=per_page) + pprint(api_response) +except ApiException as e: + print("Exception when calling DefaultApi->get_orderbook: %s\n" % e) +``` + +### Parameters + +| Name | Type | Description | Notes | +| -------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | +| **base_asset_data** | **str** | assetData (makerAssetData or takerAssetData) designated as the base currency in the [currency pair calculation](https://en.wikipedia.org/wiki/Currency_pair) of price. | +| **quote_asset_data** | **str** | assetData (makerAssetData or takerAssetData) designated as the quote currency in the currency pair calculation of price (required). | +| **network_id** | **float** | The id of the Ethereum network | [optional][default to 1] | +| **page** | **float** | The number of the page to request in the collection. | [optional][default to 1] | +| **per_page** | **float** | The number of records to return per page. | [optional][default to 100] | + +### Return type + +[**RelayerApiOrderbookResponseSchema**](RelayerApiOrderbookResponseSchema.md) + +### Authorization + +No authorization required + +### HTTP request headers + +* **Content-Type**: Not defined +* **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_orders** + +> RelayerApiOrdersResponseSchema get_orders(maker_asset_proxy_id=maker_asset_proxy_id, taker_asset_proxy_id=taker_asset_proxy_id, maker_asset_address=maker_asset_address, taker_asset_address=taker_asset_address, exchange_address=exchange_address, sender_address=sender_address, maker_asset_data=maker_asset_data, taker_asset_data=taker_asset_data, trader_asset_data=trader_asset_data, maker_address=maker_address, taker_address=taker_address, trader_address=trader_address, fee_recipient_address=fee_recipient_address, network_id=network_id, page=page, per_page=per_page) + +Retrieves a list of orders given query parameters. This endpoint should be [paginated](#section/Pagination). For querying an entire orderbook snapshot, the [orderbook endpoint](#operation/getOrderbook) is recommended. If both makerAssetData and takerAssetData are specified, returned orders will be sorted by price determined by (takerTokenAmount/makerTokenAmount) in ascending order. By default, orders returned by this endpoint are unsorted. + +### Example + +```python +from __future__ import print_function +import time +import sra_client +from sra_client.rest import ApiException +from pprint import pprint + +# create an instance of the API class +api_instance = sra_client.DefaultApi() +maker_asset_proxy_id = 0xf47261b0 # str | The maker [asset proxy id](https://0xproject.com/docs/0x.js#types-AssetProxyId) (example: \"0xf47261b0\" for ERC20, \"0x02571792\" for ERC721). (optional) +taker_asset_proxy_id = 0x02571792 # str | The taker asset [asset proxy id](https://0xproject.com/docs/0x.js#types-AssetProxyId) (example: \"0xf47261b0\" for ERC20, \"0x02571792\" for ERC721). (optional) +maker_asset_address = 0xe41d2489571d322189246dafa5ebde1f4699f498 # str | The contract address for the maker asset. (optional) +taker_asset_address = 0xe41d2489571d322189246dafa5ebde1f4699f498 # str | The contract address for the taker asset. (optional) +exchange_address = 0xe41d2489571d322189246dafa5ebde1f4699f498 # str | Same as exchangeAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) (optional) +sender_address = 0xe41d2489571d322189246dafa5ebde1f4699f498 # str | Same as senderAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) (optional) +maker_asset_data = 0xe41d2489571d322189246dafa5ebde1f4699f498 # str | Same as makerAssetData in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) (optional) +taker_asset_data = 0xe41d2489571d322189246dafa5ebde1f4699f498 # str | Same as takerAssetData in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) (optional) +trader_asset_data = 0xe41d2489571d322189246dafa5ebde1f4699f498 # str | Same as traderAssetData in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) (optional) +maker_address = 0xe41d2489571d322189246dafa5ebde1f4699f498 # str | Same as makerAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) (optional) +taker_address = 0xe41d2489571d322189246dafa5ebde1f4699f498 # str | Same as takerAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) (optional) +trader_address = 0xe41d2489571d322189246dafa5ebde1f4699f498 # str | Same as traderAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) (optional) +fee_recipient_address = 0xe41d2489571d322189246dafa5ebde1f4699f498 # str | Same as feeRecipientAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) (optional) +network_id = 42 # float | The id of the Ethereum network (optional) (default to 1) +page = 3 # float | The number of the page to request in the collection. (optional) (default to 1) +per_page = 10 # float | The number of records to return per page. (optional) (default to 100) + +try: + api_response = api_instance.get_orders(maker_asset_proxy_id=maker_asset_proxy_id, taker_asset_proxy_id=taker_asset_proxy_id, maker_asset_address=maker_asset_address, taker_asset_address=taker_asset_address, exchange_address=exchange_address, sender_address=sender_address, maker_asset_data=maker_asset_data, taker_asset_data=taker_asset_data, trader_asset_data=trader_asset_data, maker_address=maker_address, taker_address=taker_address, trader_address=trader_address, fee_recipient_address=fee_recipient_address, network_id=network_id, page=page, per_page=per_page) + pprint(api_response) +except ApiException as e: + print("Exception when calling DefaultApi->get_orders: %s\n" % e) +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | +| **maker_asset_proxy_id** | **str** | The maker [asset proxy id](https://0xproject.com/docs/0x.js#types-AssetProxyId) (example: \"0xf47261b0\" for ERC20, \"0x02571792\" for ERC721). | [optional] | +| **taker_asset_proxy_id** | **str** | The taker asset [asset proxy id](https://0xproject.com/docs/0x.js#types-AssetProxyId) (example: \"0xf47261b0\" for ERC20, \"0x02571792\" for ERC721). | [optional] | +| **maker_asset_address** | **str** | The contract address for the maker asset. | [optional] | +| **taker_asset_address** | **str** | The contract address for the taker asset. | [optional] | +| **exchange_address** | **str** | Same as exchangeAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) | [optional] | +| **sender_address** | **str** | Same as senderAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) | [optional] | +| **maker_asset_data** | **str** | Same as makerAssetData in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) | [optional] | +| **taker_asset_data** | **str** | Same as takerAssetData in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) | [optional] | +| **trader_asset_data** | **str** | Same as traderAssetData in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) | [optional] | +| **maker_address** | **str** | Same as makerAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) | [optional] | +| **taker_address** | **str** | Same as takerAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) | [optional] | +| **trader_address** | **str** | Same as traderAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) | [optional] | +| **fee_recipient_address** | **str** | Same as feeRecipientAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) | [optional] | +| **network_id** | **float** | The id of the Ethereum network | [optional][default to 1] | +| **page** | **float** | The number of the page to request in the collection. | [optional][default to 1] | +| **per_page** | **float** | The number of records to return per page. | [optional][default to 100] | + +### Return type + +[**RelayerApiOrdersResponseSchema**](RelayerApiOrdersResponseSchema.md) + +### Authorization + +No authorization required + +### HTTP request headers + +* **Content-Type**: Not defined +* **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **post_order** + +> post_order(network_id=network_id, signed_order_schema=signed_order_schema) + +Submit a signed order to the relayer. + +### Example + +```python +from __future__ import print_function +import time +import sra_client +from sra_client.rest import ApiException +from pprint import pprint + +# create an instance of the API class +api_instance = sra_client.DefaultApi() +network_id = 42 # float | The id of the Ethereum network (optional) (default to 1) +signed_order_schema = {"makerAddress":"0x9e56625509c2f60af937f23b7b532600390e8c8b","takerAddress":"0xa2b31dacf30a9c50ca473337c01d8a201ae33e32","feeRecipientAddress":"0xb046140686d052fff581f63f8136cce132e857da","senderAddress":"0xa2b31dacf30a9c50ca473337c01d8a201ae33e32","makerAssetAmount":"10000000000000000","takerAssetAmount":"20000000000000000","makerFee":"100000000000000","takerFee":"200000000000000","expirationTimeSeconds":"1532560590","salt":"1532559225","makerAssetData":"0xf47261b0000000000000000000000000e41d2489571d322189246dafa5ebde1f4699f498","takerAssetData":"0x02571792000000000000000000000000371b13d97f4bf77d724e78c16b7dc74099f40e840000000000000000000000000000000000000000000000000000000000000063","exchangeAddress":"0x12459c951127e0c374ff9105dda097662a027093","signature":"0x012761a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351bc33"} # SignedOrderSchema | A valid signed 0x order based on the schema. (optional) + +try: + api_instance.post_order(network_id=network_id, signed_order_schema=signed_order_schema) +except ApiException as e: + print("Exception when calling DefaultApi->post_order: %s\n" % e) +``` + +### Parameters + +| Name | Type | Description | Notes | +| ----------------------- | --------------------------------------------- | -------------------------------------------- | ------------------------ | +| **network_id** | **float** | The id of the Ethereum network | [optional][default to 1] | +| **signed_order_schema** | [**SignedOrderSchema**](SignedOrderSchema.md) | A valid signed 0x order based on the schema. | [optional] | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +* **Content-Type**: application/json +* **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/OrderSchema.md b/python-packages/sra_client/docs/OrderSchema.md new file mode 100644 index 000000000..5378c95f4 --- /dev/null +++ b/python-packages/sra_client/docs/OrderSchema.md @@ -0,0 +1,21 @@ +# OrderSchema + +## Properties + +| Name | Type | Description | Notes | +| --------------------------- | ------- | ----------- | ----- | +| **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** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/PaginatedCollectionSchema.md b/python-packages/sra_client/docs/PaginatedCollectionSchema.md new file mode 100644 index 000000000..969cbf7b5 --- /dev/null +++ b/python-packages/sra_client/docs/PaginatedCollectionSchema.md @@ -0,0 +1,11 @@ +# PaginatedCollectionSchema + +## Properties + +| Name | Type | Description | Notes | +| ------------ | --------- | ----------- | ----- | +| **total** | **float** | | +| **per_page** | **float** | | +| **page** | **float** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiAssetDataPairsResponseSchema.md b/python-packages/sra_client/docs/RelayerApiAssetDataPairsResponseSchema.md new file mode 100644 index 000000000..0e87e8dc0 --- /dev/null +++ b/python-packages/sra_client/docs/RelayerApiAssetDataPairsResponseSchema.md @@ -0,0 +1,9 @@ +# RelayerApiAssetDataPairsResponseSchema + +## Properties + +| Name | Type | Description | Notes | +| ----------- | ---------------- | ----------- | ----- | +| **records** | **list[object]** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiAssetDataTradeInfoSchema.md b/python-packages/sra_client/docs/RelayerApiAssetDataTradeInfoSchema.md new file mode 100644 index 000000000..15de4e4ad --- /dev/null +++ b/python-packages/sra_client/docs/RelayerApiAssetDataTradeInfoSchema.md @@ -0,0 +1,12 @@ +# RelayerApiAssetDataTradeInfoSchema + +## Properties + +| Name | Type | Description | Notes | +| -------------- | --------- | ----------- | ---------- | +| **asset_data** | **str** | | +| **min_amount** | **str** | | [optional] | +| **max_amount** | **str** | | [optional] | +| **precision** | **float** | | [optional] | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiErrorResponseSchema.md b/python-packages/sra_client/docs/RelayerApiErrorResponseSchema.md new file mode 100644 index 000000000..11e3b32a9 --- /dev/null +++ b/python-packages/sra_client/docs/RelayerApiErrorResponseSchema.md @@ -0,0 +1,11 @@ +# RelayerApiErrorResponseSchema + +## Properties + +| Name | Type | Description | Notes | +| --------------------- | ----------------------------------------------------------------------------------------------------------- | ----------- | ---------- | +| **code** | **int** | | +| **reason** | **str** | | +| **validation_errors** | [**list[RelayerApiErrorResponseSchemaValidationErrors]**](RelayerApiErrorResponseSchemaValidationErrors.md) | | [optional] | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiErrorResponseSchemaValidationErrors.md b/python-packages/sra_client/docs/RelayerApiErrorResponseSchemaValidationErrors.md new file mode 100644 index 000000000..2147b3822 --- /dev/null +++ b/python-packages/sra_client/docs/RelayerApiErrorResponseSchemaValidationErrors.md @@ -0,0 +1,11 @@ +# RelayerApiErrorResponseSchemaValidationErrors + +## Properties + +| Name | Type | Description | Notes | +| ---------- | ------- | ----------- | ----- | +| **field** | **str** | | +| **code** | **int** | | +| **reason** | **str** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiFeeRecipientsResponseSchema.md b/python-packages/sra_client/docs/RelayerApiFeeRecipientsResponseSchema.md new file mode 100644 index 000000000..f12582a81 --- /dev/null +++ b/python-packages/sra_client/docs/RelayerApiFeeRecipientsResponseSchema.md @@ -0,0 +1,9 @@ +# RelayerApiFeeRecipientsResponseSchema + +## Properties + +| Name | Type | Description | Notes | +| ----------- | ------------- | ----------- | ----- | +| **records** | **list[str]** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiOrderConfigPayloadSchema.md b/python-packages/sra_client/docs/RelayerApiOrderConfigPayloadSchema.md new file mode 100644 index 000000000..ee0800066 --- /dev/null +++ b/python-packages/sra_client/docs/RelayerApiOrderConfigPayloadSchema.md @@ -0,0 +1,16 @@ +# RelayerApiOrderConfigPayloadSchema + +## Properties + +| Name | Type | Description | Notes | +| --------------------------- | ------- | ----------- | ----- | +| **maker_address** | **str** | | +| **taker_address** | **str** | | +| **maker_asset_amount** | **str** | | +| **taker_asset_amount** | **str** | | +| **maker_asset_data** | **str** | | +| **taker_asset_data** | **str** | | +| **exchange_address** | **str** | | +| **expiration_time_seconds** | **str** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiOrderConfigResponseSchema.md b/python-packages/sra_client/docs/RelayerApiOrderConfigResponseSchema.md new file mode 100644 index 000000000..2ebafdf47 --- /dev/null +++ b/python-packages/sra_client/docs/RelayerApiOrderConfigResponseSchema.md @@ -0,0 +1,12 @@ +# RelayerApiOrderConfigResponseSchema + +## Properties + +| Name | Type | Description | Notes | +| ------------------------- | ------- | ----------- | ----- | +| **maker_fee** | **str** | | +| **taker_fee** | **str** | | +| **fee_recipient_address** | **str** | | +| **sender_address** | **str** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiOrderSchema.md b/python-packages/sra_client/docs/RelayerApiOrderSchema.md new file mode 100644 index 000000000..bbdffe2f4 --- /dev/null +++ b/python-packages/sra_client/docs/RelayerApiOrderSchema.md @@ -0,0 +1,10 @@ +# RelayerApiOrderSchema + +## Properties + +| Name | Type | Description | Notes | +| ------------- | --------------------------------- | ----------- | ----- | +| **order** | [**OrderSchema**](OrderSchema.md) | | +| **meta_data** | [**object**](.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiOrderbookResponseSchema.md b/python-packages/sra_client/docs/RelayerApiOrderbookResponseSchema.md new file mode 100644 index 000000000..6fb7c88ff --- /dev/null +++ b/python-packages/sra_client/docs/RelayerApiOrderbookResponseSchema.md @@ -0,0 +1,10 @@ +# RelayerApiOrderbookResponseSchema + +## Properties + +| Name | Type | Description | Notes | +| -------- | ----------------------------------------------------------------------- | ----------- | ----- | +| **bids** | [**RelayerApiOrdersResponseSchema**](RelayerApiOrdersResponseSchema.md) | | +| **asks** | [**RelayerApiOrdersResponseSchema**](RelayerApiOrdersResponseSchema.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiOrdersChannelSubscribePayloadSchema.md b/python-packages/sra_client/docs/RelayerApiOrdersChannelSubscribePayloadSchema.md new file mode 100644 index 000000000..97c2cbc21 --- /dev/null +++ b/python-packages/sra_client/docs/RelayerApiOrdersChannelSubscribePayloadSchema.md @@ -0,0 +1,16 @@ +# RelayerApiOrdersChannelSubscribePayloadSchema + +## Properties + +| Name | Type | Description | Notes | +| ------------------------ | --------- | ----------- | ---------- | +| **maker_asset_proxy_id** | **str** | | [optional] | +| **taker_asset_proxy_id** | **str** | | [optional] | +| **network_id** | **float** | | [optional] | +| **maker_asset_address** | **str** | | [optional] | +| **taker_asset_address** | **str** | | [optional] | +| **maker_asset_data** | **str** | | [optional] | +| **taker_asset_data** | **str** | | [optional] | +| **trader_asset_data** | **str** | | [optional] | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiOrdersChannelSubscribeSchema.md b/python-packages/sra_client/docs/RelayerApiOrdersChannelSubscribeSchema.md new file mode 100644 index 000000000..5e1c96c24 --- /dev/null +++ b/python-packages/sra_client/docs/RelayerApiOrdersChannelSubscribeSchema.md @@ -0,0 +1,12 @@ +# RelayerApiOrdersChannelSubscribeSchema + +## Properties + +| Name | Type | Description | Notes | +| -------------- | ----------------------------------------------------------------------------------------------------- | ----------- | ---------- | +| **type** | **str** | | +| **channel** | **str** | | +| **request_id** | **str** | | +| **payload** | [**RelayerApiOrdersChannelSubscribePayloadSchema**](RelayerApiOrdersChannelSubscribePayloadSchema.md) | | [optional] | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiOrdersChannelUpdateSchema.md b/python-packages/sra_client/docs/RelayerApiOrdersChannelUpdateSchema.md new file mode 100644 index 000000000..8d763367a --- /dev/null +++ b/python-packages/sra_client/docs/RelayerApiOrdersChannelUpdateSchema.md @@ -0,0 +1,12 @@ +# RelayerApiOrdersChannelUpdateSchema + +## Properties + +| Name | Type | Description | Notes | +| -------------- | ----------------------------------------------------------- | ----------- | ---------- | +| **type** | **str** | | +| **channel** | **str** | | +| **request_id** | **str** | | +| **payload** | [**list[RelayerApiOrderSchema]**](RelayerApiOrderSchema.md) | | [optional] | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/RelayerApiOrdersResponseSchema.md b/python-packages/sra_client/docs/RelayerApiOrdersResponseSchema.md new file mode 100644 index 000000000..8989d346b --- /dev/null +++ b/python-packages/sra_client/docs/RelayerApiOrdersResponseSchema.md @@ -0,0 +1,9 @@ +# RelayerApiOrdersResponseSchema + +## Properties + +| Name | Type | Description | Notes | +| ----------- | ----------------------------------------------------------- | ----------- | ----- | +| **records** | [**list[RelayerApiOrderSchema]**](RelayerApiOrderSchema.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/docs/SignedOrderSchema.md b/python-packages/sra_client/docs/SignedOrderSchema.md new file mode 100644 index 000000000..4c753e6cc --- /dev/null +++ b/python-packages/sra_client/docs/SignedOrderSchema.md @@ -0,0 +1,9 @@ +# SignedOrderSchema + +## Properties + +| Name | Type | Description | Notes | +| ------------- | ------- | ----------- | ----- | +| **signature** | **str** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/python-packages/sra_client/generate.sh b/python-packages/sra_client/generate.sh new file mode 100755 index 000000000..91967dee3 --- /dev/null +++ b/python-packages/sra_client/generate.sh @@ -0,0 +1,26 @@ +# This file provided not so much to be run but rather more for posterity, as a +# record of how this generated code was produced. + +GENERATOR_JAR=http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/3.3.4/openapi-generator-cli-3.3.4.jar +GENERATOR_JAR_BASENAME=$(basename $GENERATOR_JAR) + +if [ -f $GENERATOR_JAR_BASENAME ]; then + if [ "$(openssl dgst -sha256 $GENERATOR_JAR_BASENAME)" \ + != "SHA256($GENERATOR_JAR_BASENAME)= 24cb04939110cffcdd7062d2f50c6f61159dc3e0ca3b8aecbae6ade53ad3dc8c" \ + ]; then + rm $GENERATOR_JAR_BASENAME + fi +fi + +if [ ! -f $GENERATOR_JAR_BASENAME ]; then + wget $GENERATOR_JAR +fi + +PYTHON_POST_PROCESS_FILE="black --line-length 79" \ + java -jar openapi-generator-cli-3.3.4.jar \ + generate \ + --input-spec http://unpkg.com/@0x/sra-spec@1.0.11/lib/api.json \ + --output . \ + --generator-name python \ + --config openapi-generator-cli-config.json \ + --enable-post-process-file diff --git a/python-packages/sra_client/openapi-generator-cli-config.json b/python-packages/sra_client/openapi-generator-cli-config.json new file mode 100644 index 000000000..cc619e465 --- /dev/null +++ b/python-packages/sra_client/openapi-generator-cli-config.json @@ -0,0 +1,4 @@ +{ + "packageName": "sra_client", + "projectName": "0x-sra-client" +} diff --git a/python-packages/sra_client/requirements.txt b/python-packages/sra_client/requirements.txt new file mode 100644 index 000000000..bafdc0753 --- /dev/null +++ b/python-packages/sra_client/requirements.txt @@ -0,0 +1,5 @@ +certifi >= 14.05.14 +six >= 1.10 +python_dateutil >= 2.5.3 +setuptools >= 21.0.0 +urllib3 >= 1.15.1 diff --git a/python-packages/sra_client/setup.py b/python-packages/sra_client/setup.py new file mode 100755 index 000000000..b47f71ae7 --- /dev/null +++ b/python-packages/sra_client/setup.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# coding: utf-8 + + +import subprocess +import distutils.command.build_py + +from setuptools import setup, find_packages # noqa: H301 + +NAME = "0x-sra-client" +VERSION = "1.0.0" +# To install the library, run the following +# +# python setup.py install +# +# prerequisite: setuptools +# http://pypi.python.org/pypi/setuptools + +with open("README.md", "r") as file_handle: + README_MD = file_handle.read() + +REQUIRES = ["urllib3 >= 1.15", "six >= 1.10", "certifi", "python-dateutil"] + +class TestPublishCommand(distutils.command.build_py.build_py): + """Custom command to publish to test.pypi.org.""" + + description = ( + "Publish dist/* to test.pypi.org. Run sdist & bdist_wheel first." + ) + + def run(self): + """Run twine to upload to test.pypi.org.""" + subprocess.check_call( # nosec + ( + "twine upload --repository-url https://test.pypi.org/legacy/" + + " --verbose dist/*" + ).split() + ) + + +class PublishCommand(distutils.command.build_py.build_py): + """Custom command to publish to pypi.org.""" + + description = "Publish dist/* to pypi.org. Run sdist & bdist_wheel first." + + def run(self): + """Run twine to upload to pypi.org.""" + subprocess.check_call("twine upload dist/*".split()) # nosec + + +setup( + name=NAME, + version=VERSION, + description="Standard Relayer REST API", + author_email="", + 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(), + include_package_data=True, + long_description=README_MD, + long_description_content_type="text/markdown", + cmdclass={ + "test_publish": TestPublishCommand, + "publish": PublishCommand, + }, +) diff --git a/python-packages/sra_client/sra_client/__init__.py b/python-packages/sra_client/sra_client/__init__.py new file mode 100644 index 000000000..fc02976a5 --- /dev/null +++ b/python-packages/sra_client/sra_client/__init__.py @@ -0,0 +1,59 @@ +# coding: utf-8 + +# flake8: noqa + + +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 ( + 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 diff --git a/python-packages/sra_client/sra_client/api/__init__.py b/python-packages/sra_client/sra_client/api/__init__.py new file mode 100644 index 000000000..b7b206bb1 --- /dev/null +++ b/python-packages/sra_client/sra_client/api/__init__.py @@ -0,0 +1,6 @@ +from __future__ import absolute_import + +# flake8: noqa + +# import apis into api package +from sra_client.api.default_api import DefaultApi diff --git a/python-packages/sra_client/sra_client/api/default_api.py b/python-packages/sra_client/sra_client/api/default_api.py new file mode 100644 index 000000000..2d65db609 --- /dev/null +++ b/python-packages/sra_client/sra_client/api/default_api.py @@ -0,0 +1,976 @@ +# coding: utf-8 + + +from __future__ import absolute_import + +import re # noqa: F401 + +# python 2 and python 3 compatibility library +import six + +from sra_client.api_client import ApiClient + + +class DefaultApi(object): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client + + def get_asset_pairs(self, **kwargs): # noqa: E501 + """get_asset_pairs # noqa: E501 + + Retrieves a list of available asset pairs and the information required to trade them (in any order). Setting only `assetDataA` or `assetDataB` returns pairs filtered by that asset only. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.get_asset_pairs(async_req=True) + >>> result = thread.get() + + :param async_req bool + :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. + :return: RelayerApiAssetDataPairsResponseSchema + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + if kwargs.get("async_req"): + return self.get_asset_pairs_with_http_info(**kwargs) # noqa: E501 + else: + (data) = self.get_asset_pairs_with_http_info( + **kwargs + ) # noqa: E501 + return data + + def get_asset_pairs_with_http_info(self, **kwargs): # noqa: E501 + """get_asset_pairs # noqa: E501 + + Retrieves a list of available asset pairs and the information required to trade them (in any order). Setting only `assetDataA` or `assetDataB` returns pairs filtered by that asset only. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.get_asset_pairs_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool + :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. + :return: RelayerApiAssetDataPairsResponseSchema + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = [ + "asset_data_a", + "asset_data_b", + "network_id", + "page", + "per_page", + ] # noqa: E501 + all_params.append("async_req") + all_params.append("_return_http_data_only") + all_params.append("_preload_content") + all_params.append("_request_timeout") + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method get_asset_pairs" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + if "asset_data_a" in local_var_params: + query_params.append( + ("assetDataA", local_var_params["asset_data_a"]) + ) # noqa: E501 + if "asset_data_b" in local_var_params: + query_params.append( + ("assetDataB", local_var_params["asset_data_b"]) + ) # noqa: E501 + if "network_id" in local_var_params: + query_params.append( + ("networkId", local_var_params["network_id"]) + ) # noqa: E501 + if "page" in local_var_params: + query_params.append( + ("page", local_var_params["page"]) + ) # noqa: E501 + if "per_page" in local_var_params: + query_params.append( + ("perPage", local_var_params["per_page"]) + ) # noqa: E501 + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/v2/asset_pairs", + "GET", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="RelayerApiAssetDataPairsResponseSchema", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def get_fee_recipients(self, **kwargs): # noqa: E501 + """get_fee_recipients # noqa: E501 + + Retrieves a collection of all fee recipient addresses for a relayer. This endpoint should be [paginated](#section/Pagination). # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.get_fee_recipients(async_req=True) + >>> result = thread.get() + + :param async_req bool + :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. + :return: RelayerApiFeeRecipientsResponseSchema + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + if kwargs.get("async_req"): + return self.get_fee_recipients_with_http_info( + **kwargs + ) # noqa: E501 + else: + (data) = self.get_fee_recipients_with_http_info( + **kwargs + ) # noqa: E501 + return data + + def get_fee_recipients_with_http_info(self, **kwargs): # noqa: E501 + """get_fee_recipients # noqa: E501 + + Retrieves a collection of all fee recipient addresses for a relayer. This endpoint should be [paginated](#section/Pagination). # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.get_fee_recipients_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool + :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. + :return: RelayerApiFeeRecipientsResponseSchema + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["network_id", "page", "per_page"] # noqa: E501 + all_params.append("async_req") + all_params.append("_return_http_data_only") + all_params.append("_preload_content") + all_params.append("_request_timeout") + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method get_fee_recipients" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + if "network_id" in local_var_params: + query_params.append( + ("networkId", local_var_params["network_id"]) + ) # noqa: E501 + if "page" in local_var_params: + query_params.append( + ("page", local_var_params["page"]) + ) # noqa: E501 + if "per_page" in local_var_params: + query_params.append( + ("perPage", local_var_params["per_page"]) + ) # noqa: E501 + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/v2/fee_recipients", + "GET", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="RelayerApiFeeRecipientsResponseSchema", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def get_order(self, order_hash, **kwargs): # noqa: E501 + """get_order # noqa: E501 + + Retrieves the 0x order with meta info that is associated with the hash. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.get_order(order_hash, async_req=True) + >>> result = thread.get() + + :param async_req bool + :param str order_hash: The hash of the desired 0x order. (required) + :param float network_id: The id of the Ethereum network + :return: RelayerApiOrderSchema + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + if kwargs.get("async_req"): + return self.get_order_with_http_info( + order_hash, **kwargs + ) # noqa: E501 + else: + (data) = self.get_order_with_http_info( + order_hash, **kwargs + ) # noqa: E501 + return data + + def get_order_with_http_info(self, order_hash, **kwargs): # noqa: E501 + """get_order # noqa: E501 + + Retrieves the 0x order with meta info that is associated with the hash. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.get_order_with_http_info(order_hash, async_req=True) + >>> result = thread.get() + + :param async_req bool + :param str order_hash: The hash of the desired 0x order. (required) + :param float network_id: The id of the Ethereum network + :return: RelayerApiOrderSchema + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["order_hash", "network_id"] # noqa: E501 + all_params.append("async_req") + all_params.append("_return_http_data_only") + all_params.append("_preload_content") + all_params.append("_request_timeout") + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method get_order" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + # verify the required parameter 'order_hash' is set + if ( + "order_hash" not in local_var_params + or local_var_params["order_hash"] is None + ): + raise ValueError( + "Missing the required parameter `order_hash` when calling `get_order`" + ) # noqa: E501 + + collection_formats = {} + + path_params = {} + if "order_hash" in local_var_params: + path_params["orderHash"] = local_var_params[ + "order_hash" + ] # noqa: E501 + + query_params = [] + if "network_id" in local_var_params: + query_params.append( + ("networkId", local_var_params["network_id"]) + ) # noqa: E501 + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/v2/order/{orderHash}", + "GET", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="RelayerApiOrderSchema", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def get_order_config(self, **kwargs): # noqa: E501 + """get_order_config # noqa: E501 + + Relayers have full discretion over the orders that they are willing to host on their orderbooks (e.g what fees they charge, etc...). In order for traders to discover their requirements programmatically, they can send an incomplete order to this endpoint and receive the missing fields, specifc to that order. This gives relayers a large amount of flexibility to tailor fees to unique traders, trading pairs and volume amounts. Submit a partial order and receive information required to complete the order: `senderAddress`, `feeRecipientAddress`, `makerFee`, `takerFee`. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.get_order_config(async_req=True) + >>> result = thread.get() + + :param async_req bool + :param float network_id: The id of the Ethereum network + :param RelayerApiOrderConfigPayloadSchema relayer_api_order_config_payload_schema: The fields of a 0x order the relayer may want to decide what configuration to send back. + :return: RelayerApiOrderConfigResponseSchema + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + if kwargs.get("async_req"): + return self.get_order_config_with_http_info(**kwargs) # noqa: E501 + else: + (data) = self.get_order_config_with_http_info( + **kwargs + ) # noqa: E501 + return data + + def get_order_config_with_http_info(self, **kwargs): # noqa: E501 + """get_order_config # noqa: E501 + + Relayers have full discretion over the orders that they are willing to host on their orderbooks (e.g what fees they charge, etc...). In order for traders to discover their requirements programmatically, they can send an incomplete order to this endpoint and receive the missing fields, specifc to that order. This gives relayers a large amount of flexibility to tailor fees to unique traders, trading pairs and volume amounts. Submit a partial order and receive information required to complete the order: `senderAddress`, `feeRecipientAddress`, `makerFee`, `takerFee`. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.get_order_config_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool + :param float network_id: The id of the Ethereum network + :param RelayerApiOrderConfigPayloadSchema relayer_api_order_config_payload_schema: The fields of a 0x order the relayer may want to decide what configuration to send back. + :return: RelayerApiOrderConfigResponseSchema + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = [ + "network_id", + "relayer_api_order_config_payload_schema", + ] # noqa: E501 + all_params.append("async_req") + all_params.append("_return_http_data_only") + all_params.append("_preload_content") + all_params.append("_request_timeout") + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method get_order_config" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + if "network_id" in local_var_params: + query_params.append( + ("networkId", local_var_params["network_id"]) + ) # noqa: E501 + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "relayer_api_order_config_payload_schema" in local_var_params: + body_params = local_var_params[ + "relayer_api_order_config_payload_schema" + ] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params[ + "Content-Type" + ] = self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/v2/order_config", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="RelayerApiOrderConfigResponseSchema", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def get_orderbook( + self, base_asset_data, quote_asset_data, **kwargs + ): # noqa: E501 + """get_orderbook # noqa: E501 + + Retrieves the orderbook for a given asset pair. This endpoint should be [paginated](#section/Pagination). Bids will be sorted in descending order by price, and asks will be sorted in ascending order by price. Within the price sorted orders, the orders are further sorted by _taker fee price_ which is defined as the **takerFee** divided by **takerTokenAmount**. After _taker fee price_, orders are to be sorted by expiration in ascending order. The way pagination works for this endpoint is that the **page** and **perPage** query params apply to both `bids` and `asks` collections, and if `page` * `perPage` > `total` for a certain collection, the `records` for that collection should just be empty. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.get_orderbook(base_asset_data, quote_asset_data, async_req=True) + >>> result = thread.get() + + :param async_req bool + :param str base_asset_data: assetData (makerAssetData or takerAssetData) designated as the base currency in the [currency pair calculation](https://en.wikipedia.org/wiki/Currency_pair) of price. (required) + :param str quote_asset_data: assetData (makerAssetData or takerAssetData) designated as the quote currency in the currency pair calculation of price (required). (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. + :return: RelayerApiOrderbookResponseSchema + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + if kwargs.get("async_req"): + return self.get_orderbook_with_http_info( + base_asset_data, quote_asset_data, **kwargs + ) # noqa: E501 + else: + (data) = self.get_orderbook_with_http_info( + base_asset_data, quote_asset_data, **kwargs + ) # noqa: E501 + return data + + def get_orderbook_with_http_info( + self, base_asset_data, quote_asset_data, **kwargs + ): # noqa: E501 + """get_orderbook # noqa: E501 + + Retrieves the orderbook for a given asset pair. This endpoint should be [paginated](#section/Pagination). Bids will be sorted in descending order by price, and asks will be sorted in ascending order by price. Within the price sorted orders, the orders are further sorted by _taker fee price_ which is defined as the **takerFee** divided by **takerTokenAmount**. After _taker fee price_, orders are to be sorted by expiration in ascending order. The way pagination works for this endpoint is that the **page** and **perPage** query params apply to both `bids` and `asks` collections, and if `page` * `perPage` > `total` for a certain collection, the `records` for that collection should just be empty. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.get_orderbook_with_http_info(base_asset_data, quote_asset_data, async_req=True) + >>> result = thread.get() + + :param async_req bool + :param str base_asset_data: assetData (makerAssetData or takerAssetData) designated as the base currency in the [currency pair calculation](https://en.wikipedia.org/wiki/Currency_pair) of price. (required) + :param str quote_asset_data: assetData (makerAssetData or takerAssetData) designated as the quote currency in the currency pair calculation of price (required). (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. + :return: RelayerApiOrderbookResponseSchema + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = [ + "base_asset_data", + "quote_asset_data", + "network_id", + "page", + "per_page", + ] # noqa: E501 + all_params.append("async_req") + all_params.append("_return_http_data_only") + all_params.append("_preload_content") + all_params.append("_request_timeout") + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method get_orderbook" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + # verify the required parameter 'base_asset_data' is set + if ( + "base_asset_data" not in local_var_params + or local_var_params["base_asset_data"] is None + ): + raise ValueError( + "Missing the required parameter `base_asset_data` when calling `get_orderbook`" + ) # noqa: E501 + # verify the required parameter 'quote_asset_data' is set + if ( + "quote_asset_data" not in local_var_params + or local_var_params["quote_asset_data"] is None + ): + raise ValueError( + "Missing the required parameter `quote_asset_data` when calling `get_orderbook`" + ) # noqa: E501 + + collection_formats = {} + + path_params = {} + + query_params = [] + if "base_asset_data" in local_var_params: + query_params.append( + ("baseAssetData", local_var_params["base_asset_data"]) + ) # noqa: E501 + if "quote_asset_data" in local_var_params: + query_params.append( + ("quoteAssetData", local_var_params["quote_asset_data"]) + ) # noqa: E501 + if "network_id" in local_var_params: + query_params.append( + ("networkId", local_var_params["network_id"]) + ) # noqa: E501 + if "page" in local_var_params: + query_params.append( + ("page", local_var_params["page"]) + ) # noqa: E501 + if "per_page" in local_var_params: + query_params.append( + ("perPage", local_var_params["per_page"]) + ) # noqa: E501 + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/v2/orderbook", + "GET", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="RelayerApiOrderbookResponseSchema", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def get_orders(self, **kwargs): # noqa: E501 + """get_orders # noqa: E501 + + Retrieves a list of orders given query parameters. This endpoint should be [paginated](#section/Pagination). For querying an entire orderbook snapshot, the [orderbook endpoint](#operation/getOrderbook) is recommended. If both makerAssetData and takerAssetData are specified, returned orders will be sorted by price determined by (takerTokenAmount/makerTokenAmount) in ascending order. By default, orders returned by this endpoint are unsorted. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.get_orders(async_req=True) + >>> result = thread.get() + + :param async_req bool + :param str maker_asset_proxy_id: The maker [asset proxy id](https://0xproject.com/docs/0x.js#types-AssetProxyId) (example: \"0xf47261b0\" for ERC20, \"0x02571792\" for ERC721). + :param str taker_asset_proxy_id: The taker asset [asset proxy id](https://0xproject.com/docs/0x.js#types-AssetProxyId) (example: \"0xf47261b0\" for ERC20, \"0x02571792\" for ERC721). + :param str maker_asset_address: The contract address for the maker asset. + :param str taker_asset_address: The contract address for the taker asset. + :param str exchange_address: Same as exchangeAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) + :param str sender_address: Same as senderAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) + :param str maker_asset_data: Same as makerAssetData in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) + :param str taker_asset_data: Same as takerAssetData in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) + :param str trader_asset_data: Same as traderAssetData in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) + :param str maker_address: Same as makerAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) + :param str taker_address: Same as takerAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) + :param str trader_address: Same as traderAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) + :param str fee_recipient_address: Same as feeRecipientAddress in the [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. + :return: RelayerApiOrdersResponseSchema + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + if kwargs.get("async_req"): + return self.get_orders_with_http_info(**kwargs) # noqa: E501 + else: + (data) = self.get_orders_with_http_info(**kwargs) # noqa: E501 + return data + + def get_orders_with_http_info(self, **kwargs): # noqa: E501 + """get_orders # noqa: E501 + + Retrieves a list of orders given query parameters. This endpoint should be [paginated](#section/Pagination). For querying an entire orderbook snapshot, the [orderbook endpoint](#operation/getOrderbook) is recommended. If both makerAssetData and takerAssetData are specified, returned orders will be sorted by price determined by (takerTokenAmount/makerTokenAmount) in ascending order. By default, orders returned by this endpoint are unsorted. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.get_orders_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool + :param str maker_asset_proxy_id: The maker [asset proxy id](https://0xproject.com/docs/0x.js#types-AssetProxyId) (example: \"0xf47261b0\" for ERC20, \"0x02571792\" for ERC721). + :param str taker_asset_proxy_id: The taker asset [asset proxy id](https://0xproject.com/docs/0x.js#types-AssetProxyId) (example: \"0xf47261b0\" for ERC20, \"0x02571792\" for ERC721). + :param str maker_asset_address: The contract address for the maker asset. + :param str taker_asset_address: The contract address for the taker asset. + :param str exchange_address: Same as exchangeAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) + :param str sender_address: Same as senderAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) + :param str maker_asset_data: Same as makerAssetData in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) + :param str taker_asset_data: Same as takerAssetData in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) + :param str trader_asset_data: Same as traderAssetData in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) + :param str maker_address: Same as makerAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) + :param str taker_address: Same as takerAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) + :param str trader_address: Same as traderAddress in the [0x Protocol v2 Specification](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#order-message-format) + :param str fee_recipient_address: Same as feeRecipientAddress in the [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. + :return: RelayerApiOrdersResponseSchema + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = [ + "maker_asset_proxy_id", + "taker_asset_proxy_id", + "maker_asset_address", + "taker_asset_address", + "exchange_address", + "sender_address", + "maker_asset_data", + "taker_asset_data", + "trader_asset_data", + "maker_address", + "taker_address", + "trader_address", + "fee_recipient_address", + "network_id", + "page", + "per_page", + ] # noqa: E501 + all_params.append("async_req") + all_params.append("_return_http_data_only") + all_params.append("_preload_content") + all_params.append("_request_timeout") + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method get_orders" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + if "maker_asset_proxy_id" in local_var_params: + query_params.append( + ("makerAssetProxyId", local_var_params["maker_asset_proxy_id"]) + ) # noqa: E501 + if "taker_asset_proxy_id" in local_var_params: + query_params.append( + ("takerAssetProxyId", local_var_params["taker_asset_proxy_id"]) + ) # noqa: E501 + if "maker_asset_address" in local_var_params: + query_params.append( + ("makerAssetAddress", local_var_params["maker_asset_address"]) + ) # noqa: E501 + if "taker_asset_address" in local_var_params: + query_params.append( + ("takerAssetAddress", local_var_params["taker_asset_address"]) + ) # noqa: E501 + if "exchange_address" in local_var_params: + query_params.append( + ("exchangeAddress", local_var_params["exchange_address"]) + ) # noqa: E501 + if "sender_address" in local_var_params: + query_params.append( + ("senderAddress", local_var_params["sender_address"]) + ) # noqa: E501 + if "maker_asset_data" in local_var_params: + query_params.append( + ("makerAssetData", local_var_params["maker_asset_data"]) + ) # noqa: E501 + if "taker_asset_data" in local_var_params: + query_params.append( + ("takerAssetData", local_var_params["taker_asset_data"]) + ) # noqa: E501 + if "trader_asset_data" in local_var_params: + query_params.append( + ("traderAssetData", local_var_params["trader_asset_data"]) + ) # noqa: E501 + if "maker_address" in local_var_params: + query_params.append( + ("makerAddress", local_var_params["maker_address"]) + ) # noqa: E501 + if "taker_address" in local_var_params: + query_params.append( + ("takerAddress", local_var_params["taker_address"]) + ) # noqa: E501 + if "trader_address" in local_var_params: + query_params.append( + ("traderAddress", local_var_params["trader_address"]) + ) # noqa: E501 + if "fee_recipient_address" in local_var_params: + query_params.append( + ( + "feeRecipientAddress", + local_var_params["fee_recipient_address"], + ) + ) # noqa: E501 + if "network_id" in local_var_params: + query_params.append( + ("networkId", local_var_params["network_id"]) + ) # noqa: E501 + if "page" in local_var_params: + query_params.append( + ("page", local_var_params["page"]) + ) # noqa: E501 + if "per_page" in local_var_params: + query_params.append( + ("perPage", local_var_params["per_page"]) + ) # noqa: E501 + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/v2/orders", + "GET", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="RelayerApiOrdersResponseSchema", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def post_order(self, **kwargs): # noqa: E501 + """post_order # noqa: E501 + + Submit a signed order to the relayer. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.post_order(async_req=True) + >>> result = thread.get() + + :param async_req bool + :param float network_id: The id of the Ethereum network + :param SignedOrderSchema signed_order_schema: A valid signed 0x order based on the schema. + :return: None + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + if kwargs.get("async_req"): + return self.post_order_with_http_info(**kwargs) # noqa: E501 + else: + (data) = self.post_order_with_http_info(**kwargs) # noqa: E501 + return data + + def post_order_with_http_info(self, **kwargs): # noqa: E501 + """post_order # noqa: E501 + + Submit a signed order to the relayer. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.post_order_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool + :param float network_id: The id of the Ethereum network + :param SignedOrderSchema signed_order_schema: A valid signed 0x order based on the schema. + :return: None + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["network_id", "signed_order_schema"] # noqa: E501 + all_params.append("async_req") + all_params.append("_return_http_data_only") + all_params.append("_preload_content") + all_params.append("_request_timeout") + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method post_order" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + if "network_id" in local_var_params: + query_params.append( + ("networkId", local_var_params["network_id"]) + ) # noqa: E501 + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "signed_order_schema" in local_var_params: + body_params = local_var_params["signed_order_schema"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params[ + "Content-Type" + ] = self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/v2/order", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) diff --git a/python-packages/sra_client/sra_client/api_client.py b/python-packages/sra_client/sra_client/api_client.py new file mode 100644 index 000000000..6139fdb42 --- /dev/null +++ b/python-packages/sra_client/sra_client/api_client.py @@ -0,0 +1,730 @@ +# coding: utf-8 + +from __future__ import absolute_import + +import datetime +import json +import mimetypes +from multiprocessing.pool import ThreadPool +import os +import re +import tempfile + +# python 2 and python 3 compatibility library +import six +from six.moves.urllib.parse import quote + +from sra_client.configuration import Configuration +import sra_client.models +from sra_client import rest + + +class ApiClient(object): + """Generic API client for OpenAPI client library builds. + + OpenAPI generic API client. This client handles the client- + server communication, and is invariant across implementations. Specifics of + the methods and models for each application are generated from the OpenAPI + templates. + + NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + Do not edit the class manually. + + :param configuration: .Configuration object for this client + :param header_name: a header to pass when making calls to the API. + :param header_value: a header value to pass when making calls to + the API. + :param cookie: a cookie to include in the header when making calls + to the API + :param pool_threads: The number of threads to use for async requests + to the API. More threads means more concurrent API requests. + """ + + PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types + NATIVE_TYPES_MAPPING = { + "int": int, + "long": int if six.PY3 else long, # noqa: F821 + "float": float, + "str": str, + "bool": bool, + "date": datetime.date, + "datetime": datetime.datetime, + "object": object, + } + _pool = None + + def __init__( + self, + configuration=None, + header_name=None, + header_value=None, + cookie=None, + pool_threads=None, + ): + if configuration is None: + configuration = Configuration() + self.configuration = configuration + self.pool_threads = pool_threads + + self.rest_client = rest.RESTClientObject(configuration) + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value + self.cookie = cookie + # Set default User-Agent. + self.user_agent = "OpenAPI-Generator/1.0.0/python" + + def __del__(self): + if self._pool: + self._pool.close() + self._pool.join() + self._pool = None + + @property + def pool(self): + """Create thread pool on first request + avoids instantiating unused threadpool for blocking clients. + """ + if self._pool is None: + self._pool = ThreadPool(self.pool_threads) + return self._pool + + @property + def user_agent(self): + """User agent for this API client""" + return self.default_headers["User-Agent"] + + @user_agent.setter + def user_agent(self, value): + self.default_headers["User-Agent"] = value + + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value + + def __call_api( + self, + resource_path, + method, + path_params=None, + query_params=None, + header_params=None, + body=None, + post_params=None, + files=None, + response_type=None, + auth_settings=None, + _return_http_data_only=None, + collection_formats=None, + _preload_content=True, + _request_timeout=None, + ): + + config = self.configuration + + # header parameters + header_params = header_params or {} + header_params.update(self.default_headers) + if self.cookie: + header_params["Cookie"] = self.cookie + if header_params: + header_params = self.sanitize_for_serialization(header_params) + header_params = dict( + self.parameters_to_tuples(header_params, collection_formats) + ) + + # path parameters + if path_params: + path_params = self.sanitize_for_serialization(path_params) + path_params = self.parameters_to_tuples( + path_params, collection_formats + ) + for k, v in path_params: + # specified safe chars, encode everything + resource_path = resource_path.replace( + "{%s}" % k, + quote(str(v), safe=config.safe_chars_for_path_param), + ) + + # query parameters + if query_params: + query_params = self.sanitize_for_serialization(query_params) + query_params = self.parameters_to_tuples( + query_params, collection_formats + ) + + # post parameters + if post_params or files: + post_params = self.prepare_post_parameters(post_params, files) + post_params = self.sanitize_for_serialization(post_params) + post_params = self.parameters_to_tuples( + post_params, collection_formats + ) + + # auth setting + self.update_params_for_auth(header_params, query_params, auth_settings) + + # body + if body: + body = self.sanitize_for_serialization(body) + + # request url + url = self.configuration.host + resource_path + + # perform request and return response + response_data = self.request( + method, + url, + query_params=query_params, + headers=header_params, + post_params=post_params, + body=body, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + ) + + self.last_response = response_data + + return_data = response_data + if _preload_content: + # deserialize response data + if response_type: + return_data = self.deserialize(response_data, response_type) + else: + return_data = None + + if _return_http_data_only: + return return_data + else: + return ( + return_data, + response_data.status, + response_data.getheaders(), + ) + + def sanitize_for_serialization(self, obj): + """Builds a JSON POST object. + + If obj is None, return None. + If obj is str, int, long, float, bool, return directly. + If obj is datetime.datetime, datetime.date + convert to string in iso8601 format. + If obj is list, sanitize each element in the list. + If obj is dict, return the dict. + If obj is OpenAPI model, return the properties dict. + + :param obj: The data to serialize. + :return: The serialized form of data. + """ + if obj is None: + return None + elif isinstance(obj, self.PRIMITIVE_TYPES): + return obj + elif isinstance(obj, list): + return [ + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ] + elif isinstance(obj, tuple): + return tuple( + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ) + elif isinstance(obj, (datetime.datetime, datetime.date)): + return obj.isoformat() + + if isinstance(obj, dict): + obj_dict = obj + else: + # Convert model obj to dict except + # attributes `openapi_types`, `attribute_map` + # and attributes which value is not None. + # Convert attribute name to json key in + # model definition for request. + obj_dict = { + obj.attribute_map[attr]: getattr(obj, attr) + for attr, _ in six.iteritems(obj.openapi_types) + if getattr(obj, attr) is not None + } + + return { + key: self.sanitize_for_serialization(val) + for key, val in six.iteritems(obj_dict) + } + + def deserialize(self, response, response_type): + """Deserializes response into an object. + + :param response: RESTResponse object to be deserialized. + :param response_type: class literal for + deserialized object, or string of class name. + + :return: deserialized object. + """ + # handle file downloading + # save response body into a tmp file and return the instance + if response_type == "file": + return self.__deserialize_file(response) + + # fetch data from response object + try: + data = json.loads(response.data) + except ValueError: + data = response.data + + return self.__deserialize(data, response_type) + + def __deserialize(self, data, klass): + """Deserializes dict, list, str into an object. + + :param data: dict, list or str. + :param klass: class literal, or string of class name. + + :return: object. + """ + if data is None: + return None + + if type(klass) == str: + if klass.startswith("list["): + sub_kls = re.match(r"list\[(.*)\]", klass).group(1) + return [ + self.__deserialize(sub_data, sub_kls) for sub_data in data + ] + + if klass.startswith("dict("): + sub_kls = re.match(r"dict\(([^,]*), (.*)\)", klass).group(2) + return { + k: self.__deserialize(v, sub_kls) + for k, v in six.iteritems(data) + } + + # convert str to class + if klass in self.NATIVE_TYPES_MAPPING: + klass = self.NATIVE_TYPES_MAPPING[klass] + else: + klass = getattr(sra_client.models, klass) + + if klass in self.PRIMITIVE_TYPES: + return self.__deserialize_primitive(data, klass) + elif klass == object: + return self.__deserialize_object(data) + elif klass == datetime.date: + return self.__deserialize_date(data) + elif klass == datetime.datetime: + return self.__deserialize_datatime(data) + else: + return self.__deserialize_model(data, klass) + + def call_api( + self, + resource_path, + method, + path_params=None, + query_params=None, + header_params=None, + body=None, + post_params=None, + files=None, + response_type=None, + auth_settings=None, + async_req=None, + _return_http_data_only=None, + collection_formats=None, + _preload_content=True, + _request_timeout=None, + ): + """Makes the HTTP request (synchronous) and returns deserialized data. + + To make an async_req request, set the async_req parameter. + + :param resource_path: Path to method endpoint. + :param method: Method to call. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings list: Auth Settings names for the request. + :param response: Response data type. + :param files dict: key -> filename, value -> filepath, + for `multipart/form-data`. + :param async_req bool: execute request asynchronously + :param _return_http_data_only: response data without head status code + and headers + :param collection_formats: dict of collection formats for path, query, + header, and post parameters. + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: + If async_req parameter is True, + the request will be called asynchronously. + The method will return the request thread. + If parameter async_req is False or missing, + then the method will return the response directly. + """ + if not async_req: + return self.__call_api( + resource_path, + method, + path_params, + query_params, + header_params, + body, + post_params, + files, + response_type, + auth_settings, + _return_http_data_only, + collection_formats, + _preload_content, + _request_timeout, + ) + else: + thread = self.pool.apply_async( + self.__call_api, + ( + resource_path, + method, + path_params, + query_params, + header_params, + body, + post_params, + files, + response_type, + auth_settings, + _return_http_data_only, + collection_formats, + _preload_content, + _request_timeout, + ), + ) + return thread + + def request( + self, + method, + url, + query_params=None, + headers=None, + post_params=None, + body=None, + _preload_content=True, + _request_timeout=None, + ): + """Makes the HTTP request using RESTClient.""" + if method == "GET": + return self.rest_client.GET( + url, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + headers=headers, + ) + elif method == "HEAD": + return self.rest_client.HEAD( + url, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + headers=headers, + ) + elif method == "OPTIONS": + return self.rest_client.OPTIONS( + url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) + elif method == "POST": + return self.rest_client.POST( + url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) + elif method == "PUT": + return self.rest_client.PUT( + url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) + elif method == "PATCH": + return self.rest_client.PATCH( + url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) + elif method == "DELETE": + return self.rest_client.DELETE( + url, + query_params=query_params, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) + else: + raise ValueError( + "http method must be `GET`, `HEAD`, `OPTIONS`," + " `POST`, `PATCH`, `PUT` or `DELETE`." + ) + + def parameters_to_tuples(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: Parameters as list of tuples, collections formatted + """ + new_params = [] + if collection_formats is None: + collection_formats = {} + for k, v in ( + six.iteritems(params) if isinstance(params, dict) else params + ): # noqa: E501 + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == "multi": + new_params.extend((k, value) for value in v) + else: + if collection_format == "ssv": + delimiter = " " + elif collection_format == "tsv": + delimiter = "\t" + elif collection_format == "pipes": + delimiter = "|" + else: # csv is the default + delimiter = "," + new_params.append( + (k, delimiter.join(str(value) for value in v)) + ) + else: + new_params.append((k, v)) + return new_params + + def prepare_post_parameters(self, post_params=None, files=None): + """Builds form parameters. + + :param post_params: Normal form parameters. + :param files: File parameters. + :return: Form parameters with files. + """ + params = [] + + if post_params: + params = post_params + + if files: + for k, v in six.iteritems(files): + if not v: + continue + file_names = v if type(v) is list else [v] + for n in file_names: + with open(n, "rb") as f: + filename = os.path.basename(f.name) + filedata = f.read() + mimetype = ( + mimetypes.guess_type(filename)[0] + or "application/octet-stream" + ) + params.append( + tuple([k, tuple([filename, filedata, mimetype])]) + ) + + return params + + def select_header_accept(self, accepts): + """Returns `Accept` based on an array of accepts provided. + + :param accepts: List of headers. + :return: Accept (e.g. application/json). + """ + if not accepts: + return + + accepts = [x.lower() for x in accepts] + + if "application/json" in accepts: + return "application/json" + else: + return ", ".join(accepts) + + def select_header_content_type(self, content_types): + """Returns `Content-Type` based on an array of content_types provided. + + :param content_types: List of content-types. + :return: Content-Type (e.g. application/json). + """ + if not content_types: + return "application/json" + + content_types = [x.lower() for x in content_types] + + if "application/json" in content_types or "*/*" in content_types: + return "application/json" + else: + return content_types[0] + + def update_params_for_auth(self, headers, querys, auth_settings): + """Updates header and query params based on authentication setting. + + :param headers: Header parameters dict to be updated. + :param querys: Query parameters tuple list to be updated. + :param auth_settings: Authentication setting identifiers list. + """ + if not auth_settings: + return + + for auth in auth_settings: + auth_setting = self.configuration.auth_settings().get(auth) + if auth_setting: + if not auth_setting["value"]: + continue + elif auth_setting["in"] == "header": + headers[auth_setting["key"]] = auth_setting["value"] + elif auth_setting["in"] == "query": + querys.append((auth_setting["key"], auth_setting["value"])) + else: + raise ValueError( + "Authentication token must be in `query` or `header`" + ) + + def __deserialize_file(self, response): + """Deserializes body to file + + Saves response body into a file in a temporary folder, + using the filename from the `Content-Disposition` header if provided. + + :param response: RESTResponse. + :return: file path. + """ + fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) + os.close(fd) + os.remove(path) + + content_disposition = response.getheader("Content-Disposition") + if content_disposition: + filename = re.search( + r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition + ).group(1) + path = os.path.join(os.path.dirname(path), filename) + + with open(path, "wb") as f: + f.write(response.data) + + return path + + def __deserialize_primitive(self, data, klass): + """Deserializes string to primitive type. + + :param data: str. + :param klass: class literal. + + :return: int, long, float, str, bool. + """ + try: + return klass(data) + except UnicodeEncodeError: + return six.text_type(data) + except TypeError: + return data + + def __deserialize_object(self, value): + """Return an original value. + + :return: object. + """ + return value + + def __deserialize_date(self, string): + """Deserializes string to date. + + :param string: str. + :return: date. + """ + try: + from dateutil.parser import parse + + return parse(string).date() + except ImportError: + return string + except ValueError: + raise rest.ApiException( + status=0, + reason="Failed to parse `{0}` as date object".format(string), + ) + + def __deserialize_datatime(self, string): + """Deserializes string to datetime. + + The string should be in iso8601 datetime format. + + :param string: str. + :return: datetime. + """ + try: + from dateutil.parser import parse + + return parse(string) + except ImportError: + return string + except ValueError: + raise rest.ApiException( + status=0, + reason=( + "Failed to parse `{0}` as datetime object".format(string) + ), + ) + + def __deserialize_model(self, data, klass): + """Deserializes list or dict to model. + + :param data: dict, list. + :param klass: class literal. + :return: model object. + """ + + if not klass.openapi_types and not hasattr( + klass, "get_real_child_model" + ): + return data + + kwargs = {} + if klass.openapi_types is not None: + for attr, attr_type in six.iteritems(klass.openapi_types): + if ( + data is not None + and klass.attribute_map[attr] in data + and isinstance(data, (list, dict)) + ): + value = data[klass.attribute_map[attr]] + kwargs[attr] = self.__deserialize(value, attr_type) + + instance = klass(**kwargs) + + if hasattr(instance, "get_real_child_model"): + klass_name = instance.get_real_child_model(data) + if klass_name: + instance = self.__deserialize(data, klass_name) + return instance diff --git a/python-packages/sra_client/sra_client/configuration.py b/python-packages/sra_client/sra_client/configuration.py new file mode 100644 index 000000000..9b0cc05bb --- /dev/null +++ b/python-packages/sra_client/sra_client/configuration.py @@ -0,0 +1,225 @@ +# coding: utf-8 + + +from __future__ import absolute_import + +import copy +import logging +import multiprocessing +import sys +import urllib3 + +import six +from six.moves import http_client as httplib + + +class TypeWithDefault(type): + def __init__(cls, name, bases, dct): + super(TypeWithDefault, cls).__init__(name, bases, dct) + cls._default = None + + def __call__(cls): + if cls._default is None: + cls._default = type.__call__(cls) + return copy.copy(cls._default) + + def set_default(cls, default): + cls._default = copy.copy(default) + + +class Configuration(six.with_metaclass(TypeWithDefault, object)): + """NOTE: This class is auto generated by OpenAPI Generator + + Ref: https://openapi-generator.tech + Do not edit the class manually. + """ + + def __init__(self): + """Constructor""" + # Default Base url + self.host = "http://localhost:3000" + # Temp file folder for downloading files + self.temp_folder_path = None + + # Authentication Settings + # dict to store API key(s) + self.api_key = {} + # dict to store API prefix (e.g. Bearer) + self.api_key_prefix = {} + # Username for HTTP basic authentication + self.username = "" + # Password for HTTP basic authentication + self.password = "" + + # Logging Settings + self.logger = {} + self.logger["package_logger"] = logging.getLogger("sra_client") + self.logger["urllib3_logger"] = logging.getLogger("urllib3") + # Log format + self.logger_format = "%(asctime)s %(levelname)s %(message)s" + # Log stream handler + self.logger_stream_handler = None + # Log file handler + self.logger_file_handler = None + # Debug file location + self.logger_file = None + # Debug switch + self.debug = False + + # SSL/TLS verification + # Set this to false to skip verifying SSL certificate when calling API + # from https server. + self.verify_ssl = True + # Set this to customize the certificate file to verify the peer. + self.ssl_ca_cert = None + # client certificate file + self.cert_file = None + # client key file + self.key_file = None + # Set this to True/False to enable/disable SSL hostname verification. + self.assert_hostname = None + + # urllib3 connection pool's maximum number of connections saved + # per pool. urllib3 uses 1 connection as default value, but this is + # not the best value when you are making a lot of possibly parallel + # requests to the same host, which is often the case here. + # cpu_count * 5 is used as default value to increase performance. + self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 + + # Proxy URL + self.proxy = None + # Safe chars for path_param + self.safe_chars_for_path_param = "" + + @property + def logger_file(self): + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + return self.__logger_file + + @logger_file.setter + def logger_file(self, value): + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + self.__logger_file = value + if self.__logger_file: + # If set logging file, + # then add file handler and remove stream handler. + self.logger_file_handler = logging.FileHandler(self.__logger_file) + self.logger_file_handler.setFormatter(self.logger_formatter) + for _, logger in six.iteritems(self.logger): + logger.addHandler(self.logger_file_handler) + + @property + def debug(self): + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + return self.__debug + + @debug.setter + def debug(self, value): + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + self.__debug = value + if self.__debug: + # if debug status is True, turn on debug logging + for _, logger in six.iteritems(self.logger): + logger.setLevel(logging.DEBUG) + # turn on httplib debug + httplib.HTTPConnection.debuglevel = 1 + else: + # if debug status is False, turn off debug logging, + # setting log level to default `logging.WARNING` + for _, logger in six.iteritems(self.logger): + logger.setLevel(logging.WARNING) + # turn off httplib debug + httplib.HTTPConnection.debuglevel = 0 + + @property + def logger_format(self): + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + return self.__logger_format + + @logger_format.setter + def logger_format(self, value): + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + self.__logger_format = value + self.logger_formatter = logging.Formatter(self.__logger_format) + + def get_api_key_with_prefix(self, identifier): + """Gets API key (with prefix if set). + + :param identifier: The identifier of apiKey. + :return: The token for api key authentication. + """ + if self.api_key.get(identifier) and self.api_key_prefix.get( + identifier + ): + return ( + self.api_key_prefix[identifier] + + " " + + self.api_key[identifier] + ) # noqa: E501 + elif self.api_key.get(identifier): + return self.api_key[identifier] + + def get_basic_auth_token(self): + """Gets HTTP basic authentication header (string). + + :return: The token for basic HTTP authentication. + """ + return urllib3.util.make_headers( + basic_auth=self.username + ":" + self.password + ).get("authorization") + + def auth_settings(self): + """Gets Auth Settings dict for api client. + + :return: The Auth Settings information dict. + """ + return {} + + def to_debug_report(self): + """Gets the essential information for debugging. + + :return: The report for debugging. + """ + return ( + "Python SDK Debug Report:\n" + "OS: {env}\n" + "Python Version: {pyversion}\n" + "Version of the API: 2.0.0\n" + "SDK Package Version: 1.0.0".format( + env=sys.platform, pyversion=sys.version + ) + ) diff --git a/python-packages/sra_client/sra_client/models/__init__.py b/python-packages/sra_client/sra_client/models/__init__.py new file mode 100644 index 000000000..5e6d1baa3 --- /dev/null +++ b/python-packages/sra_client/sra_client/models/__init__.py @@ -0,0 +1,49 @@ +# 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 diff --git a/python-packages/sra_client/sra_client/models/order_schema.py b/python-packages/sra_client/sra_client/models/order_schema.py new file mode 100644 index 000000000..48fef39d8 --- /dev/null +++ b/python-packages/sra_client/sra_client/models/order_schema.py @@ -0,0 +1,550 @@ +# coding: utf-8 + + +import pprint +import re # noqa: F401 + +import six + + +class OrderSchema(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + 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", + } + + attribute_map = { + "maker_address": "makerAddress", + "taker_address": "takerAddress", + "maker_fee": "makerFee", + "taker_fee": "takerFee", + "sender_address": "senderAddress", + "maker_asset_amount": "makerAssetAmount", + "taker_asset_amount": "takerAssetAmount", + "maker_asset_data": "makerAssetData", + "taker_asset_data": "takerAssetData", + "salt": "salt", + "exchange_address": "exchangeAddress", + "fee_recipient_address": "feeRecipientAddress", + "expiration_time_seconds": "expirationTimeSeconds", + } + + def __init__( + self, + maker_address=None, + taker_address=None, + maker_fee=None, + taker_fee=None, + sender_address=None, + maker_asset_amount=None, + taker_asset_amount=None, + maker_asset_data=None, + taker_asset_data=None, + salt=None, + exchange_address=None, + fee_recipient_address=None, + expiration_time_seconds=None, + ): # noqa: E501 + """OrderSchema - a model defined in OpenAPI""" # noqa: E501 + + self._maker_address = None + self._taker_address = None + self._maker_fee = None + self._taker_fee = None + self._sender_address = None + self._maker_asset_amount = None + self._taker_asset_amount = None + self._maker_asset_data = None + self._taker_asset_data = None + self._salt = None + self._exchange_address = None + self._fee_recipient_address = None + self._expiration_time_seconds = None + self.discriminator = None + + self.maker_address = maker_address + self.taker_address = taker_address + self.maker_fee = maker_fee + self.taker_fee = taker_fee + self.sender_address = sender_address + self.maker_asset_amount = maker_asset_amount + self.taker_asset_amount = taker_asset_amount + self.maker_asset_data = maker_asset_data + self.taker_asset_data = taker_asset_data + self.salt = salt + self.exchange_address = exchange_address + self.fee_recipient_address = fee_recipient_address + self.expiration_time_seconds = expiration_time_seconds + + @property + def maker_address(self): + """Gets the maker_address of this OrderSchema. # noqa: E501 + + + :return: The maker_address of this OrderSchema. # noqa: E501 + :rtype: str + """ + return self._maker_address + + @maker_address.setter + def maker_address(self, maker_address): + """Sets the maker_address of this OrderSchema. + + + :param maker_address: The maker_address of this OrderSchema. # noqa: E501 + :type: str + """ + if maker_address is None: + raise ValueError( + "Invalid value for `maker_address`, must not be `None`" + ) # noqa: E501 + if maker_address is not None and not re.search( + r"^0x[0-9a-f]{40}$", maker_address + ): # noqa: E501 + raise ValueError( + r"Invalid value for `maker_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" + ) # noqa: E501 + + self._maker_address = maker_address + + @property + def taker_address(self): + """Gets the taker_address of this OrderSchema. # noqa: E501 + + + :return: The taker_address of this OrderSchema. # noqa: E501 + :rtype: str + """ + return self._taker_address + + @taker_address.setter + def taker_address(self, taker_address): + """Sets the taker_address of this OrderSchema. + + + :param taker_address: The taker_address of this OrderSchema. # noqa: E501 + :type: str + """ + if taker_address is None: + raise ValueError( + "Invalid value for `taker_address`, must not be `None`" + ) # noqa: E501 + if taker_address is not None and not re.search( + r"^0x[0-9a-f]{40}$", taker_address + ): # noqa: E501 + raise ValueError( + r"Invalid value for `taker_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" + ) # noqa: E501 + + self._taker_address = taker_address + + @property + def maker_fee(self): + """Gets the maker_fee of this OrderSchema. # noqa: E501 + + + :return: The maker_fee of this OrderSchema. # noqa: E501 + :rtype: str + """ + return self._maker_fee + + @maker_fee.setter + def maker_fee(self, maker_fee): + """Sets the maker_fee of this OrderSchema. + + + :param maker_fee: The maker_fee of this OrderSchema. # noqa: E501 + :type: str + """ + if maker_fee is None: + raise ValueError( + "Invalid value for `maker_fee`, must not be `None`" + ) # noqa: E501 + if maker_fee is not None and not re.search( + r"^\\d+$", maker_fee + ): # noqa: E501 + raise ValueError( + r"Invalid value for `maker_fee`, must be a follow pattern or equal to `/^\\d+$/`" + ) # noqa: E501 + + self._maker_fee = maker_fee + + @property + def taker_fee(self): + """Gets the taker_fee of this OrderSchema. # noqa: E501 + + + :return: The taker_fee of this OrderSchema. # noqa: E501 + :rtype: str + """ + return self._taker_fee + + @taker_fee.setter + def taker_fee(self, taker_fee): + """Sets the taker_fee of this OrderSchema. + + + :param taker_fee: The taker_fee of this OrderSchema. # noqa: E501 + :type: str + """ + if taker_fee is None: + raise ValueError( + "Invalid value for `taker_fee`, must not be `None`" + ) # noqa: E501 + if taker_fee is not None and not re.search( + r"^\\d+$", taker_fee + ): # noqa: E501 + raise ValueError( + r"Invalid value for `taker_fee`, must be a follow pattern or equal to `/^\\d+$/`" + ) # noqa: E501 + + self._taker_fee = taker_fee + + @property + def sender_address(self): + """Gets the sender_address of this OrderSchema. # noqa: E501 + + + :return: The sender_address of this OrderSchema. # noqa: E501 + :rtype: str + """ + return self._sender_address + + @sender_address.setter + def sender_address(self, sender_address): + """Sets the sender_address of this OrderSchema. + + + :param sender_address: The sender_address of this OrderSchema. # noqa: E501 + :type: str + """ + if sender_address is None: + raise ValueError( + "Invalid value for `sender_address`, must not be `None`" + ) # noqa: E501 + if sender_address is not None and not re.search( + r"^0x[0-9a-f]{40}$", sender_address + ): # noqa: E501 + raise ValueError( + r"Invalid value for `sender_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" + ) # noqa: E501 + + self._sender_address = sender_address + + @property + def maker_asset_amount(self): + """Gets the maker_asset_amount of this OrderSchema. # noqa: E501 + + + :return: The maker_asset_amount of this OrderSchema. # noqa: E501 + :rtype: str + """ + return self._maker_asset_amount + + @maker_asset_amount.setter + def maker_asset_amount(self, maker_asset_amount): + """Sets the maker_asset_amount of this OrderSchema. + + + :param maker_asset_amount: The maker_asset_amount of this OrderSchema. # noqa: E501 + :type: str + """ + if maker_asset_amount is None: + raise ValueError( + "Invalid value for `maker_asset_amount`, must not be `None`" + ) # noqa: E501 + if maker_asset_amount is not None and not re.search( + r"^\\d+$", maker_asset_amount + ): # noqa: E501 + raise ValueError( + r"Invalid value for `maker_asset_amount`, must be a follow pattern or equal to `/^\\d+$/`" + ) # noqa: E501 + + self._maker_asset_amount = maker_asset_amount + + @property + def taker_asset_amount(self): + """Gets the taker_asset_amount of this OrderSchema. # noqa: E501 + + + :return: The taker_asset_amount of this OrderSchema. # noqa: E501 + :rtype: str + """ + return self._taker_asset_amount + + @taker_asset_amount.setter + def taker_asset_amount(self, taker_asset_amount): + """Sets the taker_asset_amount of this OrderSchema. + + + :param taker_asset_amount: The taker_asset_amount of this OrderSchema. # noqa: E501 + :type: str + """ + if taker_asset_amount is None: + raise ValueError( + "Invalid value for `taker_asset_amount`, must not be `None`" + ) # noqa: E501 + if taker_asset_amount is not None and not re.search( + r"^\\d+$", taker_asset_amount + ): # noqa: E501 + raise ValueError( + r"Invalid value for `taker_asset_amount`, must be a follow pattern or equal to `/^\\d+$/`" + ) # noqa: E501 + + self._taker_asset_amount = taker_asset_amount + + @property + def maker_asset_data(self): + """Gets the maker_asset_data of this OrderSchema. # noqa: E501 + + + :return: The maker_asset_data of this OrderSchema. # noqa: E501 + :rtype: str + """ + return self._maker_asset_data + + @maker_asset_data.setter + def maker_asset_data(self, maker_asset_data): + """Sets the maker_asset_data of this OrderSchema. + + + :param maker_asset_data: The maker_asset_data of this OrderSchema. # noqa: E501 + :type: str + """ + if maker_asset_data is None: + raise ValueError( + "Invalid value for `maker_asset_data`, must not be `None`" + ) # noqa: E501 + if maker_asset_data is not None and not re.search( + r"^0x(([0-9a-f][0-9a-f])+)?$", maker_asset_data + ): # noqa: E501 + raise ValueError( + r"Invalid value for `maker_asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" + ) # noqa: E501 + + self._maker_asset_data = maker_asset_data + + @property + def taker_asset_data(self): + """Gets the taker_asset_data of this OrderSchema. # noqa: E501 + + + :return: The taker_asset_data of this OrderSchema. # noqa: E501 + :rtype: str + """ + return self._taker_asset_data + + @taker_asset_data.setter + def taker_asset_data(self, taker_asset_data): + """Sets the taker_asset_data of this OrderSchema. + + + :param taker_asset_data: The taker_asset_data of this OrderSchema. # noqa: E501 + :type: str + """ + if taker_asset_data is None: + raise ValueError( + "Invalid value for `taker_asset_data`, must not be `None`" + ) # noqa: E501 + if taker_asset_data is not None and not re.search( + r"^0x(([0-9a-f][0-9a-f])+)?$", taker_asset_data + ): # noqa: E501 + raise ValueError( + r"Invalid value for `taker_asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" + ) # noqa: E501 + + self._taker_asset_data = taker_asset_data + + @property + def salt(self): + """Gets the salt of this OrderSchema. # noqa: E501 + + + :return: The salt of this OrderSchema. # noqa: E501 + :rtype: str + """ + return self._salt + + @salt.setter + def salt(self, salt): + """Sets the salt of this OrderSchema. + + + :param salt: The salt of this OrderSchema. # noqa: E501 + :type: str + """ + if salt is None: + raise ValueError( + "Invalid value for `salt`, must not be `None`" + ) # noqa: E501 + if salt is not None and not re.search(r"^\\d+$", salt): # noqa: E501 + raise ValueError( + r"Invalid value for `salt`, must be a follow pattern or equal to `/^\\d+$/`" + ) # noqa: E501 + + self._salt = salt + + @property + def exchange_address(self): + """Gets the exchange_address of this OrderSchema. # noqa: E501 + + + :return: The exchange_address of this OrderSchema. # noqa: E501 + :rtype: str + """ + return self._exchange_address + + @exchange_address.setter + def exchange_address(self, exchange_address): + """Sets the exchange_address of this OrderSchema. + + + :param exchange_address: The exchange_address of this OrderSchema. # noqa: E501 + :type: str + """ + if exchange_address is None: + raise ValueError( + "Invalid value for `exchange_address`, must not be `None`" + ) # noqa: E501 + if exchange_address is not None and not re.search( + r"^0x[0-9a-f]{40}$", exchange_address + ): # noqa: E501 + raise ValueError( + r"Invalid value for `exchange_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" + ) # noqa: E501 + + self._exchange_address = exchange_address + + @property + def fee_recipient_address(self): + """Gets the fee_recipient_address of this OrderSchema. # noqa: E501 + + + :return: The fee_recipient_address of this OrderSchema. # noqa: E501 + :rtype: str + """ + return self._fee_recipient_address + + @fee_recipient_address.setter + def fee_recipient_address(self, fee_recipient_address): + """Sets the fee_recipient_address of this OrderSchema. + + + :param fee_recipient_address: The fee_recipient_address of this OrderSchema. # noqa: E501 + :type: str + """ + if fee_recipient_address is None: + raise ValueError( + "Invalid value for `fee_recipient_address`, must not be `None`" + ) # noqa: E501 + if fee_recipient_address is not None and not re.search( + r"^0x[0-9a-f]{40}$", fee_recipient_address + ): # noqa: E501 + raise ValueError( + r"Invalid value for `fee_recipient_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" + ) # noqa: E501 + + self._fee_recipient_address = fee_recipient_address + + @property + def expiration_time_seconds(self): + """Gets the expiration_time_seconds of this OrderSchema. # noqa: E501 + + + :return: The expiration_time_seconds of this OrderSchema. # noqa: E501 + :rtype: str + """ + return self._expiration_time_seconds + + @expiration_time_seconds.setter + def expiration_time_seconds(self, expiration_time_seconds): + """Sets the expiration_time_seconds of this OrderSchema. + + + :param expiration_time_seconds: The expiration_time_seconds of this OrderSchema. # noqa: E501 + :type: str + """ + if expiration_time_seconds is None: + raise ValueError( + "Invalid value for `expiration_time_seconds`, must not be `None`" + ) # noqa: E501 + if expiration_time_seconds is not None and not re.search( + r"^\\d+$", expiration_time_seconds + ): # noqa: E501 + raise ValueError( + r"Invalid value for `expiration_time_seconds`, must be a follow pattern or equal to `/^\\d+$/`" + ) # noqa: E501 + + self._expiration_time_seconds = expiration_time_seconds + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value, + ) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, OrderSchema): + return False + + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other diff --git a/python-packages/sra_client/sra_client/models/paginated_collection_schema.py b/python-packages/sra_client/sra_client/models/paginated_collection_schema.py new file mode 100644 index 000000000..4c73d31f4 --- /dev/null +++ b/python-packages/sra_client/sra_client/models/paginated_collection_schema.py @@ -0,0 +1,161 @@ +# coding: utf-8 + + +import pprint +import re # noqa: F401 + +import six + + +class PaginatedCollectionSchema(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"total": "float", "per_page": "float", "page": "float"} + + attribute_map = {"total": "total", "per_page": "perPage", "page": "page"} + + def __init__(self, total=None, per_page=None, page=None): # noqa: E501 + """PaginatedCollectionSchema - a model defined in OpenAPI""" # noqa: E501 + + self._total = None + self._per_page = None + self._page = None + self.discriminator = None + + self.total = total + self.per_page = per_page + self.page = page + + @property + def total(self): + """Gets the total of this PaginatedCollectionSchema. # noqa: E501 + + + :return: The total of this PaginatedCollectionSchema. # noqa: E501 + :rtype: float + """ + return self._total + + @total.setter + def total(self, total): + """Sets the total of this PaginatedCollectionSchema. + + + :param total: The total of this PaginatedCollectionSchema. # noqa: E501 + :type: float + """ + if total is None: + raise ValueError( + "Invalid value for `total`, must not be `None`" + ) # noqa: E501 + + self._total = total + + @property + def per_page(self): + """Gets the per_page of this PaginatedCollectionSchema. # noqa: E501 + + + :return: The per_page of this PaginatedCollectionSchema. # noqa: E501 + :rtype: float + """ + return self._per_page + + @per_page.setter + def per_page(self, per_page): + """Sets the per_page of this PaginatedCollectionSchema. + + + :param per_page: The per_page of this PaginatedCollectionSchema. # noqa: E501 + :type: float + """ + if per_page is None: + raise ValueError( + "Invalid value for `per_page`, must not be `None`" + ) # noqa: E501 + + self._per_page = per_page + + @property + def page(self): + """Gets the page of this PaginatedCollectionSchema. # noqa: E501 + + + :return: The page of this PaginatedCollectionSchema. # noqa: E501 + :rtype: float + """ + return self._page + + @page.setter + def page(self, page): + """Sets the page of this PaginatedCollectionSchema. + + + :param page: The page of this PaginatedCollectionSchema. # noqa: E501 + :type: float + """ + if page is None: + raise ValueError( + "Invalid value for `page`, must not be `None`" + ) # noqa: E501 + + self._page = page + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value, + ) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, PaginatedCollectionSchema): + return False + + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other diff --git a/python-packages/sra_client/sra_client/models/relayer_api_asset_data_pairs_response_schema.py b/python-packages/sra_client/sra_client/models/relayer_api_asset_data_pairs_response_schema.py new file mode 100644 index 000000000..97110b13a --- /dev/null +++ b/python-packages/sra_client/sra_client/models/relayer_api_asset_data_pairs_response_schema.py @@ -0,0 +1,107 @@ +# coding: utf-8 + + +import pprint +import re # noqa: F401 + +import six + + +class RelayerApiAssetDataPairsResponseSchema(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"records": "list[object]"} + + attribute_map = {"records": "records"} + + def __init__(self, records=None): # noqa: E501 + """RelayerApiAssetDataPairsResponseSchema - a model defined in OpenAPI""" # noqa: E501 + + self._records = None + self.discriminator = None + + self.records = records + + @property + def records(self): + """Gets the records of this RelayerApiAssetDataPairsResponseSchema. # noqa: E501 + + + :return: The records of this RelayerApiAssetDataPairsResponseSchema. # noqa: E501 + :rtype: list[object] + """ + return self._records + + @records.setter + def records(self, records): + """Sets the records of this RelayerApiAssetDataPairsResponseSchema. + + + :param records: The records of this RelayerApiAssetDataPairsResponseSchema. # noqa: E501 + :type: list[object] + """ + if records is None: + raise ValueError( + "Invalid value for `records`, must not be `None`" + ) # noqa: E501 + + self._records = records + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value, + ) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, RelayerApiAssetDataPairsResponseSchema): + return False + + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other diff --git a/python-packages/sra_client/sra_client/models/relayer_api_asset_data_trade_info_schema.py b/python-packages/sra_client/sra_client/models/relayer_api_asset_data_trade_info_schema.py new file mode 100644 index 000000000..c449d0a6a --- /dev/null +++ b/python-packages/sra_client/sra_client/models/relayer_api_asset_data_trade_info_schema.py @@ -0,0 +1,209 @@ +# coding: utf-8 + + +import pprint +import re # noqa: F401 + +import six + + +class RelayerApiAssetDataTradeInfoSchema(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "asset_data": "str", + "min_amount": "str", + "max_amount": "str", + "precision": "float", + } + + attribute_map = { + "asset_data": "assetData", + "min_amount": "minAmount", + "max_amount": "maxAmount", + "precision": "precision", + } + + def __init__( + self, asset_data=None, min_amount=None, max_amount=None, precision=None + ): # noqa: E501 + """RelayerApiAssetDataTradeInfoSchema - a model defined in OpenAPI""" # noqa: E501 + + self._asset_data = None + self._min_amount = None + self._max_amount = None + self._precision = None + self.discriminator = None + + self.asset_data = asset_data + if min_amount is not None: + self.min_amount = min_amount + if max_amount is not None: + self.max_amount = max_amount + if precision is not None: + self.precision = precision + + @property + def asset_data(self): + """Gets the asset_data of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501 + + + :return: The asset_data of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501 + :rtype: str + """ + return self._asset_data + + @asset_data.setter + def asset_data(self, asset_data): + """Sets the asset_data of this RelayerApiAssetDataTradeInfoSchema. + + + :param asset_data: The asset_data of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501 + :type: str + """ + if asset_data is None: + raise ValueError( + "Invalid value for `asset_data`, must not be `None`" + ) # noqa: E501 + if asset_data is not None and not re.search( + r"^0x(([0-9a-f][0-9a-f])+)?$", asset_data + ): # noqa: E501 + raise ValueError( + r"Invalid value for `asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" + ) # noqa: E501 + + self._asset_data = asset_data + + @property + def min_amount(self): + """Gets the min_amount of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501 + + + :return: The min_amount of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501 + :rtype: str + """ + return self._min_amount + + @min_amount.setter + def min_amount(self, min_amount): + """Sets the min_amount of this RelayerApiAssetDataTradeInfoSchema. + + + :param min_amount: The min_amount of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501 + :type: str + """ + if min_amount is not None and not re.search( + r"^\\d+$", min_amount + ): # noqa: E501 + raise ValueError( + r"Invalid value for `min_amount`, must be a follow pattern or equal to `/^\\d+$/`" + ) # noqa: E501 + + self._min_amount = min_amount + + @property + def max_amount(self): + """Gets the max_amount of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501 + + + :return: The max_amount of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501 + :rtype: str + """ + return self._max_amount + + @max_amount.setter + def max_amount(self, max_amount): + """Sets the max_amount of this RelayerApiAssetDataTradeInfoSchema. + + + :param max_amount: The max_amount of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501 + :type: str + """ + if max_amount is not None and not re.search( + r"^\\d+$", max_amount + ): # noqa: E501 + raise ValueError( + r"Invalid value for `max_amount`, must be a follow pattern or equal to `/^\\d+$/`" + ) # noqa: E501 + + self._max_amount = max_amount + + @property + def precision(self): + """Gets the precision of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501 + + + :return: The precision of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501 + :rtype: float + """ + return self._precision + + @precision.setter + def precision(self, precision): + """Sets the precision of this RelayerApiAssetDataTradeInfoSchema. + + + :param precision: The precision of this RelayerApiAssetDataTradeInfoSchema. # noqa: E501 + :type: float + """ + + self._precision = precision + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value, + ) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, RelayerApiAssetDataTradeInfoSchema): + return False + + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other diff --git a/python-packages/sra_client/sra_client/models/relayer_api_error_response_schema.py b/python-packages/sra_client/sra_client/models/relayer_api_error_response_schema.py new file mode 100644 index 000000000..fd06bb9f4 --- /dev/null +++ b/python-packages/sra_client/sra_client/models/relayer_api_error_response_schema.py @@ -0,0 +1,176 @@ +# coding: utf-8 + + +import pprint +import re # noqa: F401 + +import six + + +class RelayerApiErrorResponseSchema(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "code": "int", + "reason": "str", + "validation_errors": "list[RelayerApiErrorResponseSchemaValidationErrors]", + } + + attribute_map = { + "code": "code", + "reason": "reason", + "validation_errors": "validationErrors", + } + + def __init__( + self, code=None, reason=None, validation_errors=None + ): # noqa: E501 + """RelayerApiErrorResponseSchema - a model defined in OpenAPI""" # noqa: E501 + + self._code = None + self._reason = None + self._validation_errors = None + self.discriminator = None + + self.code = code + self.reason = reason + if validation_errors is not None: + self.validation_errors = validation_errors + + @property + def code(self): + """Gets the code of this RelayerApiErrorResponseSchema. # noqa: E501 + + + :return: The code of this RelayerApiErrorResponseSchema. # noqa: E501 + :rtype: int + """ + return self._code + + @code.setter + def code(self, code): + """Sets the code of this RelayerApiErrorResponseSchema. + + + :param code: The code of this RelayerApiErrorResponseSchema. # noqa: E501 + :type: int + """ + if code is None: + raise ValueError( + "Invalid value for `code`, must not be `None`" + ) # noqa: E501 + if code is not None and code > 103: # noqa: E501 + raise ValueError( + "Invalid value for `code`, must be a value less than or equal to `103`" + ) # noqa: E501 + if code is not None and code < 100: # noqa: E501 + raise ValueError( + "Invalid value for `code`, must be a value greater than or equal to `100`" + ) # noqa: E501 + + self._code = code + + @property + def reason(self): + """Gets the reason of this RelayerApiErrorResponseSchema. # noqa: E501 + + + :return: The reason of this RelayerApiErrorResponseSchema. # noqa: E501 + :rtype: str + """ + return self._reason + + @reason.setter + def reason(self, reason): + """Sets the reason of this RelayerApiErrorResponseSchema. + + + :param reason: The reason of this RelayerApiErrorResponseSchema. # noqa: E501 + :type: str + """ + if reason is None: + raise ValueError( + "Invalid value for `reason`, must not be `None`" + ) # noqa: E501 + + self._reason = reason + + @property + def validation_errors(self): + """Gets the validation_errors of this RelayerApiErrorResponseSchema. # noqa: E501 + + + :return: The validation_errors of this RelayerApiErrorResponseSchema. # noqa: E501 + :rtype: list[RelayerApiErrorResponseSchemaValidationErrors] + """ + return self._validation_errors + + @validation_errors.setter + def validation_errors(self, validation_errors): + """Sets the validation_errors of this RelayerApiErrorResponseSchema. + + + :param validation_errors: The validation_errors of this RelayerApiErrorResponseSchema. # noqa: E501 + :type: list[RelayerApiErrorResponseSchemaValidationErrors] + """ + + self._validation_errors = validation_errors + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value, + ) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, RelayerApiErrorResponseSchema): + return False + + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other diff --git a/python-packages/sra_client/sra_client/models/relayer_api_error_response_schema_validation_errors.py b/python-packages/sra_client/sra_client/models/relayer_api_error_response_schema_validation_errors.py new file mode 100644 index 000000000..ee344bbf7 --- /dev/null +++ b/python-packages/sra_client/sra_client/models/relayer_api_error_response_schema_validation_errors.py @@ -0,0 +1,171 @@ +# coding: utf-8 + + +import pprint +import re # noqa: F401 + +import six + + +class RelayerApiErrorResponseSchemaValidationErrors(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"field": "str", "code": "int", "reason": "str"} + + attribute_map = {"field": "field", "code": "code", "reason": "reason"} + + def __init__(self, field=None, code=None, reason=None): # noqa: E501 + """RelayerApiErrorResponseSchemaValidationErrors - a model defined in OpenAPI""" # noqa: E501 + + self._field = None + self._code = None + self._reason = None + self.discriminator = None + + self.field = field + self.code = code + self.reason = reason + + @property + def field(self): + """Gets the field of this RelayerApiErrorResponseSchemaValidationErrors. # noqa: E501 + + + :return: The field of this RelayerApiErrorResponseSchemaValidationErrors. # noqa: E501 + :rtype: str + """ + return self._field + + @field.setter + def field(self, field): + """Sets the field of this RelayerApiErrorResponseSchemaValidationErrors. + + + :param field: The field of this RelayerApiErrorResponseSchemaValidationErrors. # noqa: E501 + :type: str + """ + if field is None: + raise ValueError( + "Invalid value for `field`, must not be `None`" + ) # noqa: E501 + + self._field = field + + @property + def code(self): + """Gets the code of this RelayerApiErrorResponseSchemaValidationErrors. # noqa: E501 + + + :return: The code of this RelayerApiErrorResponseSchemaValidationErrors. # noqa: E501 + :rtype: int + """ + return self._code + + @code.setter + def code(self, code): + """Sets the code of this RelayerApiErrorResponseSchemaValidationErrors. + + + :param code: The code of this RelayerApiErrorResponseSchemaValidationErrors. # noqa: E501 + :type: int + """ + if code is None: + raise ValueError( + "Invalid value for `code`, must not be `None`" + ) # noqa: E501 + if code is not None and code > 1006: # noqa: E501 + raise ValueError( + "Invalid value for `code`, must be a value less than or equal to `1006`" + ) # noqa: E501 + if code is not None and code < 1000: # noqa: E501 + raise ValueError( + "Invalid value for `code`, must be a value greater than or equal to `1000`" + ) # noqa: E501 + + self._code = code + + @property + def reason(self): + """Gets the reason of this RelayerApiErrorResponseSchemaValidationErrors. # noqa: E501 + + + :return: The reason of this RelayerApiErrorResponseSchemaValidationErrors. # noqa: E501 + :rtype: str + """ + return self._reason + + @reason.setter + def reason(self, reason): + """Sets the reason of this RelayerApiErrorResponseSchemaValidationErrors. + + + :param reason: The reason of this RelayerApiErrorResponseSchemaValidationErrors. # noqa: E501 + :type: str + """ + if reason is None: + raise ValueError( + "Invalid value for `reason`, must not be `None`" + ) # noqa: E501 + + self._reason = reason + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value, + ) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance( + other, RelayerApiErrorResponseSchemaValidationErrors + ): + return False + + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other diff --git a/python-packages/sra_client/sra_client/models/relayer_api_fee_recipients_response_schema.py b/python-packages/sra_client/sra_client/models/relayer_api_fee_recipients_response_schema.py new file mode 100644 index 000000000..002eb00d7 --- /dev/null +++ b/python-packages/sra_client/sra_client/models/relayer_api_fee_recipients_response_schema.py @@ -0,0 +1,107 @@ +# coding: utf-8 + + +import pprint +import re # noqa: F401 + +import six + + +class RelayerApiFeeRecipientsResponseSchema(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"records": "list[str]"} + + attribute_map = {"records": "records"} + + def __init__(self, records=None): # noqa: E501 + """RelayerApiFeeRecipientsResponseSchema - a model defined in OpenAPI""" # noqa: E501 + + self._records = None + self.discriminator = None + + self.records = records + + @property + def records(self): + """Gets the records of this RelayerApiFeeRecipientsResponseSchema. # noqa: E501 + + + :return: The records of this RelayerApiFeeRecipientsResponseSchema. # noqa: E501 + :rtype: list[str] + """ + return self._records + + @records.setter + def records(self, records): + """Sets the records of this RelayerApiFeeRecipientsResponseSchema. + + + :param records: The records of this RelayerApiFeeRecipientsResponseSchema. # noqa: E501 + :type: list[str] + """ + if records is None: + raise ValueError( + "Invalid value for `records`, must not be `None`" + ) # noqa: E501 + + self._records = records + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value, + ) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, RelayerApiFeeRecipientsResponseSchema): + return False + + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other diff --git a/python-packages/sra_client/sra_client/models/relayer_api_order_config_payload_schema.py b/python-packages/sra_client/sra_client/models/relayer_api_order_config_payload_schema.py new file mode 100644 index 000000000..8d19d80e2 --- /dev/null +++ b/python-packages/sra_client/sra_client/models/relayer_api_order_config_payload_schema.py @@ -0,0 +1,372 @@ +# coding: utf-8 + + +import pprint +import re # noqa: F401 + +import six + + +class RelayerApiOrderConfigPayloadSchema(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + 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_asset_amount": "str", + "taker_asset_amount": "str", + "maker_asset_data": "str", + "taker_asset_data": "str", + "exchange_address": "str", + "expiration_time_seconds": "str", + } + + attribute_map = { + "maker_address": "makerAddress", + "taker_address": "takerAddress", + "maker_asset_amount": "makerAssetAmount", + "taker_asset_amount": "takerAssetAmount", + "maker_asset_data": "makerAssetData", + "taker_asset_data": "takerAssetData", + "exchange_address": "exchangeAddress", + "expiration_time_seconds": "expirationTimeSeconds", + } + + def __init__( + self, + maker_address=None, + taker_address=None, + maker_asset_amount=None, + taker_asset_amount=None, + maker_asset_data=None, + taker_asset_data=None, + exchange_address=None, + expiration_time_seconds=None, + ): # noqa: E501 + """RelayerApiOrderConfigPayloadSchema - a model defined in OpenAPI""" # noqa: E501 + + self._maker_address = None + self._taker_address = None + self._maker_asset_amount = None + self._taker_asset_amount = None + self._maker_asset_data = None + self._taker_asset_data = None + self._exchange_address = None + self._expiration_time_seconds = None + self.discriminator = None + + self.maker_address = maker_address + self.taker_address = taker_address + self.maker_asset_amount = maker_asset_amount + self.taker_asset_amount = taker_asset_amount + self.maker_asset_data = maker_asset_data + self.taker_asset_data = taker_asset_data + self.exchange_address = exchange_address + self.expiration_time_seconds = expiration_time_seconds + + @property + def maker_address(self): + """Gets the maker_address of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + + + :return: The maker_address of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + :rtype: str + """ + return self._maker_address + + @maker_address.setter + def maker_address(self, maker_address): + """Sets the maker_address of this RelayerApiOrderConfigPayloadSchema. + + + :param maker_address: The maker_address of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + :type: str + """ + if maker_address is None: + raise ValueError( + "Invalid value for `maker_address`, must not be `None`" + ) # noqa: E501 + if maker_address is not None and not re.search( + r"^0x[0-9a-f]{40}$", maker_address + ): # noqa: E501 + raise ValueError( + r"Invalid value for `maker_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" + ) # noqa: E501 + + self._maker_address = maker_address + + @property + def taker_address(self): + """Gets the taker_address of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + + + :return: The taker_address of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + :rtype: str + """ + return self._taker_address + + @taker_address.setter + def taker_address(self, taker_address): + """Sets the taker_address of this RelayerApiOrderConfigPayloadSchema. + + + :param taker_address: The taker_address of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + :type: str + """ + if taker_address is None: + raise ValueError( + "Invalid value for `taker_address`, must not be `None`" + ) # noqa: E501 + if taker_address is not None and not re.search( + r"^0x[0-9a-f]{40}$", taker_address + ): # noqa: E501 + raise ValueError( + r"Invalid value for `taker_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" + ) # noqa: E501 + + self._taker_address = taker_address + + @property + def maker_asset_amount(self): + """Gets the maker_asset_amount of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + + + :return: The maker_asset_amount of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + :rtype: str + """ + return self._maker_asset_amount + + @maker_asset_amount.setter + def maker_asset_amount(self, maker_asset_amount): + """Sets the maker_asset_amount of this RelayerApiOrderConfigPayloadSchema. + + + :param maker_asset_amount: The maker_asset_amount of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + :type: str + """ + if maker_asset_amount is None: + raise ValueError( + "Invalid value for `maker_asset_amount`, must not be `None`" + ) # noqa: E501 + if maker_asset_amount is not None and not re.search( + r"^\\d+$", maker_asset_amount + ): # noqa: E501 + raise ValueError( + r"Invalid value for `maker_asset_amount`, must be a follow pattern or equal to `/^\\d+$/`" + ) # noqa: E501 + + self._maker_asset_amount = maker_asset_amount + + @property + def taker_asset_amount(self): + """Gets the taker_asset_amount of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + + + :return: The taker_asset_amount of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + :rtype: str + """ + return self._taker_asset_amount + + @taker_asset_amount.setter + def taker_asset_amount(self, taker_asset_amount): + """Sets the taker_asset_amount of this RelayerApiOrderConfigPayloadSchema. + + + :param taker_asset_amount: The taker_asset_amount of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + :type: str + """ + if taker_asset_amount is None: + raise ValueError( + "Invalid value for `taker_asset_amount`, must not be `None`" + ) # noqa: E501 + if taker_asset_amount is not None and not re.search( + r"^\\d+$", taker_asset_amount + ): # noqa: E501 + raise ValueError( + r"Invalid value for `taker_asset_amount`, must be a follow pattern or equal to `/^\\d+$/`" + ) # noqa: E501 + + self._taker_asset_amount = taker_asset_amount + + @property + def maker_asset_data(self): + """Gets the maker_asset_data of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + + + :return: The maker_asset_data of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + :rtype: str + """ + return self._maker_asset_data + + @maker_asset_data.setter + def maker_asset_data(self, maker_asset_data): + """Sets the maker_asset_data of this RelayerApiOrderConfigPayloadSchema. + + + :param maker_asset_data: The maker_asset_data of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + :type: str + """ + if maker_asset_data is None: + raise ValueError( + "Invalid value for `maker_asset_data`, must not be `None`" + ) # noqa: E501 + if maker_asset_data is not None and not re.search( + r"^0x(([0-9a-f][0-9a-f])+)?$", maker_asset_data + ): # noqa: E501 + raise ValueError( + r"Invalid value for `maker_asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" + ) # noqa: E501 + + self._maker_asset_data = maker_asset_data + + @property + def taker_asset_data(self): + """Gets the taker_asset_data of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + + + :return: The taker_asset_data of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + :rtype: str + """ + return self._taker_asset_data + + @taker_asset_data.setter + def taker_asset_data(self, taker_asset_data): + """Sets the taker_asset_data of this RelayerApiOrderConfigPayloadSchema. + + + :param taker_asset_data: The taker_asset_data of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + :type: str + """ + if taker_asset_data is None: + raise ValueError( + "Invalid value for `taker_asset_data`, must not be `None`" + ) # noqa: E501 + if taker_asset_data is not None and not re.search( + r"^0x(([0-9a-f][0-9a-f])+)?$", taker_asset_data + ): # noqa: E501 + raise ValueError( + r"Invalid value for `taker_asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" + ) # noqa: E501 + + self._taker_asset_data = taker_asset_data + + @property + def exchange_address(self): + """Gets the exchange_address of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + + + :return: The exchange_address of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + :rtype: str + """ + return self._exchange_address + + @exchange_address.setter + def exchange_address(self, exchange_address): + """Sets the exchange_address of this RelayerApiOrderConfigPayloadSchema. + + + :param exchange_address: The exchange_address of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + :type: str + """ + if exchange_address is None: + raise ValueError( + "Invalid value for `exchange_address`, must not be `None`" + ) # noqa: E501 + if exchange_address is not None and not re.search( + r"^0x[0-9a-f]{40}$", exchange_address + ): # noqa: E501 + raise ValueError( + r"Invalid value for `exchange_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" + ) # noqa: E501 + + self._exchange_address = exchange_address + + @property + def expiration_time_seconds(self): + """Gets the expiration_time_seconds of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + + + :return: The expiration_time_seconds of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + :rtype: str + """ + return self._expiration_time_seconds + + @expiration_time_seconds.setter + def expiration_time_seconds(self, expiration_time_seconds): + """Sets the expiration_time_seconds of this RelayerApiOrderConfigPayloadSchema. + + + :param expiration_time_seconds: The expiration_time_seconds of this RelayerApiOrderConfigPayloadSchema. # noqa: E501 + :type: str + """ + if expiration_time_seconds is None: + raise ValueError( + "Invalid value for `expiration_time_seconds`, must not be `None`" + ) # noqa: E501 + if expiration_time_seconds is not None and not re.search( + r"^\\d+$", expiration_time_seconds + ): # noqa: E501 + raise ValueError( + r"Invalid value for `expiration_time_seconds`, must be a follow pattern or equal to `/^\\d+$/`" + ) # noqa: E501 + + self._expiration_time_seconds = expiration_time_seconds + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value, + ) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, RelayerApiOrderConfigPayloadSchema): + return False + + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other diff --git a/python-packages/sra_client/sra_client/models/relayer_api_order_config_response_schema.py b/python-packages/sra_client/sra_client/models/relayer_api_order_config_response_schema.py new file mode 100644 index 000000000..a6bfcf32b --- /dev/null +++ b/python-packages/sra_client/sra_client/models/relayer_api_order_config_response_schema.py @@ -0,0 +1,228 @@ +# coding: utf-8 + + +import pprint +import re # noqa: F401 + +import six + + +class RelayerApiOrderConfigResponseSchema(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "maker_fee": "str", + "taker_fee": "str", + "fee_recipient_address": "str", + "sender_address": "str", + } + + attribute_map = { + "maker_fee": "makerFee", + "taker_fee": "takerFee", + "fee_recipient_address": "feeRecipientAddress", + "sender_address": "senderAddress", + } + + def __init__( + self, + maker_fee=None, + taker_fee=None, + fee_recipient_address=None, + sender_address=None, + ): # noqa: E501 + """RelayerApiOrderConfigResponseSchema - a model defined in OpenAPI""" # noqa: E501 + + self._maker_fee = None + self._taker_fee = None + self._fee_recipient_address = None + self._sender_address = None + self.discriminator = None + + self.maker_fee = maker_fee + self.taker_fee = taker_fee + self.fee_recipient_address = fee_recipient_address + self.sender_address = sender_address + + @property + def maker_fee(self): + """Gets the maker_fee of this RelayerApiOrderConfigResponseSchema. # noqa: E501 + + + :return: The maker_fee of this RelayerApiOrderConfigResponseSchema. # noqa: E501 + :rtype: str + """ + return self._maker_fee + + @maker_fee.setter + def maker_fee(self, maker_fee): + """Sets the maker_fee of this RelayerApiOrderConfigResponseSchema. + + + :param maker_fee: The maker_fee of this RelayerApiOrderConfigResponseSchema. # noqa: E501 + :type: str + """ + if maker_fee is None: + raise ValueError( + "Invalid value for `maker_fee`, must not be `None`" + ) # noqa: E501 + if maker_fee is not None and not re.search( + r"^\\d+$", maker_fee + ): # noqa: E501 + raise ValueError( + r"Invalid value for `maker_fee`, must be a follow pattern or equal to `/^\\d+$/`" + ) # noqa: E501 + + self._maker_fee = maker_fee + + @property + def taker_fee(self): + """Gets the taker_fee of this RelayerApiOrderConfigResponseSchema. # noqa: E501 + + + :return: The taker_fee of this RelayerApiOrderConfigResponseSchema. # noqa: E501 + :rtype: str + """ + return self._taker_fee + + @taker_fee.setter + def taker_fee(self, taker_fee): + """Sets the taker_fee of this RelayerApiOrderConfigResponseSchema. + + + :param taker_fee: The taker_fee of this RelayerApiOrderConfigResponseSchema. # noqa: E501 + :type: str + """ + if taker_fee is None: + raise ValueError( + "Invalid value for `taker_fee`, must not be `None`" + ) # noqa: E501 + if taker_fee is not None and not re.search( + r"^\\d+$", taker_fee + ): # noqa: E501 + raise ValueError( + r"Invalid value for `taker_fee`, must be a follow pattern or equal to `/^\\d+$/`" + ) # noqa: E501 + + self._taker_fee = taker_fee + + @property + def fee_recipient_address(self): + """Gets the fee_recipient_address of this RelayerApiOrderConfigResponseSchema. # noqa: E501 + + + :return: The fee_recipient_address of this RelayerApiOrderConfigResponseSchema. # noqa: E501 + :rtype: str + """ + return self._fee_recipient_address + + @fee_recipient_address.setter + def fee_recipient_address(self, fee_recipient_address): + """Sets the fee_recipient_address of this RelayerApiOrderConfigResponseSchema. + + + :param fee_recipient_address: The fee_recipient_address of this RelayerApiOrderConfigResponseSchema. # noqa: E501 + :type: str + """ + if fee_recipient_address is None: + raise ValueError( + "Invalid value for `fee_recipient_address`, must not be `None`" + ) # noqa: E501 + if fee_recipient_address is not None and not re.search( + r"^0x[0-9a-f]{40}$", fee_recipient_address + ): # noqa: E501 + raise ValueError( + r"Invalid value for `fee_recipient_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" + ) # noqa: E501 + + self._fee_recipient_address = fee_recipient_address + + @property + def sender_address(self): + """Gets the sender_address of this RelayerApiOrderConfigResponseSchema. # noqa: E501 + + + :return: The sender_address of this RelayerApiOrderConfigResponseSchema. # noqa: E501 + :rtype: str + """ + return self._sender_address + + @sender_address.setter + def sender_address(self, sender_address): + """Sets the sender_address of this RelayerApiOrderConfigResponseSchema. + + + :param sender_address: The sender_address of this RelayerApiOrderConfigResponseSchema. # noqa: E501 + :type: str + """ + if sender_address is None: + raise ValueError( + "Invalid value for `sender_address`, must not be `None`" + ) # noqa: E501 + if sender_address is not None and not re.search( + r"^0x[0-9a-f]{40}$", sender_address + ): # noqa: E501 + raise ValueError( + r"Invalid value for `sender_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" + ) # noqa: E501 + + self._sender_address = sender_address + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value, + ) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, RelayerApiOrderConfigResponseSchema): + return False + + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other diff --git a/python-packages/sra_client/sra_client/models/relayer_api_order_schema.py b/python-packages/sra_client/sra_client/models/relayer_api_order_schema.py new file mode 100644 index 000000000..5ee45cb30 --- /dev/null +++ b/python-packages/sra_client/sra_client/models/relayer_api_order_schema.py @@ -0,0 +1,134 @@ +# coding: utf-8 + + +import pprint +import re # noqa: F401 + +import six + + +class RelayerApiOrderSchema(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"order": "OrderSchema", "meta_data": "object"} + + attribute_map = {"order": "order", "meta_data": "metaData"} + + def __init__(self, order=None, meta_data=None): # noqa: E501 + """RelayerApiOrderSchema - a model defined in OpenAPI""" # noqa: E501 + + self._order = None + self._meta_data = None + self.discriminator = None + + self.order = order + self.meta_data = meta_data + + @property + def order(self): + """Gets the order of this RelayerApiOrderSchema. # noqa: E501 + + + :return: The order of this RelayerApiOrderSchema. # noqa: E501 + :rtype: OrderSchema + """ + return self._order + + @order.setter + def order(self, order): + """Sets the order of this RelayerApiOrderSchema. + + + :param order: The order of this RelayerApiOrderSchema. # noqa: E501 + :type: OrderSchema + """ + if order is None: + raise ValueError( + "Invalid value for `order`, must not be `None`" + ) # noqa: E501 + + self._order = order + + @property + def meta_data(self): + """Gets the meta_data of this RelayerApiOrderSchema. # noqa: E501 + + + :return: The meta_data of this RelayerApiOrderSchema. # noqa: E501 + :rtype: object + """ + return self._meta_data + + @meta_data.setter + def meta_data(self, meta_data): + """Sets the meta_data of this RelayerApiOrderSchema. + + + :param meta_data: The meta_data of this RelayerApiOrderSchema. # noqa: E501 + :type: object + """ + if meta_data is None: + raise ValueError( + "Invalid value for `meta_data`, must not be `None`" + ) # noqa: E501 + + self._meta_data = meta_data + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value, + ) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, RelayerApiOrderSchema): + return False + + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other diff --git a/python-packages/sra_client/sra_client/models/relayer_api_orderbook_response_schema.py b/python-packages/sra_client/sra_client/models/relayer_api_orderbook_response_schema.py new file mode 100644 index 000000000..364785b03 --- /dev/null +++ b/python-packages/sra_client/sra_client/models/relayer_api_orderbook_response_schema.py @@ -0,0 +1,137 @@ +# coding: utf-8 + + +import pprint +import re # noqa: F401 + +import six + + +class RelayerApiOrderbookResponseSchema(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "bids": "RelayerApiOrdersResponseSchema", + "asks": "RelayerApiOrdersResponseSchema", + } + + attribute_map = {"bids": "bids", "asks": "asks"} + + def __init__(self, bids=None, asks=None): # noqa: E501 + """RelayerApiOrderbookResponseSchema - a model defined in OpenAPI""" # noqa: E501 + + self._bids = None + self._asks = None + self.discriminator = None + + self.bids = bids + self.asks = asks + + @property + def bids(self): + """Gets the bids of this RelayerApiOrderbookResponseSchema. # noqa: E501 + + + :return: The bids of this RelayerApiOrderbookResponseSchema. # noqa: E501 + :rtype: RelayerApiOrdersResponseSchema + """ + return self._bids + + @bids.setter + def bids(self, bids): + """Sets the bids of this RelayerApiOrderbookResponseSchema. + + + :param bids: The bids of this RelayerApiOrderbookResponseSchema. # noqa: E501 + :type: RelayerApiOrdersResponseSchema + """ + if bids is None: + raise ValueError( + "Invalid value for `bids`, must not be `None`" + ) # noqa: E501 + + self._bids = bids + + @property + def asks(self): + """Gets the asks of this RelayerApiOrderbookResponseSchema. # noqa: E501 + + + :return: The asks of this RelayerApiOrderbookResponseSchema. # noqa: E501 + :rtype: RelayerApiOrdersResponseSchema + """ + return self._asks + + @asks.setter + def asks(self, asks): + """Sets the asks of this RelayerApiOrderbookResponseSchema. + + + :param asks: The asks of this RelayerApiOrderbookResponseSchema. # noqa: E501 + :type: RelayerApiOrdersResponseSchema + """ + if asks is None: + raise ValueError( + "Invalid value for `asks`, must not be `None`" + ) # noqa: E501 + + self._asks = asks + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value, + ) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, RelayerApiOrderbookResponseSchema): + return False + + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other diff --git a/python-packages/sra_client/sra_client/models/relayer_api_orders_channel_subscribe_payload_schema.py b/python-packages/sra_client/sra_client/models/relayer_api_orders_channel_subscribe_payload_schema.py new file mode 100644 index 000000000..f6bb758f9 --- /dev/null +++ b/python-packages/sra_client/sra_client/models/relayer_api_orders_channel_subscribe_payload_schema.py @@ -0,0 +1,344 @@ +# coding: utf-8 + + +import pprint +import re # noqa: F401 + +import six + + +class RelayerApiOrdersChannelSubscribePayloadSchema(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "maker_asset_proxy_id": "str", + "taker_asset_proxy_id": "str", + "network_id": "float", + "maker_asset_address": "str", + "taker_asset_address": "str", + "maker_asset_data": "str", + "taker_asset_data": "str", + "trader_asset_data": "str", + } + + attribute_map = { + "maker_asset_proxy_id": "makerAssetProxyId", + "taker_asset_proxy_id": "takerAssetProxyId", + "network_id": "networkId", + "maker_asset_address": "makerAssetAddress", + "taker_asset_address": "takerAssetAddress", + "maker_asset_data": "makerAssetData", + "taker_asset_data": "takerAssetData", + "trader_asset_data": "traderAssetData", + } + + def __init__( + self, + maker_asset_proxy_id=None, + taker_asset_proxy_id=None, + network_id=None, + maker_asset_address=None, + taker_asset_address=None, + maker_asset_data=None, + taker_asset_data=None, + trader_asset_data=None, + ): # noqa: E501 + """RelayerApiOrdersChannelSubscribePayloadSchema - a model defined in OpenAPI""" # noqa: E501 + + self._maker_asset_proxy_id = None + self._taker_asset_proxy_id = None + self._network_id = None + self._maker_asset_address = None + self._taker_asset_address = None + self._maker_asset_data = None + self._taker_asset_data = None + self._trader_asset_data = None + self.discriminator = None + + if maker_asset_proxy_id is not None: + self.maker_asset_proxy_id = maker_asset_proxy_id + if taker_asset_proxy_id is not None: + self.taker_asset_proxy_id = taker_asset_proxy_id + if network_id is not None: + self.network_id = network_id + if maker_asset_address is not None: + self.maker_asset_address = maker_asset_address + if taker_asset_address is not None: + self.taker_asset_address = taker_asset_address + if maker_asset_data is not None: + self.maker_asset_data = maker_asset_data + if taker_asset_data is not None: + self.taker_asset_data = taker_asset_data + if trader_asset_data is not None: + self.trader_asset_data = trader_asset_data + + @property + def maker_asset_proxy_id(self): + """Gets the maker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + + + :return: The maker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + :rtype: str + """ + return self._maker_asset_proxy_id + + @maker_asset_proxy_id.setter + def maker_asset_proxy_id(self, maker_asset_proxy_id): + """Sets the maker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. + + + :param maker_asset_proxy_id: The maker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + :type: str + """ + if maker_asset_proxy_id is not None and not re.search( + r"^0x(([0-9a-f][0-9a-f])+)?$", maker_asset_proxy_id + ): # noqa: E501 + raise ValueError( + r"Invalid value for `maker_asset_proxy_id`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" + ) # noqa: E501 + + self._maker_asset_proxy_id = maker_asset_proxy_id + + @property + def taker_asset_proxy_id(self): + """Gets the taker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + + + :return: The taker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + :rtype: str + """ + return self._taker_asset_proxy_id + + @taker_asset_proxy_id.setter + def taker_asset_proxy_id(self, taker_asset_proxy_id): + """Sets the taker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. + + + :param taker_asset_proxy_id: The taker_asset_proxy_id of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + :type: str + """ + if taker_asset_proxy_id is not None and not re.search( + r"^0x(([0-9a-f][0-9a-f])+)?$", taker_asset_proxy_id + ): # noqa: E501 + raise ValueError( + r"Invalid value for `taker_asset_proxy_id`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" + ) # noqa: E501 + + self._taker_asset_proxy_id = taker_asset_proxy_id + + @property + def network_id(self): + """Gets the network_id of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + + + :return: The network_id of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + :rtype: float + """ + return self._network_id + + @network_id.setter + def network_id(self, network_id): + """Sets the network_id of this RelayerApiOrdersChannelSubscribePayloadSchema. + + + :param network_id: The network_id of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + :type: float + """ + + self._network_id = network_id + + @property + def maker_asset_address(self): + """Gets the maker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + + + :return: The maker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + :rtype: str + """ + return self._maker_asset_address + + @maker_asset_address.setter + def maker_asset_address(self, maker_asset_address): + """Sets the maker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. + + + :param maker_asset_address: The maker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + :type: str + """ + if maker_asset_address is not None and not re.search( + r"^0x[0-9a-f]{40}$", maker_asset_address + ): # noqa: E501 + raise ValueError( + r"Invalid value for `maker_asset_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" + ) # noqa: E501 + + self._maker_asset_address = maker_asset_address + + @property + def taker_asset_address(self): + """Gets the taker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + + + :return: The taker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + :rtype: str + """ + return self._taker_asset_address + + @taker_asset_address.setter + def taker_asset_address(self, taker_asset_address): + """Sets the taker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. + + + :param taker_asset_address: The taker_asset_address of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + :type: str + """ + if taker_asset_address is not None and not re.search( + r"^0x[0-9a-f]{40}$", taker_asset_address + ): # noqa: E501 + raise ValueError( + r"Invalid value for `taker_asset_address`, must be a follow pattern or equal to `/^0x[0-9a-f]{40}$/`" + ) # noqa: E501 + + self._taker_asset_address = taker_asset_address + + @property + def maker_asset_data(self): + """Gets the maker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + + + :return: The maker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + :rtype: str + """ + return self._maker_asset_data + + @maker_asset_data.setter + def maker_asset_data(self, maker_asset_data): + """Sets the maker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. + + + :param maker_asset_data: The maker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + :type: str + """ + if maker_asset_data is not None and not re.search( + r"^0x(([0-9a-f][0-9a-f])+)?$", maker_asset_data + ): # noqa: E501 + raise ValueError( + r"Invalid value for `maker_asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" + ) # noqa: E501 + + self._maker_asset_data = maker_asset_data + + @property + def taker_asset_data(self): + """Gets the taker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + + + :return: The taker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + :rtype: str + """ + return self._taker_asset_data + + @taker_asset_data.setter + def taker_asset_data(self, taker_asset_data): + """Sets the taker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. + + + :param taker_asset_data: The taker_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + :type: str + """ + if taker_asset_data is not None and not re.search( + r"^0x(([0-9a-f][0-9a-f])+)?$", taker_asset_data + ): # noqa: E501 + raise ValueError( + r"Invalid value for `taker_asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" + ) # noqa: E501 + + self._taker_asset_data = taker_asset_data + + @property + def trader_asset_data(self): + """Gets the trader_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + + + :return: The trader_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + :rtype: str + """ + return self._trader_asset_data + + @trader_asset_data.setter + def trader_asset_data(self, trader_asset_data): + """Sets the trader_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. + + + :param trader_asset_data: The trader_asset_data of this RelayerApiOrdersChannelSubscribePayloadSchema. # noqa: E501 + :type: str + """ + if trader_asset_data is not None and not re.search( + r"^0x(([0-9a-f][0-9a-f])+)?$", trader_asset_data + ): # noqa: E501 + raise ValueError( + r"Invalid value for `trader_asset_data`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" + ) # noqa: E501 + + self._trader_asset_data = trader_asset_data + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value, + ) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance( + other, RelayerApiOrdersChannelSubscribePayloadSchema + ): + return False + + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other diff --git a/python-packages/sra_client/sra_client/models/relayer_api_orders_channel_subscribe_schema.py b/python-packages/sra_client/sra_client/models/relayer_api_orders_channel_subscribe_schema.py new file mode 100644 index 000000000..2f72d5307 --- /dev/null +++ b/python-packages/sra_client/sra_client/models/relayer_api_orders_channel_subscribe_schema.py @@ -0,0 +1,211 @@ +# coding: utf-8 + + +import pprint +import re # noqa: F401 + +import six + + +class RelayerApiOrdersChannelSubscribeSchema(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "type": "str", + "channel": "str", + "request_id": "str", + "payload": "RelayerApiOrdersChannelSubscribePayloadSchema", + } + + attribute_map = { + "type": "type", + "channel": "channel", + "request_id": "requestId", + "payload": "payload", + } + + def __init__( + self, type=None, channel=None, request_id=None, payload=None + ): # noqa: E501 + """RelayerApiOrdersChannelSubscribeSchema - a model defined in OpenAPI""" # noqa: E501 + + self._type = None + self._channel = None + self._request_id = None + self._payload = None + self.discriminator = None + + self.type = type + self.channel = channel + self.request_id = request_id + if payload is not None: + self.payload = payload + + @property + def type(self): + """Gets the type of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 + + + :return: The type of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 + :rtype: str + """ + return self._type + + @type.setter + def type(self, type): + """Sets the type of this RelayerApiOrdersChannelSubscribeSchema. + + + :param type: The type of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 + :type: str + """ + if type is None: + raise ValueError( + "Invalid value for `type`, must not be `None`" + ) # noqa: E501 + allowed_values = ["subscribe"] # noqa: E501 + if type not in allowed_values: + raise ValueError( + "Invalid value for `type` ({0}), must be one of {1}".format( # noqa: E501 + type, allowed_values + ) + ) + + self._type = type + + @property + def channel(self): + """Gets the channel of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 + + + :return: The channel of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 + :rtype: str + """ + return self._channel + + @channel.setter + def channel(self, channel): + """Sets the channel of this RelayerApiOrdersChannelSubscribeSchema. + + + :param channel: The channel of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 + :type: str + """ + if channel is None: + raise ValueError( + "Invalid value for `channel`, must not be `None`" + ) # noqa: E501 + allowed_values = ["orders"] # noqa: E501 + if channel not in allowed_values: + raise ValueError( + "Invalid value for `channel` ({0}), must be one of {1}".format( # noqa: E501 + channel, allowed_values + ) + ) + + self._channel = channel + + @property + def request_id(self): + """Gets the request_id of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 + + + :return: The request_id of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 + :rtype: str + """ + return self._request_id + + @request_id.setter + def request_id(self, request_id): + """Sets the request_id of this RelayerApiOrdersChannelSubscribeSchema. + + + :param request_id: The request_id of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 + :type: str + """ + if request_id is None: + raise ValueError( + "Invalid value for `request_id`, must not be `None`" + ) # noqa: E501 + + self._request_id = request_id + + @property + def payload(self): + """Gets the payload of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 + + + :return: The payload of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 + :rtype: RelayerApiOrdersChannelSubscribePayloadSchema + """ + return self._payload + + @payload.setter + def payload(self, payload): + """Sets the payload of this RelayerApiOrdersChannelSubscribeSchema. + + + :param payload: The payload of this RelayerApiOrdersChannelSubscribeSchema. # noqa: E501 + :type: RelayerApiOrdersChannelSubscribePayloadSchema + """ + + self._payload = payload + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value, + ) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, RelayerApiOrdersChannelSubscribeSchema): + return False + + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other diff --git a/python-packages/sra_client/sra_client/models/relayer_api_orders_channel_update_schema.py b/python-packages/sra_client/sra_client/models/relayer_api_orders_channel_update_schema.py new file mode 100644 index 000000000..68aa2fddb --- /dev/null +++ b/python-packages/sra_client/sra_client/models/relayer_api_orders_channel_update_schema.py @@ -0,0 +1,211 @@ +# coding: utf-8 + + +import pprint +import re # noqa: F401 + +import six + + +class RelayerApiOrdersChannelUpdateSchema(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "type": "str", + "channel": "str", + "request_id": "str", + "payload": "list[RelayerApiOrderSchema]", + } + + attribute_map = { + "type": "type", + "channel": "channel", + "request_id": "requestId", + "payload": "payload", + } + + def __init__( + self, type=None, channel=None, request_id=None, payload=None + ): # noqa: E501 + """RelayerApiOrdersChannelUpdateSchema - a model defined in OpenAPI""" # noqa: E501 + + self._type = None + self._channel = None + self._request_id = None + self._payload = None + self.discriminator = None + + self.type = type + self.channel = channel + self.request_id = request_id + if payload is not None: + self.payload = payload + + @property + def type(self): + """Gets the type of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501 + + + :return: The type of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501 + :rtype: str + """ + return self._type + + @type.setter + def type(self, type): + """Sets the type of this RelayerApiOrdersChannelUpdateSchema. + + + :param type: The type of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501 + :type: str + """ + if type is None: + raise ValueError( + "Invalid value for `type`, must not be `None`" + ) # noqa: E501 + allowed_values = ["update"] # noqa: E501 + if type not in allowed_values: + raise ValueError( + "Invalid value for `type` ({0}), must be one of {1}".format( # noqa: E501 + type, allowed_values + ) + ) + + self._type = type + + @property + def channel(self): + """Gets the channel of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501 + + + :return: The channel of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501 + :rtype: str + """ + return self._channel + + @channel.setter + def channel(self, channel): + """Sets the channel of this RelayerApiOrdersChannelUpdateSchema. + + + :param channel: The channel of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501 + :type: str + """ + if channel is None: + raise ValueError( + "Invalid value for `channel`, must not be `None`" + ) # noqa: E501 + allowed_values = ["orders"] # noqa: E501 + if channel not in allowed_values: + raise ValueError( + "Invalid value for `channel` ({0}), must be one of {1}".format( # noqa: E501 + channel, allowed_values + ) + ) + + self._channel = channel + + @property + def request_id(self): + """Gets the request_id of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501 + + + :return: The request_id of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501 + :rtype: str + """ + return self._request_id + + @request_id.setter + def request_id(self, request_id): + """Sets the request_id of this RelayerApiOrdersChannelUpdateSchema. + + + :param request_id: The request_id of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501 + :type: str + """ + if request_id is None: + raise ValueError( + "Invalid value for `request_id`, must not be `None`" + ) # noqa: E501 + + self._request_id = request_id + + @property + def payload(self): + """Gets the payload of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501 + + + :return: The payload of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501 + :rtype: list[RelayerApiOrderSchema] + """ + return self._payload + + @payload.setter + def payload(self, payload): + """Sets the payload of this RelayerApiOrdersChannelUpdateSchema. + + + :param payload: The payload of this RelayerApiOrdersChannelUpdateSchema. # noqa: E501 + :type: list[RelayerApiOrderSchema] + """ + + self._payload = payload + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value, + ) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, RelayerApiOrdersChannelUpdateSchema): + return False + + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other diff --git a/python-packages/sra_client/sra_client/models/relayer_api_orders_response_schema.py b/python-packages/sra_client/sra_client/models/relayer_api_orders_response_schema.py new file mode 100644 index 000000000..d72b74cb7 --- /dev/null +++ b/python-packages/sra_client/sra_client/models/relayer_api_orders_response_schema.py @@ -0,0 +1,107 @@ +# coding: utf-8 + + +import pprint +import re # noqa: F401 + +import six + + +class RelayerApiOrdersResponseSchema(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"records": "list[RelayerApiOrderSchema]"} + + attribute_map = {"records": "records"} + + def __init__(self, records=None): # noqa: E501 + """RelayerApiOrdersResponseSchema - a model defined in OpenAPI""" # noqa: E501 + + self._records = None + self.discriminator = None + + self.records = records + + @property + def records(self): + """Gets the records of this RelayerApiOrdersResponseSchema. # noqa: E501 + + + :return: The records of this RelayerApiOrdersResponseSchema. # noqa: E501 + :rtype: list[RelayerApiOrderSchema] + """ + return self._records + + @records.setter + def records(self, records): + """Sets the records of this RelayerApiOrdersResponseSchema. + + + :param records: The records of this RelayerApiOrdersResponseSchema. # noqa: E501 + :type: list[RelayerApiOrderSchema] + """ + if records is None: + raise ValueError( + "Invalid value for `records`, must not be `None`" + ) # noqa: E501 + + self._records = records + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value, + ) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, RelayerApiOrdersResponseSchema): + return False + + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other diff --git a/python-packages/sra_client/sra_client/models/signed_order_schema.py b/python-packages/sra_client/sra_client/models/signed_order_schema.py new file mode 100644 index 000000000..8c71bff89 --- /dev/null +++ b/python-packages/sra_client/sra_client/models/signed_order_schema.py @@ -0,0 +1,113 @@ +# coding: utf-8 + + +import pprint +import re # noqa: F401 + +import six + + +class SignedOrderSchema(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"signature": "str"} + + attribute_map = {"signature": "signature"} + + def __init__(self, signature=None): # noqa: E501 + """SignedOrderSchema - a model defined in OpenAPI""" # noqa: E501 + + self._signature = None + self.discriminator = None + + self.signature = signature + + @property + def signature(self): + """Gets the signature of this SignedOrderSchema. # noqa: E501 + + + :return: The signature of this SignedOrderSchema. # noqa: E501 + :rtype: str + """ + return self._signature + + @signature.setter + def signature(self, signature): + """Sets the signature of this SignedOrderSchema. + + + :param signature: The signature of this SignedOrderSchema. # noqa: E501 + :type: str + """ + if signature is None: + raise ValueError( + "Invalid value for `signature`, must not be `None`" + ) # noqa: E501 + if signature is not None and not re.search( + r"^0x(([0-9a-f][0-9a-f])+)?$", signature + ): # noqa: E501 + raise ValueError( + r"Invalid value for `signature`, must be a follow pattern or equal to `/^0x(([0-9a-f][0-9a-f])+)?$/`" + ) # noqa: E501 + + self._signature = signature + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value, + ) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, SignedOrderSchema): + return False + + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other diff --git a/python-packages/sra_client/sra_client/rest.py b/python-packages/sra_client/sra_client/rest.py new file mode 100644 index 000000000..b38cabd70 --- /dev/null +++ b/python-packages/sra_client/sra_client/rest.py @@ -0,0 +1,421 @@ +# coding: utf-8 + + +from __future__ import absolute_import + +import io +import json +import logging +import re +import ssl + +import certifi + +# python 2 and python 3 compatibility library +import six +from six.moves.urllib.parse import urlencode + +try: + import urllib3 +except ImportError: + raise ImportError("OpenAPI Python client requires urllib3.") + + +logger = logging.getLogger(__name__) + + +class RESTResponse(io.IOBase): + def __init__(self, resp): + self.urllib3_response = resp + self.status = resp.status + self.reason = resp.reason + self.data = resp.data + + def getheaders(self): + """Returns a dictionary of the response headers.""" + return self.urllib3_response.getheaders() + + def getheader(self, name, default=None): + """Returns a given response header.""" + return self.urllib3_response.getheader(name, default) + + +class RESTClientObject(object): + def __init__(self, configuration, pools_size=4, maxsize=None): + # urllib3.PoolManager will pass all kw parameters to connectionpool + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 + # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 + # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 + + # cert_reqs + if configuration.verify_ssl: + cert_reqs = ssl.CERT_REQUIRED + else: + cert_reqs = ssl.CERT_NONE + + # ca_certs + if configuration.ssl_ca_cert: + ca_certs = configuration.ssl_ca_cert + else: + # if not set certificate file, use Mozilla's root certificates. + ca_certs = certifi.where() + + addition_pool_args = {} + if configuration.assert_hostname is not None: + addition_pool_args[ + "assert_hostname" + ] = configuration.assert_hostname # noqa: E501 + + if maxsize is None: + if configuration.connection_pool_maxsize is not None: + maxsize = configuration.connection_pool_maxsize + else: + maxsize = 4 + + # https pool manager + if configuration.proxy: + self.pool_manager = urllib3.ProxyManager( + num_pools=pools_size, + maxsize=maxsize, + cert_reqs=cert_reqs, + ca_certs=ca_certs, + cert_file=configuration.cert_file, + key_file=configuration.key_file, + proxy_url=configuration.proxy, + **addition_pool_args + ) + else: + self.pool_manager = urllib3.PoolManager( + num_pools=pools_size, + maxsize=maxsize, + cert_reqs=cert_reqs, + ca_certs=ca_certs, + cert_file=configuration.cert_file, + key_file=configuration.key_file, + **addition_pool_args + ) + + def request( + self, + method, + url, + query_params=None, + headers=None, + body=None, + post_params=None, + _preload_content=True, + _request_timeout=None, + ): + """Perform requests. + + :param method: http request method + :param url: http request url + :param query_params: query parameters in the url + :param headers: http request headers + :param body: request json body, for `application/json` + :param post_params: request post parameters, + `application/x-www-form-urlencoded` + and `multipart/form-data` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + """ + method = method.upper() + assert method in [ + "GET", + "HEAD", + "DELETE", + "POST", + "PUT", + "PATCH", + "OPTIONS", + ] + + if post_params and body: + raise ValueError( + "body parameter cannot be used with post_params parameter." + ) + + post_params = post_params or {} + headers = headers or {} + + timeout = None + if _request_timeout: + if isinstance( + _request_timeout, (int,) if six.PY3 else (int, long) + ): # noqa: E501,F821 + timeout = urllib3.Timeout(total=_request_timeout) + elif ( + isinstance(_request_timeout, tuple) + and len(_request_timeout) == 2 + ): + timeout = urllib3.Timeout( + connect=_request_timeout[0], read=_request_timeout[1] + ) + + if "Content-Type" not in headers: + headers["Content-Type"] = "application/json" + + try: + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` + if method in ["POST", "PUT", "PATCH", "OPTIONS", "DELETE"]: + if query_params: + url += "?" + urlencode(query_params) + if re.search("json", headers["Content-Type"], re.IGNORECASE): + request_body = None + if body is not None: + request_body = json.dumps(body) + r = self.pool_manager.request( + method, + url, + body=request_body, + preload_content=_preload_content, + timeout=timeout, + headers=headers, + ) + elif ( + headers["Content-Type"] + == "application/x-www-form-urlencoded" + ): # noqa: E501 + r = self.pool_manager.request( + method, + url, + fields=post_params, + encode_multipart=False, + preload_content=_preload_content, + timeout=timeout, + headers=headers, + ) + elif headers["Content-Type"] == "multipart/form-data": + # must del headers['Content-Type'], or the correct + # Content-Type which generated by urllib3 will be + # overwritten. + del headers["Content-Type"] + r = self.pool_manager.request( + method, + url, + fields=post_params, + encode_multipart=True, + preload_content=_preload_content, + timeout=timeout, + headers=headers, + ) + # Pass a `string` parameter directly in the body to support + # other content types than Json when `body` argument is + # provided in serialized form + elif isinstance(body, str): + request_body = body + r = self.pool_manager.request( + method, + url, + body=request_body, + preload_content=_preload_content, + timeout=timeout, + headers=headers, + ) + else: + # Cannot generate the request from given parameters + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" + raise ApiException(status=0, reason=msg) + # For `GET`, `HEAD` + else: + r = self.pool_manager.request( + method, + url, + fields=query_params, + preload_content=_preload_content, + timeout=timeout, + headers=headers, + ) + except urllib3.exceptions.SSLError as e: + msg = "{0}\n{1}".format(type(e).__name__, str(e)) + raise ApiException(status=0, reason=msg) + + if _preload_content: + r = RESTResponse(r) + + # In the python 3, the response.data is bytes. + # we need to decode it to string. + if six.PY3: + r.data = r.data.decode("utf8") + + # log response body + logger.debug("response body: %s", r.data) + + if not 200 <= r.status <= 299: + raise ApiException(http_resp=r) + + return r + + def GET( + self, + url, + headers=None, + query_params=None, + _preload_content=True, + _request_timeout=None, + ): + return self.request( + "GET", + url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params, + ) + + def HEAD( + self, + url, + headers=None, + query_params=None, + _preload_content=True, + _request_timeout=None, + ): + return self.request( + "HEAD", + url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params, + ) + + def OPTIONS( + self, + url, + headers=None, + query_params=None, + post_params=None, + body=None, + _preload_content=True, + _request_timeout=None, + ): + return self.request( + "OPTIONS", + url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) + + def DELETE( + self, + url, + headers=None, + query_params=None, + body=None, + _preload_content=True, + _request_timeout=None, + ): + return self.request( + "DELETE", + url, + headers=headers, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) + + def POST( + self, + url, + headers=None, + query_params=None, + post_params=None, + body=None, + _preload_content=True, + _request_timeout=None, + ): + return self.request( + "POST", + url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) + + def PUT( + self, + url, + headers=None, + query_params=None, + post_params=None, + body=None, + _preload_content=True, + _request_timeout=None, + ): + return self.request( + "PUT", + url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) + + def PATCH( + self, + url, + headers=None, + query_params=None, + post_params=None, + body=None, + _preload_content=True, + _request_timeout=None, + ): + return self.request( + "PATCH", + url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) + + +class ApiException(Exception): + def __init__(self, status=None, reason=None, http_resp=None): + if http_resp: + self.status = http_resp.status + self.reason = http_resp.reason + self.body = http_resp.data + self.headers = http_resp.getheaders() + else: + self.status = status + self.reason = reason + self.body = None + self.headers = None + + def __str__(self): + """Custom error messages for exception""" + error_message = "({0})\n" "Reason: {1}\n".format( + self.status, self.reason + ) + if self.headers: + error_message += "HTTP response headers: {0}\n".format( + self.headers + ) + + if self.body: + error_message += "HTTP response body: {0}\n".format(self.body) + + return error_message diff --git a/python-packages/sra_client/test-requirements.txt b/python-packages/sra_client/test-requirements.txt new file mode 100644 index 000000000..2702246c0 --- /dev/null +++ b/python-packages/sra_client/test-requirements.txt @@ -0,0 +1,5 @@ +coverage>=4.0.3 +nose>=1.3.7 +pluggy>=0.3.1 +py>=1.4.31 +randomize>=0.13 diff --git a/python-packages/sra_client/test/__init__.py b/python-packages/sra_client/test/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/python-packages/sra_client/test/__init__.py diff --git a/python-packages/sra_client/test/test_default_api.py b/python-packages/sra_client/test/test_default_api.py new file mode 100644 index 000000000..d23c6173f --- /dev/null +++ b/python-packages/sra_client/test/test_default_api.py @@ -0,0 +1,35 @@ +# coding: utf-8 + + +from __future__ import absolute_import + +import unittest + +import sra_client +from sra_client.api.default_api import DefaultApi # noqa: E501 +from sra_client.models.relayer_api_asset_data_pairs_response_schema import ( + RelayerApiAssetDataPairsResponseSchema +) +from sra_client.rest import ApiException + + +class TestDefaultApi(unittest.TestCase): + """DefaultApi unit test stubs""" + + def setUp(self): + self.api = sra_client.api.default_api.DefaultApi() # noqa: E501 + + def tearDown(self): + pass + + def test_get_asset_pairs(self): + """Test case for get_asset_pairs + + """ + expected = RelayerApiAssetDataPairsResponseSchema([]) + actual = self.api.get_asset_pairs() + self.assertEqual(actual, expected) + + +if __name__ == "__main__": + unittest.main() diff --git a/python-packages/sra_client/tox.ini b/python-packages/sra_client/tox.ini new file mode 100644 index 000000000..69d59f4ff --- /dev/null +++ b/python-packages/sra_client/tox.ini @@ -0,0 +1,24 @@ +[tox] +envlist = py27, py3 + +[testenv] +deps=-r{toxinidir}/requirements.txt + -r{toxinidir}/test-requirements.txt + +commands= + nosetests \ + [] + +[testenv:run_tests_against_test_deployment] +commands = + # install dependencies from real PyPI + pip install mypy_extensions pytest + # install package-under-test from test PyPI + pip install --index-url https://test.pypi.org/legacy/ 0x-sra-client + pytest test + +[testenv:run_tests_against_deployment] +deps=pytest +commands = + pip install 0x-sra-client + pytest test |