From bdabb2d0d685bf361c35717cab95ebdcf9468a3f Mon Sep 17 00:00:00 2001 From: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> Date: Tue, 24 Sep 2024 19:58:45 -0400 Subject: [PATCH 01/40] [chore] Add SECURITY.md (#8) --- SECURITY.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 SECURITY.md diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..35c5d7e --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,7 @@ +# Security Policy + +The Coinbase team takes security seriously. Please do not file a public ticket discussing a potential vulnerability. + +Please report your findings through our [HackerOne][1] program. + +[1]: https://hackerone.com/coinbase From 6d18e539b651f6cf15e2b5e2853280d6aea869a0 Mon Sep 17 00:00:00 2001 From: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> Date: Wed, 25 Sep 2024 11:09:41 -0400 Subject: [PATCH 02/40] [chore] Import/Export WalletData (#9) --- Makefile | 2 +- cdp/__init__.py | 2 ++ cdp/wallet.py | 47 +++++++++++++++++++++++++++-- cdp/wallet_data.py | 73 ++++++++++++++++++++++++++++++++++++++++++++++ docs/cdp.rst | 8 +++++ 5 files changed, 128 insertions(+), 4 deletions(-) create mode 100644 cdp/wallet_data.py diff --git a/Makefile b/Makefile index bafa3ab..f44df2e 100644 --- a/Makefile +++ b/Makefile @@ -28,4 +28,4 @@ install-deps: .PHONY: docs docs: - sphinx-apidoc -o docs/ ./cdp/ + sphinx-apidoc -f -o docs/ ./cdp/ diff --git a/cdp/__init__.py b/cdp/__init__.py index 59e9448..b2ef04a 100644 --- a/cdp/__init__.py +++ b/cdp/__init__.py @@ -10,11 +10,13 @@ from cdp.transaction import Transaction from cdp.transfer import Transfer from cdp.wallet import Wallet +from cdp.wallet_data import WalletData __all__ = [ "__version__", "Cdp", "Wallet", + "WalletData", "Asset", "Transfer", "Address", diff --git a/cdp/wallet.py b/cdp/wallet.py index e5e81a8..41c2414 100644 --- a/cdp/wallet.py +++ b/cdp/wallet.py @@ -28,6 +28,7 @@ from cdp.faucet_transaction import FaucetTransaction from cdp.trade import Trade from cdp.wallet_address import WalletAddress +from cdp.wallet_data import WalletData class Wallet: @@ -176,8 +177,8 @@ def reload(self) -> None: self._model = model return - @staticmethod - def fetch(wallet_id: str) -> "Wallet": + @classmethod + def fetch(cls, wallet_id: str) -> "Wallet": """Fetch a wallet by its ID. Args: @@ -192,7 +193,7 @@ def fetch(wallet_id: str) -> "Wallet": """ model = Cdp.api_clients.wallets.get_wallet(wallet_id) - return Wallet(model, "") + return cls(model, "") @classmethod def list(cls) -> Iterator["Wallet"]: @@ -218,6 +219,31 @@ def list(cls) -> Iterator["Wallet"]: page = response.next_page + @classmethod + def import_data(cls, data: WalletData) -> "Wallet": + """Import a wallet from previously exported wallet data. + + Args: + data (WalletData): The wallet data to import. + + Returns: + Wallet: The imported wallet. + + Raises: + Exception: If there's an error getting the wallet. + + """ + if not isinstance(data, WalletData): + raise ValueError("Data must be a WalletData instance") + + model = Cdp.api_clients.wallets.get_wallet(data.wallet_id) + + wallet = cls(model, data.seed) + + wallet._set_addresses() + + return wallet + def create_address(self) -> "WalletAddress": """Create a new address for the wallet. @@ -372,6 +398,21 @@ def default_address(self) -> WalletAddress | None: else None ) + def export_data(self) -> WalletData: + """Export the wallet's data. + + Returns: + WalletData: The wallet's data. + + Raises: + ValueError: If the wallet does not have a seed loaded. + + """ + if self._master is None or self._seed is None: + raise ValueError("Wallet does not have seed loaded") + + return WalletData(self.id, self._seed) + def save_seed(self, file_path: str, encrypt: bool | None = False) -> None: """Save the wallet seed to a file. diff --git a/cdp/wallet_data.py b/cdp/wallet_data.py new file mode 100644 index 0000000..dc4816e --- /dev/null +++ b/cdp/wallet_data.py @@ -0,0 +1,73 @@ +class WalletData: + """A class representing wallet data required to recreate a wallet.""" + + def __init__(self, wallet_id: str, seed: str) -> None: + """Initialize the WalletData class. + + Args: + wallet_id (str): The ID of the wallet. + seed (str): The seed of the wallet. + + """ + self._wallet_id = wallet_id + self._seed = seed + + @property + def wallet_id(self) -> str: + """Get the ID of the wallet. + + Returns: + str: The ID of the wallet. + + """ + return self._wallet_id + + @property + def seed(self) -> str: + """Get the seed of the wallet. + + Returns: + str: The seed of the wallet. + + """ + return self._seed + + def to_dict(self) -> dict[str, str]: + """Convert the wallet data to a dictionary. + + Returns: + dict[str, str]: The dictionary representation of the wallet data. + + """ + return {"wallet_id": self.wallet_id, "seed": self.seed} + + @classmethod + def from_dict(cls, data: dict[str, str]) -> "WalletData": + """Create a WalletData class instance from the given dictionary. + + Args: + data (dict[str, str]): The data to create the WalletData object from. + + Returns: + WalletData: The wallet data. + + """ + return cls(data["wallet_id"], data["seed"]) + + def __str__(self) -> str: + """Return a string representation of the WalletData object. + + Returns: + str: A string representation of the wallet data. + + """ + return f"WalletData: (wallet_id: {self.wallet_id}, seed: {self.seed})" + + def __repr__(self) -> str: + """Return a string representation of the WalletData object. + + Returns: + str: A string representation of the wallet data. + + """ + return str(self) diff --git a/docs/cdp.rst b/docs/cdp.rst index 9812bca..e0c4e6b 100644 --- a/docs/cdp.rst +++ b/docs/cdp.rst @@ -132,6 +132,14 @@ cdp.wallet\_address module :undoc-members: :show-inheritance: +cdp.wallet\_data module +----------------------- + +.. automodule:: cdp.wallet_data + :members: + :undoc-members: + :show-inheritance: + Module contents --------------- From e17b200dc1089caacb60fe7ed6986b2b15ab304d Mon Sep 17 00:00:00 2001 From: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> Date: Wed, 25 Sep 2024 13:01:09 -0400 Subject: [PATCH 03/40] [chore] Add status Property to Trade (#10) --- cdp/trade.py | 10 ++++++++++ tests/test_trade.py | 4 ++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/cdp/trade.py b/cdp/trade.py index 1880f2f..57d78f7 100644 --- a/cdp/trade.py +++ b/cdp/trade.py @@ -227,6 +227,16 @@ def to_amount(self) -> Decimal: """ return Decimal(self._model.to_amount) / Decimal(10) ** self._model.to_asset.decimals + @property + def status(self) -> str: + """Get the status. + + Returns: + str: The status. + + """ + return self.transaction.status + @property def transaction(self) -> Transaction: """Get the trade transaction.""" diff --git a/tests/test_trade.py b/tests/test_trade.py index f30259d..5bf23e0 100644 --- a/tests/test_trade.py +++ b/tests/test_trade.py @@ -193,7 +193,7 @@ def test_broadcast_trade(mock_api_clients, trade_factory): broadcast_trade_request=ANY, ) assert isinstance(response, Trade) - assert response.transaction.status.value == "broadcast" + assert response.status.value == "broadcast" broadcast_trade_request = mock_broadcast.call_args[1]["broadcast_trade_request"] assert broadcast_trade_request.signed_payload == trade.transaction.signature assert ( @@ -224,7 +224,7 @@ def test_wait_for_trade(mock_time, mock_sleep, mock_api_clients, trade_factory): result = pending_trade.wait(interval_seconds=0.2, timeout_seconds=1) - assert result.transaction.status.value == "complete" + assert result.status.value == "complete" mock_get_trade.assert_called_with( wallet_id=pending_trade.wallet_id, address_id=pending_trade.address_id, From 105bc8cd1ff30fd4c9dcaca6312c99f7179e41a7 Mon Sep 17 00:00:00 2001 From: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> Date: Wed, 25 Sep 2024 14:27:38 -0400 Subject: [PATCH 04/40] [v0.0.3] Release (#11) * [v0.0.3] Release * add changelog --- CHANGELOG.md | 9 +++++++++ README.md | 3 +++ cdp/__version__.py | 2 +- docs/conf.py | 2 +- pyproject.toml | 2 +- 5 files changed, 15 insertions(+), 3 deletions(-) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..8b4d99d --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,9 @@ +# CDP Python SDK Changelog + +## Unreleased + +## [0.0.3] - 2024-09-25 + +### Added + +- Initial release of the CDP Python SDK. diff --git a/README.md b/README.md index 57a6d95..ca22e3d 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ one asset into another. ## Documentation - [CDP API Documentation](https://docs.cdp.coinbase.com/platform-apis/docs/welcome) +- [CDP SDK Python Documentation](https://coinbase.github.io/cdp-sdk-python/) ## Requirements @@ -21,9 +22,11 @@ Before using the SDK, ensure that you have the correct version of Python install ```bash python --version +pip --version ``` If you need to upgrade your Python version, you can download and install the latest version of Python from the [official Python website](https://www.python.org/downloads/). +For `pip`, refer to the [official pip documentation](https://pip.pypa.io/en/stable/installation/) for installation instructions. ## Installation diff --git a/cdp/__version__.py b/cdp/__version__.py index 3b93d0b..27fdca4 100644 --- a/cdp/__version__.py +++ b/cdp/__version__.py @@ -1 +1 @@ -__version__ = "0.0.2" +__version__ = "0.0.3" diff --git a/docs/conf.py b/docs/conf.py index 799f6dc..e9c96db 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -14,7 +14,7 @@ project = 'CDP SDK' author = 'Coinbase Developer Platform' -release = '0.0.2' +release = '0.0.3' # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration diff --git a/pyproject.toml b/pyproject.toml index 3d16c0d..782d916 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "cdp-sdk" -version = "0.0.2" +version = "0.0.3" description = "CDP Python SDK" readme = "README.md" authors = [{name = "John Peterson", email = "john.peterson@coinbase.com"}] From d0fc1c3f9284f95d1cd730ba221c9152055db847 Mon Sep 17 00:00:00 2001 From: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> Date: Mon, 30 Sep 2024 11:43:22 -0400 Subject: [PATCH 05/40] [PSDK-500] Contract Invocation Support (#13) * [PSDK-500] Contract Invocation Support * fix typo --- CHANGELOG.md | 4 + cdp/__init__.py | 2 + cdp/api_clients.py | 18 ++ cdp/contract_invocation.py | 350 ++++++++++++++++++++++++++++++ cdp/wallet.py | 37 ++++ cdp/wallet_address.py | 50 +++++ docs/cdp.rst | 8 + tests/test_contract_invocation.py | 265 ++++++++++++++++++++++ tests/test_wallet.py | 55 +++++ tests/test_wallet_address.py | 173 +++++++++++++++ 10 files changed, 962 insertions(+) create mode 100644 cdp/contract_invocation.py create mode 100644 tests/test_contract_invocation.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b4d99d..2723d63 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +### Added + +- Contract invocation support. + ## [0.0.3] - 2024-09-25 ### Added diff --git a/cdp/__init__.py b/cdp/__init__.py index b2ef04a..df12ecb 100644 --- a/cdp/__init__.py +++ b/cdp/__init__.py @@ -4,6 +4,7 @@ from cdp.balance import Balance from cdp.balance_map import BalanceMap from cdp.cdp import Cdp +from cdp.contract_invocation import ContractInvocation from cdp.faucet_transaction import FaucetTransaction from cdp.sponsored_send import SponsoredSend from cdp.trade import Trade @@ -15,6 +16,7 @@ __all__ = [ "__version__", "Cdp", + "ContractInvocation", "Wallet", "WalletData", "Asset", diff --git a/cdp/api_clients.py b/cdp/api_clients.py index c20f0eb..a3615ad 100644 --- a/cdp/api_clients.py +++ b/cdp/api_clients.py @@ -1,6 +1,7 @@ from cdp.cdp_api_client import CdpApiClient from cdp.client.api.addresses_api import AddressesApi from cdp.client.api.assets_api import AssetsApi +from cdp.client.api.contract_invocations_api import ContractInvocationsApi from cdp.client.api.external_addresses_api import ExternalAddressesApi from cdp.client.api.networks_api import NetworksApi from cdp.client.api.trades_api import TradesApi @@ -23,6 +24,7 @@ class ApiClients: _networks (Optional[NetworksApi]): The NetworksApi client instance. _assets (Optional[AssetsApi]): The AssetsApi client instance. _trades (Optional[TradesApi]): The TradesApi client instance. + _contract_invocations (Optional[ContractInvocationsApi]): The ContractInvocationsApi client instance. """ @@ -41,6 +43,7 @@ def __init__(self, cdp_client: CdpApiClient) -> None: self._networks: NetworksApi | None = None self._assets: AssetsApi | None = None self._trades: TradesApi | None = None + self._contract_invocations: ContractInvocationsApi | None = None @property def wallets(self) -> WalletsApi: @@ -146,3 +149,18 @@ def trades(self) -> TradesApi: if self._trades is None: self._trades = TradesApi(api_client=self._cdp_client) return self._trades + + @property + def contract_invocations(self) -> ContractInvocationsApi: + """Get the ContractInvocationsApi client instance. + + Returns: + ContractInvocationsApi: The ContractInvocationsApi client instance. + + Note: + This property lazily initializes the ContractInvocationsApi client on first access. + + """ + if self._contract_invocations is None: + self._contract_invocations = ContractInvocationsApi(api_client=self._cdp_client) + return self._contract_invocations diff --git a/cdp/contract_invocation.py b/cdp/contract_invocation.py new file mode 100644 index 0000000..000d3af --- /dev/null +++ b/cdp/contract_invocation.py @@ -0,0 +1,350 @@ +import json +import time +from collections.abc import Iterator +from decimal import Decimal +from typing import Any + +from eth_account.signers.local import LocalAccount + +from cdp.asset import Asset +from cdp.cdp import Cdp +from cdp.client.models.broadcast_contract_invocation_request import ( + BroadcastContractInvocationRequest, +) +from cdp.client.models.contract_invocation import ContractInvocation as ContractInvocationModel +from cdp.client.models.create_contract_invocation_request import CreateContractInvocationRequest +from cdp.errors import TransactionNotSignedError +from cdp.transaction import Transaction + + +class ContractInvocation: + """A class representing a contract invocation.""" + + def __init__(self, model: ContractInvocationModel) -> None: + """Initialize the ContractInvocation class. + + Args: + model (ContractInvocationModel): The model representing the contract invocation. + + """ + self._model = model + self._transaction = None + + @property + def contract_invocation_id(self) -> str: + """Get the contract invocation ID. + + Returns: + str: The contract invocation ID. + + """ + return self._model.contract_invocation_id + + @property + def wallet_id(self) -> str: + """Get the wallet ID of the contract invocation. + + Returns: + str: The wallet ID. + + """ + return self._model.wallet_id + + @property + def address_id(self) -> str: + """Get the address ID of the contract invocation. + + Returns: + str: The address ID. + + """ + return self._model.address_id + + @property + def network_id(self) -> str: + """Get the network ID of the contract invocation. + + Returns: + str: The network ID. + + """ + return self._model.network_id + + @property + def contract_address(self) -> str: + """Get the contract address. + + Returns: + str: The contract address. + + """ + return self._model.contract_address + + @property + def abi(self) -> dict[str, Any]: + """Get the ABI of the contract invocation. + + Returns: + Dict: The ABI JSON. + + """ + return dict(json.loads(self._model.abi).items()) + + @property + def method(self) -> str: + """Get the method being invoked in the contract. + + Returns: + str: The method being invoked. + + """ + return self._model.method + + @property + def args(self) -> dict[str, Any]: + """Get the arguments passed to the contract method. + + Returns: + Dict: The arguments passed to the contract method. + + """ + return dict(json.loads(self._model.args).items()) + + @property + def amount(self) -> Decimal: + """Get the amount sent to the contract in atomic units. + + Returns: + Decimal: The amount in atomic units. + + """ + return Decimal(self._model.amount) + + @property + def transaction(self) -> Transaction | None: + """Get the transaction associated with the contract invocation. + + Returns: + Transaction: The transaction. + + """ + if self._transaction is None and self._model.transaction is not None: + self._update_transaction(self._model) + return self._transaction + + @property + def transaction_link(self) -> str: + """Get the link to the transaction on the blockchain explorer. + + Returns: + str: The transaction link. + + """ + return self.transaction.transaction_link + + @property + def transaction_hash(self) -> str: + """Get the transaction hash of the contract invocation. + + Returns: + str: The transaction hash. + + """ + return self.transaction.transaction_hash + + @property + def status(self) -> str: + """Get the status of the contract invocation. + + Returns: + str: The status. + + """ + return self.transaction.status if self.transaction else None + + def sign(self, key: LocalAccount) -> "ContractInvocation": + """Sign the contract invocation transaction with the given key. + + Args: + key (LocalAccount): The key to sign the contract invocation with. + + Returns: + ContractInvocation: The signed ContractInvocation object. + + Raises: + ValueError: If the key is not a LocalAccount. + + """ + if not isinstance(key, LocalAccount): + raise ValueError("key must be a LocalAccount") + + self.transaction.sign(key) + return self + + def broadcast(self) -> "ContractInvocation": + """Broadcast the contract invocation to the network. + + Returns: + ContractInvocation: The broadcasted ContractInvocation object. + + Raises: + TransactionNotSignedError: If the transaction is not signed. + + """ + if not self.transaction.signed: + raise TransactionNotSignedError("Contract invocation is not signed") + + broadcast_contract_invocation_request = BroadcastContractInvocationRequest( + signed_payload=self.transaction.signature + ) + + model = Cdp.api_clients.contract_invocations.broadcast_contract_invocation( + wallet_id=self.wallet_id, + address_id=self.address_id, + contract_invocation_id=self.contract_invocation_id, + broadcast_contract_invocation_request=broadcast_contract_invocation_request, + ) + self._model = model + return self + + def reload(self) -> "ContractInvocation": + """Reload the Contract Invocation model with the latest version from the server. + + Returns: + ContractInvocation: The updated ContractInvocation object. + + """ + model = Cdp.api_clients.contract_invocations.get_contract_invocation( + wallet_id=self.wallet_id, + address_id=self.address_id, + contract_invocation_id=self.contract_invocation_id, + ) + + self._model = model + self._update_transaction(model) + + return self + + def wait( + self, interval_seconds: float = 0.2, timeout_seconds: float = 20 + ) -> "ContractInvocation": + """Wait until the contract invocation is signed or fails by polling the server. + + Args: + interval_seconds: The interval at which to poll the server. + timeout_seconds: The maximum time to wait before timing out. + + Returns: + ContractInvocation: The completed contract invocation. + + Raises: + TimeoutError: If the invocation takes longer than the given timeout. + + """ + start_time = time.time() + while not self.transaction.terminal_state: + self.reload() + + if time.time() - start_time > timeout_seconds: + raise TimeoutError("Contract Invocation timed out") + + time.sleep(interval_seconds) + + return self + + @classmethod + def create( + cls, + address_id: str, + wallet_id: str, + network_id: str, + contract_address: str, + method: str, + abi: list[dict] | None = None, + args: dict | None = None, + amount: Decimal | None = None, + asset_id: str | None = None, + ) -> "ContractInvocation": + """Create a new ContractInvocation object. + + Args: + address_id (str): The address ID of the signing address. + wallet_id (str): The wallet ID associated with the signing address. + network_id (str): The Network ID. + contract_address (str): The contract address. + method (str): The contract method. + abi (Optional[list[dict]]): The contract ABI, if provided. + args (Optional[dict]): The arguments to pass to the contract method. + amount (Optional[Decimal]): The amount of native asset to send to a payable contract method. + asset_id (Optional[str]): The asset ID to send to the contract. + + Returns: + ContractInvocation: The new ContractInvocation object. + + """ + atomic_amount = None + abi_json = None + + if asset_id and amount: + asset = Asset.fetch(network_id, asset_id) + atomic_amount = str(int(asset.to_atomic_amount(Decimal(amount)))) + + if abi: + abi_json = json.dumps(abi, separators=(",", ":")) + + create_contract_invocation_request = CreateContractInvocationRequest( + contract_address=contract_address, + abi=abi_json, + method=method, + args=json.dumps(args or {}, separators=(",", ":")), + amount=atomic_amount, + ) + + model = Cdp.api_clients.contract_invocations.create_contract_invocation( + wallet_id=wallet_id, + address_id=address_id, + create_contract_invocation_request=create_contract_invocation_request, + ) + + return cls(model) + + @classmethod + def list(cls, wallet_id: str, address_id: str) -> Iterator["ContractInvocation"]: + """List Contract Invocations. + + Args: + wallet_id (str): The wallet ID. + address_id (str): The address ID. + + Returns: + Iterator[ContractInvocation]: An iterator of ContractInvocation objects. + + """ + page = None + while True: + response = Cdp.api_clients.contract_invocations.list_contract_invocations( + wallet_id=wallet_id, address_id=address_id, limit=100, page=page + ) + for contract_invocation in response.data: + yield cls(contract_invocation) + + if not response.has_more: + break + + page = response.next_page + + def _update_transaction(self, model: ContractInvocationModel) -> None: + """Update the transaction with the new model.""" + if model.transaction is not None: + self._transaction = Transaction(model.transaction) + + def __str__(self) -> str: + """Return a string representation of the contract invocation.""" + return ( + f"ContractInvocation: (contract_invocation_id: {self.contract_invocation_id}, wallet_id: {self.wallet_id}, address_id: {self.address_id}, " + f"network_id: {self.network_id}, method: {self.method}, transaction_hash: {self.transaction_hash}, transaction_link: {self.transaction_link}, status: {self.status})" + ) + + def __repr__(self) -> str: + """Return a string representation of the contract invocation.""" + return str(self) diff --git a/cdp/wallet.py b/cdp/wallet.py index 41c2414..f67fd70 100644 --- a/cdp/wallet.py +++ b/cdp/wallet.py @@ -1,3 +1,4 @@ +import builtins import hashlib import json import os @@ -25,6 +26,7 @@ ) from cdp.client.models.wallet import Wallet as WalletModel from cdp.client.models.wallet_list import WalletList +from cdp.contract_invocation import ContractInvocation from cdp.faucet_transaction import FaucetTransaction from cdp.trade import Trade from cdp.wallet_address import WalletAddress @@ -384,6 +386,41 @@ def trade(self, amount: Number | Decimal | str, from_asset_id: str, to_asset_id: return self.default_address.trade(amount, from_asset_id, to_asset_id) + def invoke_contract( + self, + contract_address: str, + method: str, + abi: builtins.list[dict] | None = None, + args: dict | None = None, + amount: Number | Decimal | str | None = None, + asset_id: str | None = None, + ) -> ContractInvocation: + """Invoke a method on the specified contract address, with the given ABI and arguments. + + Args: + contract_address (str): The address of the contract to invoke. + method (str): The name of the method to call on the contract. + abi (Optional[list[dict]]): The ABI of the contract, if provided. + args (Optional[dict]): The arguments to pass to the method. + amount (Optional[Union[Number, Decimal, str]]): The amount to send with the invocation, if applicable. + asset_id (Optional[str]): The asset ID associated with the amount, if applicable. + + Returns: + ContractInvocation: The contract invocation object. + + Raises: + ValueError: If the default address does not exist. + + """ + if self.default_address is None: + raise ValueError("Default address does not exist") + + invocation = self.default_address.invoke_contract( + contract_address, method, abi, args, amount, asset_id + ) + + return invocation + @property def default_address(self) -> WalletAddress | None: """Get the default address of the wallet. diff --git a/cdp/wallet_address.py b/cdp/wallet_address.py index 7dcb607..34de42e 100644 --- a/cdp/wallet_address.py +++ b/cdp/wallet_address.py @@ -8,6 +8,7 @@ from cdp.address import Address from cdp.cdp import Cdp from cdp.client.models.address import Address as AddressModel +from cdp.contract_invocation import ContractInvocation from cdp.errors import InsufficientFundsError from cdp.trade import Trade from cdp.transfer import Transfer @@ -146,6 +147,55 @@ def trade(self, amount: Number | Decimal | str, from_asset_id: str, to_asset_id: return trade + def invoke_contract( + self, + contract_address: str, + method: str, + abi: list[dict] | None = None, + args: dict | None = None, + amount: Number | Decimal | str | None = None, + asset_id: str | None = None, + ) -> ContractInvocation: + """Invoke a method on the specified contract address, with the given ABI and arguments. + + Args: + contract_address (str): The address of the contract to invoke. + method (str): The name of the method to call on the contract. + abi (Optional[list[dict]]): The ABI of the contract, if provided. + args (Optional[dict]): The arguments to pass to the method. + amount (Optional[Union[Number, Decimal, str]]): The amount to send with the invocation, if applicable. + asset_id (Optional[str]): The asset ID associated with the amount, if applicable. + + Returns: + ContractInvocation: The contract invocation object. + + """ + normalized_amount = Decimal(amount) if amount else Decimal("0") + + if amount and asset_id: + self._ensure_sufficient_balance(amount, asset_id) + + invocation = ContractInvocation.create( + address_id=self.address_id, + wallet_id=self.wallet_id, + network_id=self.network_id, + contract_address=contract_address, + method=method, + abi=abi, + args=args, + amount=normalized_amount, + asset_id=asset_id, + ) + + if Cdp.use_server_signer: + return invocation + + invocation.sign(self.key) + + invocation.broadcast() + + return invocation + def transfers(self) -> Iterator[Transfer]: """List transfers for this wallet address. diff --git a/docs/cdp.rst b/docs/cdp.rst index e0c4e6b..2692f8f 100644 --- a/docs/cdp.rst +++ b/docs/cdp.rst @@ -68,6 +68,14 @@ cdp.cdp\_api\_client module :undoc-members: :show-inheritance: +cdp.contract\_invocation module +------------------------------- + +.. automodule:: cdp.contract_invocation + :members: + :undoc-members: + :show-inheritance: + cdp.errors module ----------------- diff --git a/tests/test_contract_invocation.py b/tests/test_contract_invocation.py new file mode 100644 index 0000000..8fb4080 --- /dev/null +++ b/tests/test_contract_invocation.py @@ -0,0 +1,265 @@ +from decimal import Decimal +from unittest.mock import ANY, Mock, call, patch + +import pytest + +from cdp.asset import Asset +from cdp.client.models.asset import Asset as AssetModel +from cdp.client.models.contract_invocation import ContractInvocation as ContractInvocationModel +from cdp.client.models.transaction import Transaction as TransactionModel +from cdp.contract_invocation import ContractInvocation +from cdp.errors import TransactionNotSignedError + + +@pytest.fixture +def asset_model_factory(): + """Create and return a factory for creating AssetModel fixtures.""" + + def _create_asset_model(network_id="base-sepolia", asset_id="usdc", decimals=6): + return AssetModel(network_id=network_id, asset_id=asset_id, decimals=decimals) + + return _create_asset_model + + +@pytest.fixture +def asset_factory(asset_model_factory): + """Create and return a factory for creating Asset fixtures.""" + + def _create_asset(network_id="base-sepolia", asset_id="usdc", decimals=6): + asset_model = asset_model_factory(network_id, asset_id, decimals) + return Asset.from_model(asset_model) + + return _create_asset + + +@pytest.fixture +def transaction_model_factory(): + """Create and return a factory for creating TransactionModel fixtures.""" + + def _create_transaction_model(status="complete"): + return TransactionModel( + network_id="base-sepolia", + transaction_hash="0xtransactionhash", + from_address_id="0xaddressid", + to_address_id="0xdestination", + unsigned_payload="0xunsignedpayload", + signed_payload="0xsignedpayload" + if status in ["signed", "broadcast", "complete"] + else None, + status=status, + transaction_link="https://sepolia.basescan.org/tx/0xtransactionlink" + if status == "complete" + else None, + ) + + return _create_transaction_model + + +@pytest.fixture +def contract_invocation_model_factory(transaction_model_factory): + """Create and return a factory for creating ContractInvocationModel fixtures.""" + + def _create_contract_invocation_model(status="complete"): + return ContractInvocationModel( + network_id="base-sepolia", + wallet_id="test-wallet-id", + address_id="0xaddressid", + contract_invocation_id="test-invocation-id", + contract_address="0xcontractaddress", + method="testMethod", + args='{"arg1": "value1"}', + abi='{"abi": "data"}', + amount="1", + transaction=transaction_model_factory(status), + ) + + return _create_contract_invocation_model + + +@pytest.fixture +def contract_invocation_factory(contract_invocation_model_factory): + """Create and return a factory for creating ContractInvocation fixtures.""" + + def _create_contract_invocation(status="complete"): + contract_invocation_model = contract_invocation_model_factory(status) + return ContractInvocation(contract_invocation_model) + + return _create_contract_invocation + + +def test_contract_invocation_initialization(contract_invocation_factory): + """Test the initialization of a ContractInvocation object.""" + contract_invocation = contract_invocation_factory() + assert isinstance(contract_invocation, ContractInvocation) + + +def test_contract_invocation_properties(contract_invocation_factory): + """Test the properties of a ContractInvocation object.""" + contract_invocation = contract_invocation_factory() + assert contract_invocation.contract_invocation_id == "test-invocation-id" + assert contract_invocation.wallet_id == "test-wallet-id" + assert contract_invocation.address_id == "0xaddressid" + assert contract_invocation.contract_address == "0xcontractaddress" + assert contract_invocation.method == "testMethod" + assert contract_invocation.args == {"arg1": "value1"} + assert contract_invocation.abi == {"abi": "data"} + assert contract_invocation.amount == Decimal("1") # 1 in atomic units + assert contract_invocation.status.value == "complete" + assert ( + contract_invocation.transaction_link == "https://sepolia.basescan.org/tx/0xtransactionlink" + ) + assert contract_invocation.transaction_hash == "0xtransactionhash" + + +@patch("cdp.Cdp.api_clients") +@patch("cdp.contract_invocation.Asset") +def test_create_contract_invocation( + mock_asset, mock_api_clients, contract_invocation_factory, asset_factory +): + """Test the creation of a ContractInvocation object.""" + mock_fetch = Mock() + mock_fetch.return_value = asset_factory() + mock_asset.fetch = mock_fetch + mock_asset.to_atomic_amount = Mock(return_value=Decimal("1")) + + mock_create_invocation = Mock() + mock_create_invocation.return_value = contract_invocation_factory()._model + mock_api_clients.contract_invocations.create_contract_invocation = mock_create_invocation + + contract_invocation = ContractInvocation.create( + address_id="0xaddressid", + wallet_id="test-wallet-id", + network_id="base-sepolia", + contract_address="0xcontractaddress", + method="testMethod", + abi=[{"abi": "data"}], + args={"arg1": "value1"}, + amount=Decimal("1"), + asset_id="wei", + ) + + assert isinstance(contract_invocation, ContractInvocation) + mock_create_invocation.assert_called_once_with( + wallet_id="test-wallet-id", + address_id="0xaddressid", + create_contract_invocation_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_broadcast_contract_invocation(mock_api_clients, contract_invocation_factory): + """Test the broadcasting of a ContractInvocation object.""" + contract_invocation = contract_invocation_factory(status="signed") + mock_broadcast = Mock(return_value=contract_invocation_factory(status="broadcast")._model) + mock_api_clients.contract_invocations.broadcast_contract_invocation = mock_broadcast + + response = contract_invocation.broadcast() + + assert isinstance(response, ContractInvocation) + mock_broadcast.assert_called_once_with( + wallet_id=contract_invocation.wallet_id, + address_id=contract_invocation.address_id, + contract_invocation_id=contract_invocation.contract_invocation_id, + broadcast_contract_invocation_request=ANY, + ) + + +def test_broadcast_unsigned_contract_invocation(contract_invocation_factory): + """Test the broadcasting of an unsigned ContractInvocation object.""" + contract_invocation = contract_invocation_factory(status="pending") + with pytest.raises(TransactionNotSignedError, match="Contract invocation is not signed"): + contract_invocation.broadcast() + + +@patch("cdp.Cdp.api_clients") +def test_reload_contract_invocation(mock_api_clients, contract_invocation_factory): + """Test the reloading of a ContractInvocation object.""" + contract_invocation = contract_invocation_factory(status="pending") + complete_invocation = contract_invocation_factory(status="complete") + mock_get_invocation = Mock() + mock_api_clients.contract_invocations.get_contract_invocation = mock_get_invocation + mock_get_invocation.return_value = complete_invocation._model + + contract_invocation.reload() + + mock_get_invocation.assert_called_once_with( + wallet_id=contract_invocation.wallet_id, + address_id=contract_invocation.address_id, + contract_invocation_id=contract_invocation.contract_invocation_id, + ) + assert contract_invocation.status.value == "complete" + + +@patch("cdp.Cdp.api_clients") +@patch("cdp.contract_invocation.time.sleep") +@patch("cdp.contract_invocation.time.time") +def test_wait_for_contract_invocation( + mock_time, mock_sleep, mock_api_clients, contract_invocation_factory +): + """Test the waiting for a ContractInvocation object to complete.""" + pending_invocation = contract_invocation_factory(status="pending") + complete_invocation = contract_invocation_factory(status="complete") + mock_get_invocation = Mock() + mock_api_clients.contract_invocations.get_contract_invocation = mock_get_invocation + mock_get_invocation.side_effect = [pending_invocation._model, complete_invocation._model] + + mock_time.side_effect = [0, 0.2, 0.4] + + result = pending_invocation.wait(interval_seconds=0.2, timeout_seconds=1) + + assert result.status.value == "complete" + mock_get_invocation.assert_called_with( + wallet_id=pending_invocation.wallet_id, + address_id=pending_invocation.address_id, + contract_invocation_id=pending_invocation.contract_invocation_id, + ) + assert mock_get_invocation.call_count == 2 + mock_sleep.assert_has_calls([call(0.2)] * 2) + assert mock_time.call_count == 3 + + +@patch("cdp.Cdp.api_clients") +@patch("cdp.contract_invocation.time.sleep") +@patch("cdp.contract_invocation.time.time") +def test_wait_for_contract_invocation_timeout( + mock_time, mock_sleep, mock_api_clients, contract_invocation_factory +): + """Test the waiting for a ContractInvocation object to complete with a timeout.""" + pending_invocation = contract_invocation_factory(status="pending") + mock_get_invocation = Mock(return_value=pending_invocation._model) + mock_api_clients.contract_invocations.get_contract_invocation = mock_get_invocation + + mock_time.side_effect = [0, 0.5, 1.0, 1.5, 2.0, 2.5] + + with pytest.raises(TimeoutError, match="Contract Invocation timed out"): + pending_invocation.wait(interval_seconds=0.5, timeout_seconds=2) + + assert mock_get_invocation.call_count == 5 + mock_sleep.assert_has_calls([call(0.5)] * 4) + assert mock_time.call_count == 6 + + +def test_sign_contract_invocation_invalid_key(contract_invocation_factory): + """Test the signing of a ContractInvocation object with an invalid key.""" + contract_invocation = contract_invocation_factory() + with pytest.raises(ValueError, match="key must be a LocalAccount"): + contract_invocation.sign("invalid_key") + + +def test_contract_invocation_str_representation(contract_invocation_factory): + """Test the string representation of a ContractInvocation object.""" + contract_invocation = contract_invocation_factory() + expected_str = ( + f"ContractInvocation: (contract_invocation_id: {contract_invocation.contract_invocation_id}, " + f"wallet_id: {contract_invocation.wallet_id}, address_id: {contract_invocation.address_id}, " + f"network_id: {contract_invocation.network_id}, method: {contract_invocation.method}, " + f"transaction_hash: {contract_invocation.transaction_hash}, transaction_link: {contract_invocation.transaction_link}, " + f"status: {contract_invocation.status})" + ) + assert str(contract_invocation) == expected_str + + +def test_contract_invocation_repr(contract_invocation_factory): + """Test the representation of a ContractInvocation object.""" + contract_invocation = contract_invocation_factory() + assert repr(contract_invocation) == str(contract_invocation) diff --git a/tests/test_wallet.py b/tests/test_wallet.py index afac1f3..575395a 100644 --- a/tests/test_wallet.py +++ b/tests/test_wallet.py @@ -10,6 +10,7 @@ from cdp.client.models.create_wallet_request import CreateWalletRequest, CreateWalletRequestWallet from cdp.client.models.feature_set import FeatureSet from cdp.client.models.wallet import Wallet as WalletModel +from cdp.contract_invocation import ContractInvocation from cdp.trade import Trade from cdp.transfer import Transfer from cdp.wallet import Wallet @@ -420,6 +421,60 @@ def test_wallet_transfer_no_default_address(wallet_factory): ) +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_invoke_contract_with_server_signer(wallet_factory): + """Test the invoke_contract method of a Wallet with server-signer.""" + wallet = wallet_factory() + mock_default_address = Mock(spec=WalletAddress) + mock_contract_invocation_instance = Mock(spec=ContractInvocation) + mock_default_address.invoke_contract.return_value = mock_contract_invocation_instance + + with patch.object( + Wallet, "default_address", new_callable=PropertyMock + ) as mock_default_address_prop: + mock_default_address_prop.return_value = mock_default_address + + contract_invocation = wallet.invoke_contract( + contract_address="0xcontractaddress", + method="testMethod", + abi=[{"abi": "data"}], + args={"arg1": "value1"}, + amount=Decimal("1"), + asset_id="wei", + ) + + assert isinstance(contract_invocation, ContractInvocation) + mock_default_address.invoke_contract.assert_called_once_with( + "0xcontractaddress", + "testMethod", + [{"abi": "data"}], + {"arg1": "value1"}, + Decimal("1"), + "wei", + ) + + +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_contract_invocation_no_default_address(wallet_factory): + """Test the invoke_contract method of a Wallet with no default address.""" + wallet = wallet_factory() + + with patch.object( + Wallet, "default_address", new_callable=PropertyMock + ) as mock_default_address_prop: + mock_default_address_prop.return_value = None + + with pytest.raises(ValueError, match="Default address does not exist"): + wallet.invoke_contract( + contract_address="0xcontractaddress", + method="testMethod", + abi=[{"abi": "data"}], + args={"arg1": "value1"}, + amount=Decimal("1"), + asset_id="wei", + ) + + @patch("cdp.Cdp.api_clients") def test_wallet_reload(mock_api_clients, wallet_factory): """Test the reload method of a Wallet.""" diff --git a/tests/test_wallet_address.py b/tests/test_wallet_address.py index 96362e9..633ee6b 100644 --- a/tests/test_wallet_address.py +++ b/tests/test_wallet_address.py @@ -7,6 +7,7 @@ from cdp.client.models.address import Address as AddressModel from cdp.client.models.asset import Asset as AssetModel from cdp.client.models.balance import Balance as BalanceModel +from cdp.contract_invocation import ContractInvocation from cdp.errors import InsufficientFundsError from cdp.trade import Trade from cdp.transfer import Transfer @@ -334,6 +335,178 @@ def test_trades_api_error(mock_trade, wallet_address): wallet_address.trades() +@patch("cdp.wallet_address.ContractInvocation") +@patch("cdp.Cdp.api_clients") +@patch("cdp.Cdp.use_server_signer", True) +def test_invoke_contract_with_server_signer( + mock_api_clients, mock_contract_invocation, wallet_address, balance_model +): + """Test the invoke_contract method with a server signer.""" + mock_contract_invocation_instance = Mock(spec=ContractInvocation) + mock_contract_invocation.create.return_value = mock_contract_invocation_instance + + mock_get_balance = Mock() + mock_get_balance.return_value = balance_model + mock_api_clients.external_addresses.get_external_address_balance = mock_get_balance + + contract_invocation = wallet_address.invoke_contract( + contract_address="0xcontractaddress", + method="testMethod", + abi=[{"abi": "data"}], + args={"arg1": "value1"}, + amount=Decimal("1"), + asset_id="wei", + ) + + assert isinstance(contract_invocation, ContractInvocation) + mock_get_balance.assert_called_once_with( + network_id=wallet_address.network_id, address_id=wallet_address.address_id, asset_id="eth" + ) + mock_contract_invocation.create.assert_called_once_with( + address_id=wallet_address.address_id, + wallet_id=wallet_address.wallet_id, + network_id=wallet_address.network_id, + contract_address="0xcontractaddress", + method="testMethod", + abi=[{"abi": "data"}], + args={"arg1": "value1"}, + amount=Decimal("1"), + asset_id="wei", + ) + mock_contract_invocation_instance.sign.assert_not_called() + mock_contract_invocation_instance.broadcast.assert_not_called() + + +@patch("cdp.wallet_address.ContractInvocation") +@patch("cdp.Cdp.api_clients") +@patch("cdp.Cdp.use_server_signer", False) +def test_invoke_contract( + mock_api_clients, mock_contract_invocation, wallet_address_with_key, balance_model +): + """Test the invoke_contract method.""" + mock_contract_invocation_instance = Mock(spec=ContractInvocation) + mock_contract_invocation.create.return_value = mock_contract_invocation_instance + + mock_get_balance = Mock() + mock_get_balance.return_value = balance_model + mock_api_clients.external_addresses.get_external_address_balance = mock_get_balance + + contract_invocation = wallet_address_with_key.invoke_contract( + contract_address="0xcontractaddress", + method="testMethod", + abi=[{"abi": "data"}], + args={"arg1": "value1"}, + amount=Decimal("1"), + asset_id="wei", + ) + + assert isinstance(contract_invocation, ContractInvocation) + mock_get_balance.assert_called_once_with( + network_id=wallet_address_with_key.network_id, + address_id=wallet_address_with_key.address_id, + asset_id="eth", + ) + mock_contract_invocation.create.assert_called_once_with( + address_id=wallet_address_with_key.address_id, + wallet_id=wallet_address_with_key.wallet_id, + network_id=wallet_address_with_key.network_id, + contract_address="0xcontractaddress", + method="testMethod", + abi=[{"abi": "data"}], + args={"arg1": "value1"}, + amount=Decimal("1"), + asset_id="wei", + ) + mock_contract_invocation_instance.sign.assert_called_once_with(wallet_address_with_key.key) + mock_contract_invocation_instance.broadcast.assert_called_once() + + +@patch("cdp.wallet_address.ContractInvocation") +@patch("cdp.Cdp.api_clients") +@patch("cdp.Cdp.use_server_signer", False) +def test_invoke_contract_api_error( + mock_api_clients, mock_contract_invocation, wallet_address_with_key, balance_model +): + """Test the invoke_contract method raises an error when the create API call fails.""" + mock_contract_invocation.create.side_effect = Exception("API Error") + + mock_get_balance = Mock() + mock_get_balance.return_value = balance_model + mock_api_clients.external_addresses.get_external_address_balance = mock_get_balance + + with pytest.raises(Exception, match="API Error"): + wallet_address_with_key.invoke_contract( + contract_address="0xcontractaddress", + method="testMethod", + abi=[{"abi": "data"}], + args={"arg1": "value1"}, + amount=Decimal("1"), + asset_id="wei", + ) + + mock_get_balance.assert_called_once_with( + network_id=wallet_address_with_key.network_id, + address_id=wallet_address_with_key.address_id, + asset_id="eth", + ) + mock_contract_invocation.create.assert_called_once_with( + address_id=wallet_address_with_key.address_id, + wallet_id=wallet_address_with_key.wallet_id, + network_id=wallet_address_with_key.network_id, + contract_address="0xcontractaddress", + method="testMethod", + abi=[{"abi": "data"}], + args={"arg1": "value1"}, + amount=Decimal("1"), + asset_id="wei", + ) + + +@patch("cdp.wallet_address.ContractInvocation") +@patch("cdp.Cdp.api_clients") +@patch("cdp.Cdp.use_server_signer", False) +def test_invoke_contract_broadcast_api_error( + mock_api_clients, mock_contract_invocation, wallet_address_with_key, balance_model +): + """Test the invoke_contract method raises an error when the broadcast API call fails.""" + mock_contract_invocation_instance = Mock(spec=ContractInvocation) + mock_contract_invocation.create.return_value = mock_contract_invocation_instance + mock_contract_invocation_instance.broadcast.side_effect = Exception("API Error") + + mock_get_balance = Mock() + mock_get_balance.return_value = balance_model + mock_api_clients.external_addresses.get_external_address_balance = mock_get_balance + + with pytest.raises(Exception, match="API Error"): + wallet_address_with_key.invoke_contract( + contract_address="0xcontractaddress", + method="testMethod", + abi=[{"abi": "data"}], + args={"arg1": "value1"}, + amount=Decimal("1"), + asset_id="wei", + ) + + mock_get_balance.assert_called_once_with( + network_id=wallet_address_with_key.network_id, + address_id=wallet_address_with_key.address_id, + asset_id="eth", + ) + mock_contract_invocation.create.assert_called_once_with( + address_id=wallet_address_with_key.address_id, + wallet_id=wallet_address_with_key.wallet_id, + network_id=wallet_address_with_key.network_id, + contract_address="0xcontractaddress", + method="testMethod", + abi=[{"abi": "data"}], + args={"arg1": "value1"}, + amount=Decimal("1"), + asset_id="wei", + ) + mock_contract_invocation_instance.sign.assert_called_once_with(wallet_address_with_key.key) + mock_contract_invocation_instance.broadcast.assert_called_once() + + @patch("cdp.Cdp.api_clients") def test_ensure_sufficient_balance_sufficient(mock_api_clients, wallet_address, balance_model): """Test the ensure_sufficient_balance method with sufficient balance.""" From 385ba862b0ea0e149fa19da3b729b60d84e8a0d1 Mon Sep 17 00:00:00 2001 From: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> Date: Mon, 30 Sep 2024 12:52:15 -0400 Subject: [PATCH 06/40] [chore] Export WalletAddress in CDP Module (#16) --- cdp/__init__.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cdp/__init__.py b/cdp/__init__.py index df12ecb..78c7e4d 100644 --- a/cdp/__init__.py +++ b/cdp/__init__.py @@ -11,6 +11,7 @@ from cdp.transaction import Transaction from cdp.transfer import Transfer from cdp.wallet import Wallet +from cdp.wallet_address import WalletAddress from cdp.wallet_data import WalletData __all__ = [ @@ -18,6 +19,7 @@ "Cdp", "ContractInvocation", "Wallet", + "WalletAddress", "WalletData", "Asset", "Transfer", From 0013e00ddab38bda753e1be66d9543eabfa41782 Mon Sep 17 00:00:00 2001 From: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> Date: Mon, 30 Sep 2024 13:05:08 -0400 Subject: [PATCH 07/40] [chore] Clean up README Code Snippets (#15) --- README.md | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index ca22e3d..447dbd2 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ To start, [create a CDP API key](https://portal.cdp.coinbase.com/access/api). Th from cdp import * api_key_name = "Copy your API key name here." -# Ensure that you are using double-quotes here. + api_key_private_key = "Copy your API key's private key here." Cdp.configure(api_key_name, api_key_private_key) @@ -80,6 +80,8 @@ Now create a wallet. Wallets are created with a single default address. ```python # Create a wallet with one address by default. wallet1 = Wallet.create() + +print(f"Wallet successfully created: {wallet1}") ``` Wallets come with a single default address, accessible via `default_address`: @@ -130,6 +132,11 @@ wallet3 = Wallet.create() print(f"Wallet successfully created: {wallet3}") +# Fund the wallet with USDC with a faucet transaction. +usdc_faucet_tx = wallet1.faucet("usdc") + +print(f"Faucet transaction successfully completed: {usdc_faucet_tx}") + transfer = wallet1.transfer(0.00001, "usdc", wallet3, gasless=True).wait() ``` @@ -137,7 +144,7 @@ transfer = wallet1.transfer(0.00001, "usdc", wallet3, gasless=True).wait() ```python # Return list of all transfers. This will paginate and fetch all transfers for the address. -address.transfers() +list(address.transfers()) ``` ## Trading Funds @@ -159,6 +166,6 @@ print(f"Trade successfully completed: {trade}") ```python # Return list of all trades. This will paginate and fetch all trades for the address. -address.trades() +list(address.trades()) ``` From cda596a2b77a6165cae3f68cfe3476926fbe9507 Mon Sep 17 00:00:00 2001 From: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> Date: Mon, 30 Sep 2024 13:10:29 -0400 Subject: [PATCH 08/40] [chore] Fix Get Default Address on Newly Hydrated Wallet (#14) --- CHANGELOG.md | 4 ++++ cdp/wallet.py | 2 +- tests/test_wallet.py | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2723d63..9e35335 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ - Contract invocation support. +### Fixed + +- Fixed bug in `Wallet` `default_address` property for newly hydrated wallets. + ## [0.0.3] - 2024-09-25 ### Added diff --git a/cdp/wallet.py b/cdp/wallet.py index f67fd70..93980d9 100644 --- a/cdp/wallet.py +++ b/cdp/wallet.py @@ -606,7 +606,7 @@ def _address(self, address_id: str) -> WalletAddress | None: """ return next( - (address for address in self._addresses if address.address_id == address_id), + (address for address in self.addresses if address.address_id == address_id), None, ) diff --git a/tests/test_wallet.py b/tests/test_wallet.py index 575395a..0819646 100644 --- a/tests/test_wallet.py +++ b/tests/test_wallet.py @@ -48,7 +48,7 @@ def _create_wallet_model( network_id="base-sepolia", default_address=None, feature_set=None, - server_signer_status="active_seed", + server_signer_status="active_seed" ): if default_address is None: default_address = address_model_factory() From ba1196e3a66f88297ebd30c9590a0c25e731f66c Mon Sep 17 00:00:00 2001 From: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> Date: Mon, 30 Sep 2024 13:26:56 -0400 Subject: [PATCH 09/40] [chore] Fully Automate Doc Generation via GHA (#17) --- .github/workflows/publish_docs.yml | 3 +-- Makefile | 4 ++++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/publish_docs.yml b/.github/workflows/publish_docs.yml index 82a6012..1472326 100644 --- a/.github/workflows/publish_docs.yml +++ b/.github/workflows/publish_docs.yml @@ -23,6 +23,7 @@ jobs: - name: Build Sphinx Documentation run: | + make docs cd docs make html @@ -32,5 +33,3 @@ jobs: github_token: ${{ secrets.GITHUB_TOKEN }} publish_dir: ./docs/_build/html keep_files: false - - diff --git a/Makefile b/Makefile index f44df2e..858161d 100644 --- a/Makefile +++ b/Makefile @@ -29,3 +29,7 @@ install-deps: .PHONY: docs docs: sphinx-apidoc -f -o docs/ ./cdp/ + +.PHONY: local-docs +local-docs: docs + cd docs && make html && open ./_build/html/index.html From b28f694eb0fbadb35eef9ca980301c0ae91f73c7 Mon Sep 17 00:00:00 2001 From: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> Date: Mon, 30 Sep 2024 17:32:33 -0400 Subject: [PATCH 10/40] [PSDK-499] Payload Signature Support (#19) --- CHANGELOG.md | 1 + cdp/__init__.py | 2 + cdp/payload_signature.py | 228 ++++++++++++++++++++++++++++++++ cdp/wallet.py | 17 +++ cdp/wallet_address.py | 25 ++++ tests/test_payload_signature.py | 205 ++++++++++++++++++++++++++++ tests/test_wallet.py | 36 ++++- tests/test_wallet_address.py | 83 ++++++++++++ 8 files changed, 596 insertions(+), 1 deletion(-) create mode 100644 cdp/payload_signature.py create mode 100644 tests/test_payload_signature.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e35335..079f926 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Added - Contract invocation support. +- Arbitrary message signing support. ### Fixed diff --git a/cdp/__init__.py b/cdp/__init__.py index 78c7e4d..57e82e1 100644 --- a/cdp/__init__.py +++ b/cdp/__init__.py @@ -6,6 +6,7 @@ from cdp.cdp import Cdp from cdp.contract_invocation import ContractInvocation from cdp.faucet_transaction import FaucetTransaction +from cdp.payload_signature import PayloadSignature from cdp.sponsored_send import SponsoredSend from cdp.trade import Trade from cdp.transaction import Transaction @@ -30,4 +31,5 @@ "FaucetTransaction", "Trade", "SponsoredSend", + "PayloadSignature", ] diff --git a/cdp/payload_signature.py b/cdp/payload_signature.py new file mode 100644 index 0000000..9d12b52 --- /dev/null +++ b/cdp/payload_signature.py @@ -0,0 +1,228 @@ +import time +from collections.abc import Iterator +from enum import Enum + +from cdp import Cdp +from cdp.client.models.create_payload_signature_request import CreatePayloadSignatureRequest +from cdp.client.models.payload_signature import PayloadSignature as PayloadSignatureModel +from cdp.client.models.payload_signature_list import PayloadSignatureList + + +class PayloadSignature: + """A representation of a Payload Signature.""" + + class Status(Enum): + """Enumeration of Payload Signature statuses.""" + + PENDING = "pending" + SIGNED = "signed" + FAILED = "failed" + + @classmethod + def terminal_states(cls): + """Get the terminal states. + + Returns: + List[str]: The terminal states. + + """ + return [cls.SIGNED, cls.FAILED] + + def __str__(self) -> str: + """Return a string representation of the Status.""" + return self.value + + def __repr__(self) -> str: + """Return a string representation of the Status.""" + return str(self) + + def __init__(self, model: PayloadSignatureModel) -> None: + """Initialize the PayloadSignature class. + + Args: + model (PayloadSignatureModel): The model representing the paylaod signature. + + """ + if not isinstance(model, PayloadSignatureModel): + raise TypeError("model must be of type PayloadSignatureModel") + + self._model = model + + @property + def payload_signature_id(self) -> str: + """Get the payload signature ID. + + Returns: + str: The payload signature ID. + + """ + return self._model.payload_signature_id + + @property + def wallet_id(self) -> str: + """Get the wallet ID. + + Returns: + str: The wallet ID. + + """ + return self._model.wallet_id + + @property + def address_id(self) -> str: + """Get the address ID. + + Returns: + str: The address ID. + + """ + return self._model.address_id + + @property + def unsigned_payload(self) -> str: + """Get the unsigned payload. + + Returns: + str: The unsigned payload. + + """ + return self._model.unsigned_payload + + @property + def signature(self) -> str: + """Get the signature. + + Returns: + str: The signature. + + """ + return self._model.signature + + @property + def status(self) -> Status: + """Get the status. + + Returns: + PayloadSignature.Status: The status. + + """ + return self.Status(self._model.status) + + @property + def terminal_state(self) -> bool: + """Check if the Transaction is in a terminal state. + + Returns: + bool: Whether the paylaod signature is in a terminal state. + + """ + return self.status in self.Status.terminal_states() + + def reload(self) -> None: + """Reload the payload signature.""" + model = Cdp.api_clients.addresses.get_payload_signature( + self.wallet_id, self.address_id, self.payload_signature_id + ) + self._model = model + + def wait( + self, interval_seconds: float = 0.2, timeout_seconds: float = 20 + ) -> "PayloadSignature": + """Wait for the payload signature to complete. + + Args: + interval_seconds (float): The interval seconds. + timeout_seconds (float): The timeout seconds. + + Returns: + PayloadSignature: The payload signature. + + """ + start_time = time.time() + + while not self.terminal_state: + self.reload() + + if time.time() - start_time > timeout_seconds: + raise TimeoutError("Timed out waiting for PayloadSignature to be signed") + + time.sleep(interval_seconds) + + return self + + @classmethod + def create( + cls, wallet_id: str, address_id: str, unsigned_payload: str, signature: str | None = None + ) -> "PayloadSignature": + """Create a payload signature. + + Args: + wallet_id (str): The wallet ID. + address_id (str): The address ID. + unsigned_payload (str): The unsigned payload. + signature (Optional[str]): The signature. + + Returns: + PayloadSignature: The payload signature. + + Raises: + Exception: If there's an error creating the payload signature.. + + """ + create_payload_signature_request_dict = {"unsigned_payload": unsigned_payload} + + if signature is not None: + create_payload_signature_request_dict["signature"] = signature + + create_payload_signature_request = CreatePayloadSignatureRequest.from_dict( + create_payload_signature_request_dict + ) + + model = Cdp.api_clients.addresses.create_payload_signature( + wallet_id=wallet_id, + address_id=address_id, + create_payload_signature_request=create_payload_signature_request, + ) + + return cls(model) + + @classmethod + def list(cls, wallet_id: str, address_id: str) -> Iterator["PayloadSignature"]: + """List payload signatures. + + Args: + wallet_id (str): The wallet ID. + address_id (str): The address ID. + + Returns: + Iterator[Payload]: An iterator of payload signatures. + + Raises: + Exception: If there's an error listing the payload signatures. + + """ + page = None + while True: + response: PayloadSignatureList = Cdp.api_clients.addresses.list_payload_signatures( + wallet_id=wallet_id, address_id=address_id, limit=100, page=page + ) + + for payload_signature_model in response.data: + yield cls(payload_signature_model) + + if not response.has_more: + break + + page = response.next_page + + def __str__(self) -> str: + """Get a string representation of the payload signature.""" + return ( + f"PayloadSignature: (payload_signature_id: {self.payload_signature_id}, wallet_id: {self.wallet_id}, " + f"address_id: {self.address_id}, unsigned_payload: {self.unsigned_payload}, signature: {self.signature}, " + f"status: {self.status})" + ) + + def __repr__(self) -> str: + """Get a string representation of the payload signature.""" + return str(self) diff --git a/cdp/wallet.py b/cdp/wallet.py index 93980d9..c117641 100644 --- a/cdp/wallet.py +++ b/cdp/wallet.py @@ -28,6 +28,7 @@ from cdp.client.models.wallet_list import WalletList from cdp.contract_invocation import ContractInvocation from cdp.faucet_transaction import FaucetTransaction +from cdp.payload_signature import PayloadSignature from cdp.trade import Trade from cdp.wallet_address import WalletAddress from cdp.wallet_data import WalletData @@ -421,6 +422,22 @@ def invoke_contract( return invocation + def sign_payload(self, unsigned_payload: str) -> PayloadSignature: + """Sign the given unsigned payload. + + Args: + unsigned_payload (str): The unsigned payload. + + Returns: + PayloadSignature: The payload signature object. + + + """ + if self.default_address is None: + raise ValueError("Default address does not exist") + + return self.default_address.sign_payload(unsigned_payload) + @property def default_address(self) -> WalletAddress | None: """Get the default address of the wallet. diff --git a/cdp/wallet_address.py b/cdp/wallet_address.py index 34de42e..c530781 100644 --- a/cdp/wallet_address.py +++ b/cdp/wallet_address.py @@ -4,12 +4,14 @@ from typing import TYPE_CHECKING, Union from eth_account.signers.local import LocalAccount +from eth_utils import to_bytes, to_hex from cdp.address import Address from cdp.cdp import Cdp from cdp.client.models.address import Address as AddressModel from cdp.contract_invocation import ContractInvocation from cdp.errors import InsufficientFundsError +from cdp.payload_signature import PayloadSignature from cdp.trade import Trade from cdp.transfer import Transfer @@ -196,6 +198,29 @@ def invoke_contract( return invocation + def sign_payload(self, unsigned_payload: str) -> PayloadSignature: + """Sign the given unsigned payload. + + Args: + unsigned_payload (str): The unsigned payload. + + Returns: + PayloadSignature: The payload signature object. + + """ + signature = None + + if not Cdp.use_server_signer: + signed_message = self.key.unsafe_sign_hash(to_bytes(hexstr=unsigned_payload)) + signature = to_hex(signed_message.signature) + + return PayloadSignature.create( + wallet_id=self.wallet_id, + address_id=self.address_id, + unsigned_payload=unsigned_payload, + signature=signature, + ) + def transfers(self) -> Iterator[Transfer]: """List transfers for this wallet address. diff --git a/tests/test_payload_signature.py b/tests/test_payload_signature.py new file mode 100644 index 0000000..7721fca --- /dev/null +++ b/tests/test_payload_signature.py @@ -0,0 +1,205 @@ +from unittest.mock import ANY, Mock, call, patch + +import pytest + +from cdp.client.models.payload_signature import PayloadSignature as PayloadSignatureModel +from cdp.payload_signature import PayloadSignature + + +@pytest.fixture +def payload_signature_model_factory(): + """Create and return a factory for creating PayloadSignatureModel fixtures.""" + + def _create_payload_signature_model(status="signed"): + payload_signature_model = PayloadSignatureModel( + payload_signature_id="test-payload-signature-id", + address_id="0xaddressid", + wallet_id="test-wallet-id", + unsigned_payload="0xunsignedpayload", + signature="0xsignature" if status == "signed" else None, + status=status, + ) + + return payload_signature_model + + return _create_payload_signature_model + + +@pytest.fixture +def payload_signature_factory(payload_signature_model_factory): + """Create and return a factory for creating PayloadSignature fixtures.""" + + def _create_payload_signature(status="signed"): + payload_signature_model = payload_signature_model_factory(status) + return PayloadSignature(payload_signature_model) + + return _create_payload_signature + + +def test_payload_signature_initialization(payload_signature_factory): + """Test the initialization of a PayloadSignature object.""" + payload_signature = payload_signature_factory() + assert isinstance(payload_signature, PayloadSignature) + + +def test_payload_signuatre_properties(payload_signature_factory): + """Test the properties of a PayloadSignature object.""" + payload_signature = payload_signature_factory() + assert payload_signature.payload_signature_id == "test-payload-signature-id" + assert payload_signature.address_id == "0xaddressid" + assert payload_signature.wallet_id == "test-wallet-id" + assert payload_signature.unsigned_payload == "0xunsignedpayload" + assert payload_signature.signature == "0xsignature" + assert payload_signature.status.value == "signed" + + +@patch("cdp.Cdp.api_clients") +def test_create_unsigned_payload_signature(mock_api_clients, payload_signature_model_factory): + """Test the creation of a PayloadSignature object.""" + mock_create_payload_signature = Mock(return_value=payload_signature_model_factory("pending")) + mock_api_clients.addresses.create_payload_signature = mock_create_payload_signature + + payload_signature = PayloadSignature.create( + wallet_id="test-wallet-id", + address_id="0xaddressid", + unsigned_payload="0xunsignedpayload", + signature="0xsignature", + ) + + assert isinstance(payload_signature, PayloadSignature) + mock_create_payload_signature.assert_called_once_with( + wallet_id="test-wallet-id", address_id="0xaddressid", create_payload_signature_request=ANY + ) + + create_payload_signature_request = mock_create_payload_signature.call_args[1][ + "create_payload_signature_request" + ] + assert create_payload_signature_request.unsigned_payload == "0xunsignedpayload" + + +@patch("cdp.Cdp.api_clients") +def test_create_payload_signature(mock_api_clients, payload_signature_model_factory): + """Test the creation of a PayloadSignature object.""" + mock_create_payload_signature = Mock(return_value=payload_signature_model_factory()) + mock_api_clients.addresses.create_payload_signature = mock_create_payload_signature + + payload_signature = PayloadSignature.create( + wallet_id="test-wallet-id", + address_id="0xaddressid", + unsigned_payload="0xunsignedpayload", + signature="0xsignature", + ) + + assert isinstance(payload_signature, PayloadSignature) + mock_create_payload_signature.assert_called_once_with( + wallet_id="test-wallet-id", address_id="0xaddressid", create_payload_signature_request=ANY + ) + + create_payload_signature_request = mock_create_payload_signature.call_args[1][ + "create_payload_signature_request" + ] + assert create_payload_signature_request.unsigned_payload == "0xunsignedpayload" + assert create_payload_signature_request.signature == "0xsignature" + + +@patch("cdp.Cdp.api_clients") +def test_list_payload_signatures(mock_api_clients, payload_signature_model_factory): + """Test the listing of payload signatures.""" + mock_list_payload_signatures = Mock() + mock_list_payload_signatures.return_value = Mock( + data=[payload_signature_model_factory()], has_more=False + ) + mock_api_clients.addresses.list_payload_signatures = mock_list_payload_signatures + + payload_signatures = PayloadSignature.list("test-wallet-id", "0xaddressid") + assert len(list(payload_signatures)) == 1 + assert all(isinstance(p, PayloadSignature) for p in payload_signatures) + mock_list_payload_signatures.assert_called_once_with( + wallet_id="test-wallet-id", address_id="0xaddressid", limit=100, page=None + ) + + +@patch("cdp.Cdp.api_clients") +def test_reload_payload_signature(mock_api_clients, payload_signature_factory): + """Test the reloading of a payload signature.""" + payload_signature = payload_signature_factory("pending") + signed_payload_signature = payload_signature_factory() + mock_get_payload_signature = Mock(return_value=signed_payload_signature._model) + mock_api_clients.addresses.get_payload_signature = mock_get_payload_signature + + payload_signature.reload() + mock_get_payload_signature.assert_called_once_with( + payload_signature.wallet_id, + payload_signature.address_id, + payload_signature.payload_signature_id, + ) + assert payload_signature.status.value == "signed" + + +@patch("cdp.Cdp.api_clients") +@patch("cdp.payload_signature.time.sleep") +@patch("cdp.payload_signature.time.time") +def test_wait_for_payload_signature( + mock_time, mock_sleep, mock_api_clients, payload_signature_factory +): + """Test the waiting for a PayloadSignature object to be signed.""" + pending_payload_signature = payload_signature_factory("pending") + signed_payload_signature = payload_signature_factory() + mock_get_payload_signature = Mock() + mock_api_clients.addresses.get_payload_signature = mock_get_payload_signature + mock_get_payload_signature.side_effect = [ + pending_payload_signature._model, + signed_payload_signature._model, + ] + + mock_time.side_effect = [0, 0.2, 0.4] + + result = pending_payload_signature.wait(interval_seconds=0.2, timeout_seconds=1) + + assert result.status.value == "signed" + mock_get_payload_signature.assert_called_with( + pending_payload_signature.wallet_id, + pending_payload_signature.address_id, + pending_payload_signature.payload_signature_id, + ) + assert mock_get_payload_signature.call_count == 2 + mock_sleep.assert_has_calls([call(0.2)] * 2) + assert mock_time.call_count == 3 + + +@patch("cdp.Cdp.api_clients") +@patch("cdp.payload_signature.time.sleep") +@patch("cdp.payload_signature.time.time") +def test_wait_for_payload_signature_timeout( + mock_time, mock_sleep, mock_api_clients, payload_signature_factory +): + """Test the waiting for a PayloadSignature object to be signed with a timeout.""" + pending_payload_signature = payload_signature_factory("pending") + mock_get_payload_signature = Mock(return_value=pending_payload_signature._model) + mock_api_clients.addresses.get_payload_signature = mock_get_payload_signature + + mock_time.side_effect = [0, 0.5, 1.0, 1.5, 2.0, 2.5] + + with pytest.raises(TimeoutError, match="Timed out waiting for PayloadSignature to be signed"): + pending_payload_signature.wait(interval_seconds=0.5, timeout_seconds=2) + + assert mock_get_payload_signature.call_count == 5 + mock_sleep.assert_has_calls([call(0.5)] * 4) + assert mock_time.call_count == 6 + + +def test_payload_signature_str_representation(payload_signature_factory): + """Test the string representation of a PayloadSignature object.""" + payload_signature = payload_signature_factory() + expected_str = ( + f"PayloadSignature: (payload_signature_id: {payload_signature.payload_signature_id}, wallet_id: {payload_signature.wallet_id}, " + f"address_id: {payload_signature.address_id}, unsigned_payload: {payload_signature.unsigned_payload}, signature: {payload_signature.signature}, " + f"status: {payload_signature.status})" + ) + assert str(payload_signature) == expected_str + + +def test_payload_signature_repr(payload_signature_factory): + """Test the representation of a PayloadSignature object.""" + payload_signature = payload_signature_factory() + assert repr(payload_signature) == str(payload_signature) diff --git a/tests/test_wallet.py b/tests/test_wallet.py index 0819646..60cb9db 100644 --- a/tests/test_wallet.py +++ b/tests/test_wallet.py @@ -11,6 +11,7 @@ from cdp.client.models.feature_set import FeatureSet from cdp.client.models.wallet import Wallet as WalletModel from cdp.contract_invocation import ContractInvocation +from cdp.payload_signature import PayloadSignature from cdp.trade import Trade from cdp.transfer import Transfer from cdp.wallet import Wallet @@ -48,7 +49,7 @@ def _create_wallet_model( network_id="base-sepolia", default_address=None, feature_set=None, - server_signer_status="active_seed" + server_signer_status="active_seed", ): if default_address is None: default_address = address_model_factory() @@ -475,6 +476,39 @@ def test_wallet_contract_invocation_no_default_address(wallet_factory): ) +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_sign_payload_with_server_signer(wallet_factory): + """Test the sign_payload method of a Wallet with server-signer.""" + wallet = wallet_factory() + mock_default_address = Mock(spec=WalletAddress) + mock_payload_signature_instance = Mock(spec=PayloadSignature) + mock_default_address.sign_payload.return_value = mock_payload_signature_instance + + with patch.object( + Wallet, "default_address", new_callable=PropertyMock + ) as mock_default_address_prop: + mock_default_address_prop.return_value = mock_default_address + + payload_signature = wallet.sign_payload(unsigned_payload="0xunsignedpayload") + + assert isinstance(payload_signature, PayloadSignature) + mock_default_address.sign_payload.assert_called_once_with("0xunsignedpayload") + + +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_sign_payload_no_default_address(wallet_factory): + """Test the sign_payload method of a Wallet with no default address.""" + wallet = wallet_factory() + + with patch.object( + Wallet, "default_address", new_callable=PropertyMock + ) as mock_default_address_prop: + mock_default_address_prop.return_value = None + + with pytest.raises(ValueError, match="Default address does not exist"): + wallet.sign_payload(unsigned_payload="0xunsignedpayload") + + @patch("cdp.Cdp.api_clients") def test_wallet_reload(mock_api_clients, wallet_factory): """Test the reload method of a Wallet.""" diff --git a/tests/test_wallet_address.py b/tests/test_wallet_address.py index 633ee6b..9772714 100644 --- a/tests/test_wallet_address.py +++ b/tests/test_wallet_address.py @@ -2,13 +2,18 @@ from unittest.mock import Mock, patch import pytest +from eth_account.datastructures import SignedMessage +from eth_account.messages import encode_defunct from eth_account.signers.local import LocalAccount +from eth_utils import to_bytes +from web3 import Web3 from cdp.client.models.address import Address as AddressModel from cdp.client.models.asset import Asset as AssetModel from cdp.client.models.balance import Balance as BalanceModel from cdp.contract_invocation import ContractInvocation from cdp.errors import InsufficientFundsError +from cdp.payload_signature import PayloadSignature from cdp.trade import Trade from cdp.transfer import Transfer from cdp.wallet_address import WalletAddress @@ -507,6 +512,84 @@ def test_invoke_contract_broadcast_api_error( mock_contract_invocation_instance.broadcast.assert_called_once() +@patch("cdp.wallet_address.PayloadSignature") +@patch("cdp.Cdp.api_clients") +@patch("cdp.Cdp.use_server_signer", True) +def test_sign_payload_with_server_signer(mock_api_clients, mock_payload_signature, wallet_address): + """Test the sign_payload method with a server signer.""" + mock_payload_signature_instance = Mock(spec=PayloadSignature) + mock_payload_signature.create.return_value = mock_payload_signature_instance + + payload_signature = wallet_address.sign_payload(unsigned_payload="0xunsignedpayload") + + assert isinstance(payload_signature, PayloadSignature) + mock_payload_signature.create.assert_called_once_with( + wallet_id=wallet_address.wallet_id, + address_id=wallet_address.address_id, + unsigned_payload="0xunsignedpayload", + signature=None, + ) + + +@patch("cdp.wallet_address.to_hex", Mock(return_value="0xsignature")) +@patch("cdp.wallet_address.PayloadSignature") +@patch("cdp.Cdp.api_clients") +@patch("cdp.Cdp.use_server_signer", False) +def test_sign_payload(mock_api_clients, mock_payload_signature, wallet_address_with_key): + """Test the sign_payload method.""" + mock_payload_signature_instance = Mock(spec=PayloadSignature) + mock_payload_signature.create.return_value = mock_payload_signature_instance + + mock_signature = Mock(spec=SignedMessage) + mock_signature.signature = "0xsignature" + wallet_address_with_key.key.unsafe_sign_hash.return_value = mock_signature + + message_encoded = encode_defunct(text="eip-191 message") + unsigned_payload = Web3.keccak(message_encoded.body).hex() + + payload_signature = wallet_address_with_key.sign_payload(unsigned_payload=unsigned_payload) + + assert isinstance(payload_signature, PayloadSignature) + mock_payload_signature.create.assert_called_once_with( + wallet_id=wallet_address_with_key.wallet_id, + address_id=wallet_address_with_key.address_id, + unsigned_payload=unsigned_payload, + signature="0xsignature", + ) + wallet_address_with_key.key.unsafe_sign_hash.assert_called_once_with( + to_bytes(hexstr=unsigned_payload) + ) + + +@patch("cdp.wallet_address.to_hex", Mock(return_value="0xsignature")) +@patch("cdp.wallet_address.PayloadSignature") +@patch("cdp.Cdp.api_clients") +@patch("cdp.Cdp.use_server_signer", False) +def test_sign_payload_api_error(mock_api_clients, mock_payload_signature, wallet_address_with_key): + """Test the sign_payload method.""" + mock_signature = Mock(spec=SignedMessage) + mock_signature.signature = "0xsignature" + wallet_address_with_key.key.unsafe_sign_hash.return_value = mock_signature + + message_encoded = encode_defunct(text="eip-191 message") + unsigned_payload = Web3.keccak(message_encoded.body).hex() + + mock_payload_signature.create.side_effect = Exception("API Error") + + with pytest.raises(Exception, match="API Error"): + wallet_address_with_key.sign_payload(unsigned_payload=unsigned_payload) + + mock_payload_signature.create.assert_called_once_with( + wallet_id=wallet_address_with_key.wallet_id, + address_id=wallet_address_with_key.address_id, + unsigned_payload=unsigned_payload, + signature="0xsignature", + ) + wallet_address_with_key.key.unsafe_sign_hash.assert_called_once_with( + to_bytes(hexstr=unsigned_payload) + ) + + @patch("cdp.Cdp.api_clients") def test_ensure_sufficient_balance_sufficient(mock_api_clients, wallet_address, balance_model): """Test the ensure_sufficient_balance method with sufficient balance.""" From 1657ddfd422757b2e3d2922ff25d66232b10ad67 Mon Sep 17 00:00:00 2001 From: rohan-agarwal-coinbase Date: Mon, 30 Sep 2024 18:17:50 -0400 Subject: [PATCH 11/40] Added CONTRIBUTING.md (#20) * Contributing * Update CONTRIBUTING.md Co-authored-by: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> * Feedback * Testing --------- Co-authored-by: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> --- CONTRIBUTING.md | 58 +++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 3 +++ 2 files changed, 61 insertions(+) create mode 100644 CONTRIBUTING.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..c4b5e13 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,58 @@ +# Contributing Guide + +## Development + +### Python Version + +Developing in this repository requires Python 3.10 or higher. + +### Set-up + +Clone the repo by running: + +```bash +git clone git@github.com:coinbase/cdp-sdk-python.git +``` + +To install all dependencies, run: + +```bash +make install-deps +``` + +### Formatting + +To format the code, run: + +```bash +make format +``` + +### Linting + +To detect all lint errors, run: + +```bash +make lint +``` + +To autocorrect all lint errors, run: + +```bash +make lint-fix +``` + +### Testing +To run all tests, run: + +```bash +make test +``` + +### Generating Documentation + +To build and view the documentation locally, run: + +```bash +make local-docs +``` \ No newline at end of file diff --git a/README.md b/README.md index 447dbd2..1bf05fd 100644 --- a/README.md +++ b/README.md @@ -169,3 +169,6 @@ print(f"Trade successfully completed: {trade}") list(address.trades()) ``` +## Contributing + +See [CONTRIBUTING.md](CONTRIBUTING.md) for more information. From 45d04c13b68a9599c050bf98f3122c68529d12f0 Mon Sep 17 00:00:00 2001 From: rohan-agarwal-coinbase Date: Tue, 1 Oct 2024 12:47:43 -0400 Subject: [PATCH 12/40] Support for deploy_token, deploy_nft, deploy_multi_token (#18) --- CHANGELOG.md | 1 + cdp/__init__.py | 2 + cdp/api_clients.py | 17 + cdp/client/__init__.py | 26 +- cdp/client/api/__init__.py | 2 + cdp/client/api/addresses_api.py | 1670 +++++++++-------- cdp/client/api/assets_api.py | 184 +- cdp/client/api/balance_history_api.py | 242 +-- cdp/client/api/contract_events_api.py | 308 ++- cdp/client/api/contract_invocations_api.py | 782 ++++---- cdp/client/api/external_addresses_api.py | 832 +++----- cdp/client/api/networks_api.py | 161 +- cdp/client/api/server_signers_api.py | 1046 ++++++----- cdp/client/api/smart_contracts_api.py | 728 ++++--- cdp/client/api/stake_api.py | 982 +++++----- cdp/client/api/trades_api.py | 748 ++++---- cdp/client/api/transaction_history_api.py | 346 ++++ cdp/client/api/transfers_api.py | 748 ++++---- cdp/client/api/users_api.py | 157 +- cdp/client/api/validators_api.py | 408 ++-- cdp/client/api/wallet_stake_api.py | 569 +++--- cdp/client/api/wallets_api.py | 805 ++++---- cdp/client/api/webhooks_api.py | 959 +++++++--- cdp/client/api_client.py | 314 ++-- cdp/client/api_response.py | 18 +- cdp/client/configuration.py | 121 +- cdp/client/exceptions.py | 79 +- cdp/client/models/__init__.py | 25 +- cdp/client/models/address.py | 64 +- cdp/client/models/address_balance_list.py | 69 +- .../models/address_historical_balance_list.py | 67 +- cdp/client/models/address_list.py | 69 +- cdp/client/models/address_transaction_list.py | 67 +- cdp/client/models/asset.py | 66 +- cdp/client/models/balance.py | 57 +- .../broadcast_contract_invocation_request.py | 50 +- .../broadcast_staking_operation_request.py | 60 +- cdp/client/models/broadcast_trade_request.py | 56 +- .../models/broadcast_transfer_request.py | 46 +- .../models/build_staking_operation_request.py | 70 +- cdp/client/models/contract_event.py | 102 +- cdp/client/models/contract_event_list.py | 67 +- cdp/client/models/contract_invocation.py | 96 +- cdp/client/models/contract_invocation_list.py | 73 +- cdp/client/models/create_address_request.py | 67 +- .../create_contract_invocation_request.py | 69 +- .../create_payload_signature_request.py | 51 +- .../models/create_server_signer_request.py | 62 +- .../models/create_smart_contract_request.py | 59 +- .../create_staking_operation_request.py | 58 +- cdp/client/models/create_trade_request.py | 54 +- cdp/client/models/create_transfer_request.py | 72 +- cdp/client/models/create_wallet_request.py | 57 +- .../models/create_wallet_request_wallet.py | 54 +- .../models/create_wallet_webhook_request.py | 89 + cdp/client/models/create_webhook_request.py | 96 +- .../models/deploy_smart_contract_request.py | 50 +- cdp/client/models/erc20_transfer_event.py | 155 +- cdp/client/models/erc721_transfer_event.py | 154 +- cdp/client/models/error.py | 68 +- cdp/client/models/ethereum_transaction.py | 180 +- .../models/ethereum_transaction_access.py | 53 +- .../ethereum_transaction_access_list.py | 61 +- .../ethereum_transaction_flattened_trace.py | 144 +- .../models/ethereum_validator_metadata.py | 103 +- cdp/client/models/faucet_transaction.py | 60 +- cdp/client/models/feature_set.py | 67 +- ...historical_staking_balances200_response.py | 67 +- .../fetch_staking_rewards200_response.py | 67 +- .../models/fetch_staking_rewards_request.py | 82 +- .../models/get_staking_context_request.py | 62 +- cdp/client/models/historical_balance.py | 69 +- .../models/multi_token_contract_options.py | 87 + cdp/client/models/network.py | 94 +- cdp/client/models/network_identifier.py | 40 +- cdp/client/models/nft_contract_options.py | 49 +- cdp/client/models/payload_signature.py | 79 +- cdp/client/models/payload_signature_list.py | 73 +- cdp/client/models/seed_creation_event.py | 53 +- .../models/seed_creation_event_result.py | 69 +- cdp/client/models/server_signer.py | 58 +- cdp/client/models/server_signer_event.py | 63 +- .../models/server_signer_event_event.py | 78 +- cdp/client/models/server_signer_event_list.py | 69 +- cdp/client/models/server_signer_list.py | 73 +- cdp/client/models/signature_creation_event.py | 88 +- .../models/signature_creation_event_result.py | 74 +- .../signed_voluntary_exit_message_metadata.py | 62 +- cdp/client/models/smart_contract.py | 95 +- cdp/client/models/smart_contract_list.py | 67 +- cdp/client/models/smart_contract_options.py | 94 +- cdp/client/models/smart_contract_type.py | 29 +- cdp/client/models/sponsored_send.py | 97 +- cdp/client/models/staking_balance.py | 85 +- cdp/client/models/staking_context.py | 57 +- cdp/client/models/staking_context_context.py | 73 +- cdp/client/models/staking_operation.py | 105 +- .../models/staking_operation_metadata.py | 82 +- cdp/client/models/staking_reward.py | 92 +- cdp/client/models/staking_reward_format.py | 28 +- cdp/client/models/staking_reward_usd_value.py | 60 +- cdp/client/models/token_contract_options.py | 58 +- cdp/client/models/trade.py | 108 +- cdp/client/models/trade_list.py | 73 +- cdp/client/models/transaction.py | 133 +- cdp/client/models/transaction_content.py | 76 +- cdp/client/models/transaction_type.py | 26 +- cdp/client/models/transfer.py | 137 +- cdp/client/models/transfer_list.py | 73 +- cdp/client/models/update_webhook_request.py | 74 +- cdp/client/models/user.py | 49 +- cdp/client/models/validator.py | 81 +- cdp/client/models/validator_details.py | 80 +- cdp/client/models/validator_list.py | 67 +- cdp/client/models/validator_status.py | 50 +- cdp/client/models/wallet.py | 87 +- cdp/client/models/wallet_list.py | 69 +- cdp/client/models/webhook.py | 123 +- cdp/client/models/webhook_event_filter.py | 69 +- cdp/client/models/webhook_event_type.py | 32 +- .../models/webhook_event_type_filter.py | 80 +- cdp/client/models/webhook_list.py | 72 +- .../models/webhook_wallet_activity_filter.py | 57 +- cdp/client/rest.py | 111 +- cdp/smart_contract.py | 352 ++++ cdp/transaction.py | 6 +- cdp/wallet.py | 61 + cdp/wallet_address.py | 84 + tests/test_smart_contract.py | 237 +++ tests/test_wallet.py | 169 ++ tests/test_wallet_address.py | 316 +++- 131 files changed, 11892 insertions(+), 8780 deletions(-) create mode 100644 cdp/client/api/transaction_history_api.py create mode 100644 cdp/client/models/create_wallet_webhook_request.py create mode 100644 cdp/client/models/multi_token_contract_options.py create mode 100644 cdp/smart_contract.py create mode 100644 tests/test_smart_contract.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 079f926..585a06a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ - Contract invocation support. - Arbitrary message signing support. +- Deploy ERC20, ERC721, and ERC1155 smart contracts. ### Fixed diff --git a/cdp/__init__.py b/cdp/__init__.py index 57e82e1..0c2f049 100644 --- a/cdp/__init__.py +++ b/cdp/__init__.py @@ -7,6 +7,7 @@ from cdp.contract_invocation import ContractInvocation from cdp.faucet_transaction import FaucetTransaction from cdp.payload_signature import PayloadSignature +from cdp.smart_contract import SmartContract from cdp.sponsored_send import SponsoredSend from cdp.trade import Trade from cdp.transaction import Transaction @@ -32,4 +33,5 @@ "Trade", "SponsoredSend", "PayloadSignature", + "SmartContract", ] diff --git a/cdp/api_clients.py b/cdp/api_clients.py index a3615ad..a63b0e1 100644 --- a/cdp/api_clients.py +++ b/cdp/api_clients.py @@ -4,6 +4,7 @@ from cdp.client.api.contract_invocations_api import ContractInvocationsApi from cdp.client.api.external_addresses_api import ExternalAddressesApi from cdp.client.api.networks_api import NetworksApi +from cdp.client.api.smart_contracts_api import SmartContractsApi from cdp.client.api.trades_api import TradesApi from cdp.client.api.transfers_api import TransfersApi from cdp.client.api.wallets_api import WalletsApi @@ -44,6 +45,7 @@ def __init__(self, cdp_client: CdpApiClient) -> None: self._assets: AssetsApi | None = None self._trades: TradesApi | None = None self._contract_invocations: ContractInvocationsApi | None = None + self._smart_contracts: SmartContractsApi | None = None @property def wallets(self) -> WalletsApi: @@ -164,3 +166,18 @@ def contract_invocations(self) -> ContractInvocationsApi: if self._contract_invocations is None: self._contract_invocations = ContractInvocationsApi(api_client=self._cdp_client) return self._contract_invocations + + @property + def smart_contracts(self) -> SmartContractsApi: + """Get the SmartContractsApi client instance. + + Returns: + SmartContractsApi: The SmartContractsApi client instance. + + Note: + This property lazily initializes the SmartContractsApi client on first access. + + """ + if self._smart_contracts is None: + self._smart_contracts = SmartContractsApi(api_client=self._cdp_client) + return self._smart_contracts diff --git a/cdp/client/__init__.py b/cdp/client/__init__.py index 7e20acf..8b003f5 100644 --- a/cdp/client/__init__.py +++ b/cdp/client/__init__.py @@ -3,16 +3,17 @@ # flake8: noqa """ -Coinbase Platform API + Coinbase Platform API -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -Do not edit the class manually. + Do not edit the class manually. """ # noqa: E501 + __version__ = "1.0.0" # import apis into sdk package @@ -27,6 +28,7 @@ from cdp.client.api.smart_contracts_api import SmartContractsApi from cdp.client.api.stake_api import StakeApi from cdp.client.api.trades_api import TradesApi +from cdp.client.api.transaction_history_api import TransactionHistoryApi from cdp.client.api.transfers_api import TransfersApi from cdp.client.api.users_api import UsersApi from cdp.client.api.validators_api import ValidatorsApi @@ -53,9 +55,7 @@ from cdp.client.models.address_transaction_list import AddressTransactionList from cdp.client.models.asset import Asset from cdp.client.models.balance import Balance -from cdp.client.models.broadcast_contract_invocation_request import ( - BroadcastContractInvocationRequest, -) +from cdp.client.models.broadcast_contract_invocation_request import BroadcastContractInvocationRequest from cdp.client.models.broadcast_staking_operation_request import BroadcastStakingOperationRequest from cdp.client.models.broadcast_trade_request import BroadcastTradeRequest from cdp.client.models.broadcast_transfer_request import BroadcastTransferRequest @@ -74,6 +74,7 @@ from cdp.client.models.create_transfer_request import CreateTransferRequest from cdp.client.models.create_wallet_request import CreateWalletRequest from cdp.client.models.create_wallet_request_wallet import CreateWalletRequestWallet +from cdp.client.models.create_wallet_webhook_request import CreateWalletWebhookRequest from cdp.client.models.create_webhook_request import CreateWebhookRequest from cdp.client.models.deploy_smart_contract_request import DeploySmartContractRequest from cdp.client.models.erc20_transfer_event import ERC20TransferEvent @@ -86,13 +87,12 @@ from cdp.client.models.ethereum_validator_metadata import EthereumValidatorMetadata from cdp.client.models.faucet_transaction import FaucetTransaction from cdp.client.models.feature_set import FeatureSet -from cdp.client.models.fetch_historical_staking_balances200_response import ( - FetchHistoricalStakingBalances200Response, -) +from cdp.client.models.fetch_historical_staking_balances200_response import FetchHistoricalStakingBalances200Response from cdp.client.models.fetch_staking_rewards200_response import FetchStakingRewards200Response from cdp.client.models.fetch_staking_rewards_request import FetchStakingRewardsRequest from cdp.client.models.get_staking_context_request import GetStakingContextRequest from cdp.client.models.historical_balance import HistoricalBalance +from cdp.client.models.multi_token_contract_options import MultiTokenContractOptions from cdp.client.models.nft_contract_options import NFTContractOptions from cdp.client.models.network import Network from cdp.client.models.network_identifier import NetworkIdentifier @@ -107,9 +107,7 @@ from cdp.client.models.server_signer_list import ServerSignerList from cdp.client.models.signature_creation_event import SignatureCreationEvent from cdp.client.models.signature_creation_event_result import SignatureCreationEventResult -from cdp.client.models.signed_voluntary_exit_message_metadata import ( - SignedVoluntaryExitMessageMetadata, -) +from cdp.client.models.signed_voluntary_exit_message_metadata import SignedVoluntaryExitMessageMetadata from cdp.client.models.smart_contract import SmartContract from cdp.client.models.smart_contract_list import SmartContractList from cdp.client.models.smart_contract_options import SmartContractOptions diff --git a/cdp/client/api/__init__.py b/cdp/client/api/__init__.py index 4ebcc4a..28574b9 100644 --- a/cdp/client/api/__init__.py +++ b/cdp/client/api/__init__.py @@ -12,9 +12,11 @@ from cdp.client.api.smart_contracts_api import SmartContractsApi from cdp.client.api.stake_api import StakeApi from cdp.client.api.trades_api import TradesApi +from cdp.client.api.transaction_history_api import TransactionHistoryApi from cdp.client.api.transfers_api import TransfersApi from cdp.client.api.users_api import UsersApi from cdp.client.api.validators_api import ValidatorsApi from cdp.client.api.wallet_stake_api import WalletStakeApi from cdp.client.api.wallets_api import WalletsApi from cdp.client.api.webhooks_api import WebhooksApi + diff --git a/cdp/client/api/addresses_api.py b/cdp/client/api/addresses_api.py index 195cb57..3c6fedd 100644 --- a/cdp/client/api/addresses_api.py +++ b/cdp/client/api/addresses_api.py @@ -1,19 +1,24 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from typing import Annotated, Any + Do not edit the class manually. +""" # noqa: E501 -from pydantic import Field, StrictFloat, StrictInt, StrictStr, validate_call +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated -from cdp.client.api_client import ApiClient, RequestSerialized -from cdp.client.api_response import ApiResponse +from pydantic import Field, StrictInt, StrictStr +from typing import Optional +from typing_extensions import Annotated from cdp.client.models.address import Address from cdp.client.models.address_balance_list import AddressBalanceList from cdp.client.models.address_list import AddressList @@ -23,6 +28,9 @@ from cdp.client.models.faucet_transaction import FaucetTransaction from cdp.client.models.payload_signature import PayloadSignature from cdp.client.models.payload_signature_list import PayloadSignatureList + +from cdp.client.api_client import ApiClient, RequestSerialized +from cdp.client.api_response import ApiResponse from cdp.client.rest import RESTResponseType @@ -38,19 +46,23 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def create_address( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet to create the address in.") - ], - create_address_request: CreateAddressRequest | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet to create the address in.")], + create_address_request: Optional[CreateAddressRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Address: """Create a new address @@ -81,39 +93,47 @@ def create_address( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_address_serialize( wallet_id=wallet_id, create_address_request=create_address_request, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Address", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Address", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def create_address_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet to create the address in.") - ], - create_address_request: CreateAddressRequest | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet to create the address in.")], + create_address_request: Optional[CreateAddressRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[Address]: """Create a new address @@ -144,39 +164,47 @@ def create_address_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_address_serialize( wallet_id=wallet_id, create_address_request=create_address_request, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Address", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Address", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def create_address_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet to create the address in.") - ], - create_address_request: CreateAddressRequest | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet to create the address in.")], + create_address_request: Optional[CreateAddressRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Create a new address @@ -207,22 +235,27 @@ def create_address_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_address_serialize( wallet_id=wallet_id, create_address_request=create_address_request, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Address", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Address", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _create_address_serialize( self, wallet_id, @@ -232,20 +265,22 @@ def _create_address_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id # process the query parameters # process the header parameters # process the form parameters @@ -253,24 +288,36 @@ def _create_address_serialize( if create_address_request is not None: _body_params = create_address_request + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` if _content_type: - _header_params["Content-Type"] = _content_type + _header_params['Content-Type'] = _content_type else: - _default_content_type = self.api_client.select_header_content_type(["application/json"]) + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) if _default_content_type is not None: - _header_params["Content-Type"] = _default_content_type + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="POST", - resource_path="/v1/wallets/{wallet_id}/addresses", + method='POST', + resource_path='/v1/wallets/{wallet_id}/addresses', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -280,26 +327,29 @@ def _create_address_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def create_payload_signature( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The onchain address of the address to sign the payload with."), - ], - create_payload_signature_request: CreatePayloadSignatureRequest | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address to sign the payload with.")], + create_payload_signature_request: Optional[CreatePayloadSignatureRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> PayloadSignature: """Create a new payload signature. @@ -332,7 +382,8 @@ def create_payload_signature( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_payload_signature_serialize( wallet_id=wallet_id, address_id=address_id, @@ -340,36 +391,40 @@ def create_payload_signature( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "PayloadSignature", + _response_types_map: Dict[str, Optional[str]] = { + '200': "PayloadSignature", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def create_payload_signature_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The onchain address of the address to sign the payload with."), - ], - create_payload_signature_request: CreatePayloadSignatureRequest | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address to sign the payload with.")], + create_payload_signature_request: Optional[CreatePayloadSignatureRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[PayloadSignature]: """Create a new payload signature. @@ -402,7 +457,8 @@ def create_payload_signature_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_payload_signature_serialize( wallet_id=wallet_id, address_id=address_id, @@ -410,36 +466,40 @@ def create_payload_signature_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "PayloadSignature", + _response_types_map: Dict[str, Optional[str]] = { + '200': "PayloadSignature", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def create_payload_signature_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The onchain address of the address to sign the payload with."), - ], - create_payload_signature_request: CreatePayloadSignatureRequest | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address to sign the payload with.")], + create_payload_signature_request: Optional[CreatePayloadSignatureRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Create a new payload signature. @@ -472,7 +532,8 @@ def create_payload_signature_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_payload_signature_serialize( wallet_id=wallet_id, address_id=address_id, @@ -480,15 +541,19 @@ def create_payload_signature_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "PayloadSignature", + _response_types_map: Dict[str, Optional[str]] = { + '200': "PayloadSignature", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _create_payload_signature_serialize( self, wallet_id, @@ -499,22 +564,24 @@ def _create_payload_signature_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id # process the query parameters # process the header parameters # process the form parameters @@ -522,24 +589,36 @@ def _create_payload_signature_serialize( if create_payload_signature_request is not None: _body_params = create_payload_signature_request + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` if _content_type: - _header_params["Content-Type"] = _content_type + _header_params['Content-Type'] = _content_type else: - _default_content_type = self.api_client.select_header_content_type(["application/json"]) + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) if _default_content_type is not None: - _header_params["Content-Type"] = _default_content_type + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="POST", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/payload_signatures", + method='POST', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/payload_signatures', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -549,25 +628,28 @@ def _create_payload_signature_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def get_address( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The onchain address of the address that is being fetched."), - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address that is being fetched.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Address: """Get address by onchain address @@ -598,42 +680,47 @@ def get_address( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_address_serialize( wallet_id=wallet_id, address_id=address_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Address", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Address", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def get_address_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The onchain address of the address that is being fetched."), - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address that is being fetched.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[Address]: """Get address by onchain address @@ -664,42 +751,47 @@ def get_address_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_address_serialize( wallet_id=wallet_id, address_id=address_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Address", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Address", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def get_address_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The onchain address of the address that is being fetched."), - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address that is being fetched.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Get address by onchain address @@ -730,22 +822,27 @@ def get_address_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_address_serialize( wallet_id=wallet_id, address_id=address_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Address", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Address", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _get_address_serialize( self, wallet_id, @@ -755,37 +852,46 @@ def _get_address_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id # process the query parameters # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}", + method='GET', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -795,28 +901,29 @@ def _get_address_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def get_address_balance( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet to fetch the balance for") - ], - address_id: Annotated[ - StrictStr, - Field(description="The onchain address of the address that is being fetched."), - ], - asset_id: Annotated[ - StrictStr, Field(description="The symbol of the asset to fetch the balance for") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet to fetch the balance for")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address that is being fetched.")], + asset_id: Annotated[StrictStr, Field(description="The symbol of the asset to fetch the balance for")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Balance: """Get address balance for asset @@ -849,7 +956,8 @@ def get_address_balance( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_address_balance_serialize( wallet_id=wallet_id, address_id=address_id, @@ -857,38 +965,40 @@ def get_address_balance( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Balance", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Balance", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def get_address_balance_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet to fetch the balance for") - ], - address_id: Annotated[ - StrictStr, - Field(description="The onchain address of the address that is being fetched."), - ], - asset_id: Annotated[ - StrictStr, Field(description="The symbol of the asset to fetch the balance for") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet to fetch the balance for")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address that is being fetched.")], + asset_id: Annotated[StrictStr, Field(description="The symbol of the asset to fetch the balance for")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[Balance]: """Get address balance for asset @@ -921,7 +1031,8 @@ def get_address_balance_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_address_balance_serialize( wallet_id=wallet_id, address_id=address_id, @@ -929,38 +1040,40 @@ def get_address_balance_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Balance", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Balance", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def get_address_balance_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet to fetch the balance for") - ], - address_id: Annotated[ - StrictStr, - Field(description="The onchain address of the address that is being fetched."), - ], - asset_id: Annotated[ - StrictStr, Field(description="The symbol of the asset to fetch the balance for") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet to fetch the balance for")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address that is being fetched.")], + asset_id: Annotated[StrictStr, Field(description="The symbol of the asset to fetch the balance for")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Get address balance for asset @@ -993,7 +1106,8 @@ def get_address_balance_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_address_balance_serialize( wallet_id=wallet_id, address_id=address_id, @@ -1001,15 +1115,19 @@ def get_address_balance_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Balance", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Balance", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _get_address_balance_serialize( self, wallet_id, @@ -1020,39 +1138,48 @@ def _get_address_balance_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id if asset_id is not None: - _path_params["asset_id"] = asset_id + _path_params['asset_id'] = asset_id # process the query parameters # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/balances/{asset_id}", + method='GET', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/balances/{asset_id}', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -1062,28 +1189,29 @@ def _get_address_balance_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def get_payload_signature( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The onchain address of the address that signed the payload."), - ], - payload_signature_id: Annotated[ - StrictStr, Field(description="The ID of the payload signature to fetch.") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address that signed the payload.")], + payload_signature_id: Annotated[StrictStr, Field(description="The ID of the payload signature to fetch.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> PayloadSignature: """Get payload signature. @@ -1116,7 +1244,8 @@ def get_payload_signature( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_payload_signature_serialize( wallet_id=wallet_id, address_id=address_id, @@ -1124,38 +1253,40 @@ def get_payload_signature( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "PayloadSignature", + _response_types_map: Dict[str, Optional[str]] = { + '200': "PayloadSignature", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def get_payload_signature_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The onchain address of the address that signed the payload."), - ], - payload_signature_id: Annotated[ - StrictStr, Field(description="The ID of the payload signature to fetch.") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address that signed the payload.")], + payload_signature_id: Annotated[StrictStr, Field(description="The ID of the payload signature to fetch.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[PayloadSignature]: """Get payload signature. @@ -1188,7 +1319,8 @@ def get_payload_signature_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_payload_signature_serialize( wallet_id=wallet_id, address_id=address_id, @@ -1196,38 +1328,40 @@ def get_payload_signature_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "PayloadSignature", + _response_types_map: Dict[str, Optional[str]] = { + '200': "PayloadSignature", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def get_payload_signature_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The onchain address of the address that signed the payload."), - ], - payload_signature_id: Annotated[ - StrictStr, Field(description="The ID of the payload signature to fetch.") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address that signed the payload.")], + payload_signature_id: Annotated[StrictStr, Field(description="The ID of the payload signature to fetch.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Get payload signature. @@ -1260,7 +1394,8 @@ def get_payload_signature_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_payload_signature_serialize( wallet_id=wallet_id, address_id=address_id, @@ -1268,15 +1403,19 @@ def get_payload_signature_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "PayloadSignature", + _response_types_map: Dict[str, Optional[str]] = { + '200': "PayloadSignature", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _get_payload_signature_serialize( self, wallet_id, @@ -1287,39 +1426,48 @@ def _get_payload_signature_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id if payload_signature_id is not None: - _path_params["payload_signature_id"] = payload_signature_id + _path_params['payload_signature_id'] = payload_signature_id # process the query parameters # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/payload_signatures/{payload_signature_id}", + method='GET', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/payload_signatures/{payload_signature_id}', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -1329,31 +1477,29 @@ def _get_payload_signature_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def list_address_balances( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet to fetch the balances for") - ], - address_id: Annotated[ - StrictStr, - Field(description="The onchain address of the address that is being fetched."), - ], - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet to fetch the balances for")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address that is being fetched.")], + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> AddressBalanceList: """Get all balances for address @@ -1386,7 +1532,8 @@ def list_address_balances( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_address_balances_serialize( wallet_id=wallet_id, address_id=address_id, @@ -1394,41 +1541,40 @@ def list_address_balances( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "AddressBalanceList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressBalanceList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def list_address_balances_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet to fetch the balances for") - ], - address_id: Annotated[ - StrictStr, - Field(description="The onchain address of the address that is being fetched."), - ], - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet to fetch the balances for")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address that is being fetched.")], + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[AddressBalanceList]: """Get all balances for address @@ -1461,7 +1607,8 @@ def list_address_balances_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_address_balances_serialize( wallet_id=wallet_id, address_id=address_id, @@ -1469,41 +1616,40 @@ def list_address_balances_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "AddressBalanceList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressBalanceList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def list_address_balances_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet to fetch the balances for") - ], - address_id: Annotated[ - StrictStr, - Field(description="The onchain address of the address that is being fetched."), - ], - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet to fetch the balances for")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address that is being fetched.")], + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Get all balances for address @@ -1536,7 +1682,8 @@ def list_address_balances_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_address_balances_serialize( wallet_id=wallet_id, address_id=address_id, @@ -1544,15 +1691,19 @@ def list_address_balances_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "AddressBalanceList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressBalanceList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _list_address_balances_serialize( self, wallet_id, @@ -1563,40 +1714,50 @@ def _list_address_balances_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id # process the query parameters if page is not None: - _query_params.append(("page", page)) - + + _query_params.append(('page', page)) + # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/balances", + method='GET', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/balances', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -1606,33 +1767,29 @@ def _list_address_balances_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def list_addresses( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet whose addresses to fetch") - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet whose addresses to fetch")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> AddressList: """List addresses in a wallet. @@ -1665,7 +1822,8 @@ def list_addresses( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_addresses_serialize( wallet_id=wallet_id, limit=limit, @@ -1673,43 +1831,40 @@ def list_addresses( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "AddressList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def list_addresses_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet whose addresses to fetch") - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet whose addresses to fetch")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), - ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[AddressList]: """List addresses in a wallet. @@ -1742,7 +1897,8 @@ def list_addresses_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_addresses_serialize( wallet_id=wallet_id, limit=limit, @@ -1750,43 +1906,40 @@ def list_addresses_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "AddressList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def list_addresses_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet whose addresses to fetch") - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet whose addresses to fetch")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """List addresses in a wallet. @@ -1819,7 +1972,8 @@ def list_addresses_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_addresses_serialize( wallet_id=wallet_id, limit=limit, @@ -1827,15 +1981,19 @@ def list_addresses_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "AddressList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _list_addresses_serialize( self, wallet_id, @@ -1846,41 +2004,52 @@ def _list_addresses_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id # process the query parameters if limit is not None: - _query_params.append(("limit", limit)) - + + _query_params.append(('limit', limit)) + if page is not None: - _query_params.append(("page", page)) - + + _query_params.append(('page', page)) + # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/wallets/{wallet_id}/addresses", + method='GET', + resource_path='/v1/wallets/{wallet_id}/addresses', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -1890,39 +2059,30 @@ def _list_addresses_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def list_payload_signatures( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field( - description="The onchain address of the address whose payload signatures to fetch." - ), - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address whose payload signatures to fetch.")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> PayloadSignatureList: """List payload signatures for an address. @@ -1957,7 +2117,8 @@ def list_payload_signatures( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_payload_signatures_serialize( wallet_id=wallet_id, address_id=address_id, @@ -1966,49 +2127,41 @@ def list_payload_signatures( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "PayloadSignatureList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "PayloadSignatureList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def list_payload_signatures_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field( - description="The onchain address of the address whose payload signatures to fetch." - ), - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address whose payload signatures to fetch.")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[PayloadSignatureList]: """List payload signatures for an address. @@ -2043,7 +2196,8 @@ def list_payload_signatures_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_payload_signatures_serialize( wallet_id=wallet_id, address_id=address_id, @@ -2052,49 +2206,41 @@ def list_payload_signatures_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "PayloadSignatureList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "PayloadSignatureList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def list_payload_signatures_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field( - description="The onchain address of the address whose payload signatures to fetch." - ), - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address whose payload signatures to fetch.")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), - ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """List payload signatures for an address. @@ -2129,7 +2275,8 @@ def list_payload_signatures_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_payload_signatures_serialize( wallet_id=wallet_id, address_id=address_id, @@ -2138,15 +2285,19 @@ def list_payload_signatures_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "PayloadSignatureList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "PayloadSignatureList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _list_payload_signatures_serialize( self, wallet_id, @@ -2158,43 +2309,54 @@ def _list_payload_signatures_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id # process the query parameters if limit is not None: - _query_params.append(("limit", limit)) - + + _query_params.append(('limit', limit)) + if page is not None: - _query_params.append(("page", page)) - + + _query_params.append(('page', page)) + # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/payload_signatures", + method='GET', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/payload_signatures', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -2204,28 +2366,29 @@ def _list_payload_signatures_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def request_faucet_funds( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The onchain address of the address that is being fetched."), - ], - asset_id: Annotated[ - StrictStr | None, Field(description="The ID of the asset to transfer from the faucet.") + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address that is being fetched.")], + asset_id: Annotated[Optional[StrictStr], Field(description="The ID of the asset to transfer from the faucet.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> FaucetTransaction: """Request faucet funds for onchain address. @@ -2258,7 +2421,8 @@ def request_faucet_funds( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._request_faucet_funds_serialize( wallet_id=wallet_id, address_id=address_id, @@ -2266,38 +2430,40 @@ def request_faucet_funds( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "FaucetTransaction", + _response_types_map: Dict[str, Optional[str]] = { + '200': "FaucetTransaction", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def request_faucet_funds_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The onchain address of the address that is being fetched."), - ], - asset_id: Annotated[ - StrictStr | None, Field(description="The ID of the asset to transfer from the faucet.") + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address that is being fetched.")], + asset_id: Annotated[Optional[StrictStr], Field(description="The ID of the asset to transfer from the faucet.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[FaucetTransaction]: """Request faucet funds for onchain address. @@ -2330,7 +2496,8 @@ def request_faucet_funds_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._request_faucet_funds_serialize( wallet_id=wallet_id, address_id=address_id, @@ -2338,38 +2505,40 @@ def request_faucet_funds_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "FaucetTransaction", + _response_types_map: Dict[str, Optional[str]] = { + '200': "FaucetTransaction", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def request_faucet_funds_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The onchain address of the address that is being fetched."), - ], - asset_id: Annotated[ - StrictStr | None, Field(description="The ID of the asset to transfer from the faucet.") + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address that is being fetched.")], + asset_id: Annotated[Optional[StrictStr], Field(description="The ID of the asset to transfer from the faucet.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Request faucet funds for onchain address. @@ -2402,7 +2571,8 @@ def request_faucet_funds_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._request_faucet_funds_serialize( wallet_id=wallet_id, address_id=address_id, @@ -2410,15 +2580,19 @@ def request_faucet_funds_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "FaucetTransaction", + _response_types_map: Dict[str, Optional[str]] = { + '200': "FaucetTransaction", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _request_faucet_funds_serialize( self, wallet_id, @@ -2429,40 +2603,50 @@ def _request_faucet_funds_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id # process the query parameters if asset_id is not None: - _query_params.append(("asset_id", asset_id)) - + + _query_params.append(('asset_id', asset_id)) + # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="POST", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/faucet", + method='POST', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/faucet', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -2472,5 +2656,7 @@ def _request_faucet_funds_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + diff --git a/cdp/client/api/assets_api.py b/cdp/client/api/assets_api.py index c5fd410..874b2dc 100644 --- a/cdp/client/api/assets_api.py +++ b/cdp/client/api/assets_api.py @@ -1,20 +1,27 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 -from typing import Annotated, Any +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated -from pydantic import Field, StrictFloat, StrictInt, StrictStr, validate_call +from pydantic import Field, StrictStr +from typing_extensions import Annotated +from cdp.client.models.asset import Asset from cdp.client.api_client import ApiClient, RequestSerialized from cdp.client.api_response import ApiResponse -from cdp.client.models.asset import Asset from cdp.client.rest import RESTResponseType @@ -30,22 +37,23 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def get_asset( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], - asset_id: Annotated[ - StrictStr, - Field( - description="The ID of the asset to fetch. This could be a symbol or an ERC20 contract address." - ), - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + asset_id: Annotated[StrictStr, Field(description="The ID of the asset to fetch. This could be a symbol or an ERC20 contract address.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Asset: """Get the asset for the specified asset ID. @@ -76,42 +84,47 @@ def get_asset( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_asset_serialize( network_id=network_id, asset_id=asset_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Asset", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Asset", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def get_asset_with_http_info( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], - asset_id: Annotated[ - StrictStr, - Field( - description="The ID of the asset to fetch. This could be a symbol or an ERC20 contract address." - ), - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + asset_id: Annotated[StrictStr, Field(description="The ID of the asset to fetch. This could be a symbol or an ERC20 contract address.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[Asset]: """Get the asset for the specified asset ID. @@ -142,42 +155,47 @@ def get_asset_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_asset_serialize( network_id=network_id, asset_id=asset_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Asset", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Asset", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def get_asset_without_preload_content( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], - asset_id: Annotated[ - StrictStr, - Field( - description="The ID of the asset to fetch. This could be a symbol or an ERC20 contract address." - ), - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + asset_id: Annotated[StrictStr, Field(description="The ID of the asset to fetch. This could be a symbol or an ERC20 contract address.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Get the asset for the specified asset ID. @@ -208,22 +226,27 @@ def get_asset_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_asset_serialize( network_id=network_id, asset_id=asset_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Asset", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Asset", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _get_asset_serialize( self, network_id, @@ -233,37 +256,46 @@ def _get_asset_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if network_id is not None: - _path_params["network_id"] = network_id + _path_params['network_id'] = network_id if asset_id is not None: - _path_params["asset_id"] = asset_id + _path_params['asset_id'] = asset_id # process the query parameters # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/networks/{network_id}/assets/{asset_id}", + method='GET', + resource_path='/v1/networks/{network_id}/assets/{asset_id}', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -273,5 +305,7 @@ def _get_asset_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + diff --git a/cdp/client/api/balance_history_api.py b/cdp/client/api/balance_history_api.py index e4b0691..c0eaf82 100644 --- a/cdp/client/api/balance_history_api.py +++ b/cdp/client/api/balance_history_api.py @@ -1,20 +1,28 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from typing import Annotated, Any + Do not edit the class manually. +""" # noqa: E501 -from pydantic import Field, StrictFloat, StrictInt, StrictStr, validate_call +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from pydantic import Field, StrictInt, StrictStr +from typing import Optional +from typing_extensions import Annotated +from cdp.client.models.address_historical_balance_list import AddressHistoricalBalanceList from cdp.client.api_client import ApiClient, RequestSerialized from cdp.client.api_response import ApiResponse -from cdp.client.models.address_historical_balance_list import AddressHistoricalBalanceList from cdp.client.rest import RESTResponseType @@ -30,36 +38,26 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def list_address_historical_balance( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], - address_id: Annotated[ - StrictStr, - Field(description="The ID of the address to fetch the historical balance for."), - ], - asset_id: Annotated[ - StrictStr, - Field(description="The symbol of the asset to fetch the historical balance for."), - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the historical balance for.")], + asset_id: Annotated[StrictStr, Field(description="The symbol of the asset to fetch the historical balance for.")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), - ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> AddressHistoricalBalanceList: """Get address balance history for asset @@ -96,7 +94,8 @@ def list_address_historical_balance( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_address_historical_balance_serialize( network_id=network_id, address_id=address_id, @@ -106,49 +105,42 @@ def list_address_historical_balance( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "AddressHistoricalBalanceList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressHistoricalBalanceList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def list_address_historical_balance_with_http_info( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], - address_id: Annotated[ - StrictStr, - Field(description="The ID of the address to fetch the historical balance for."), - ], - asset_id: Annotated[ - StrictStr, - Field(description="The symbol of the asset to fetch the historical balance for."), - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the historical balance for.")], + asset_id: Annotated[StrictStr, Field(description="The symbol of the asset to fetch the historical balance for.")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), - ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[AddressHistoricalBalanceList]: """Get address balance history for asset @@ -185,7 +177,8 @@ def list_address_historical_balance_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_address_historical_balance_serialize( network_id=network_id, address_id=address_id, @@ -195,49 +188,42 @@ def list_address_historical_balance_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "AddressHistoricalBalanceList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressHistoricalBalanceList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def list_address_historical_balance_without_preload_content( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], - address_id: Annotated[ - StrictStr, - Field(description="The ID of the address to fetch the historical balance for."), - ], - asset_id: Annotated[ - StrictStr, - Field(description="The symbol of the asset to fetch the historical balance for."), - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the historical balance for.")], + asset_id: Annotated[StrictStr, Field(description="The symbol of the asset to fetch the historical balance for.")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Get address balance history for asset @@ -274,7 +260,8 @@ def list_address_historical_balance_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_address_historical_balance_serialize( network_id=network_id, address_id=address_id, @@ -284,15 +271,19 @@ def list_address_historical_balance_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "AddressHistoricalBalanceList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressHistoricalBalanceList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _list_address_historical_balance_serialize( self, network_id, @@ -305,45 +296,56 @@ def _list_address_historical_balance_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if network_id is not None: - _path_params["network_id"] = network_id + _path_params['network_id'] = network_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id if asset_id is not None: - _path_params["asset_id"] = asset_id + _path_params['asset_id'] = asset_id # process the query parameters if limit is not None: - _query_params.append(("limit", limit)) - + + _query_params.append(('limit', limit)) + if page is not None: - _query_params.append(("page", page)) - + + _query_params.append(('page', page)) + # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/networks/{network_id}/addresses/{address_id}/balance_history/{asset_id}", + method='GET', + resource_path='/v1/networks/{network_id}/addresses/{address_id}/balance_history/{asset_id}', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -353,5 +355,7 @@ def _list_address_historical_balance_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + diff --git a/cdp/client/api/contract_events_api.py b/cdp/client/api/contract_events_api.py index fc20a93..a9b88d4 100644 --- a/cdp/client/api/contract_events_api.py +++ b/cdp/client/api/contract_events_api.py @@ -1,20 +1,28 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 -from typing import Annotated, Any +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated -from pydantic import Field, StrictFloat, StrictInt, StrictStr, validate_call +from pydantic import Field, StrictInt, StrictStr +from typing import Optional +from typing_extensions import Annotated +from cdp.client.models.contract_event_list import ContractEventList from cdp.client.api_client import ApiClient, RequestSerialized from cdp.client.api_response import ApiResponse -from cdp.client.models.contract_event_list import ContractEventList from cdp.client.rest import RESTResponseType @@ -30,47 +38,29 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def list_contract_events( self, - network_id: Annotated[ - StrictStr, Field(description="Unique identifier for the blockchain network") - ], - protocol_name: Annotated[ - StrictStr, Field(description="Case-sensitive name of the blockchain protocol") - ], - contract_address: Annotated[ - StrictStr, - Field( - description="EVM address of the smart contract (42 characters, including '0x', in lowercase)" - ), - ], - contract_name: Annotated[ - StrictStr, - Field(description="Case-sensitive name of the specific contract within the project"), - ], - event_name: Annotated[ - StrictStr, - Field( - description="Case-sensitive name of the event to filter for in the contract's logs" - ), - ], - from_block_height: Annotated[ - StrictInt, Field(description="Lower bound of the block range to query (inclusive)") - ], - to_block_height: Annotated[ - StrictInt, Field(description="Upper bound of the block range to query (inclusive)") - ], - next_page: Annotated[ - StrictStr | None, - Field(description="Pagination token for retrieving the next set of results"), + network_id: Annotated[StrictStr, Field(description="Unique identifier for the blockchain network")], + protocol_name: Annotated[StrictStr, Field(description="Case-sensitive name of the blockchain protocol")], + contract_address: Annotated[StrictStr, Field(description="EVM address of the smart contract (42 characters, including '0x', in lowercase)")], + contract_name: Annotated[StrictStr, Field(description="Case-sensitive name of the specific contract within the project")], + event_name: Annotated[StrictStr, Field(description="Case-sensitive name of the event to filter for in the contract's logs")], + from_block_height: Annotated[StrictInt, Field(description="Lower bound of the block range to query (inclusive)")], + to_block_height: Annotated[StrictInt, Field(description="Upper bound of the block range to query (inclusive)")], + next_page: Annotated[Optional[StrictStr], Field(description="Pagination token for retrieving the next set of results")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ContractEventList: """List contract events @@ -113,7 +103,8 @@ def list_contract_events( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_contract_events_serialize( network_id=network_id, protocol_name=protocol_name, @@ -126,60 +117,45 @@ def list_contract_events( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ContractEventList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ContractEventList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def list_contract_events_with_http_info( self, - network_id: Annotated[ - StrictStr, Field(description="Unique identifier for the blockchain network") - ], - protocol_name: Annotated[ - StrictStr, Field(description="Case-sensitive name of the blockchain protocol") - ], - contract_address: Annotated[ - StrictStr, - Field( - description="EVM address of the smart contract (42 characters, including '0x', in lowercase)" - ), - ], - contract_name: Annotated[ - StrictStr, - Field(description="Case-sensitive name of the specific contract within the project"), - ], - event_name: Annotated[ - StrictStr, - Field( - description="Case-sensitive name of the event to filter for in the contract's logs" - ), - ], - from_block_height: Annotated[ - StrictInt, Field(description="Lower bound of the block range to query (inclusive)") - ], - to_block_height: Annotated[ - StrictInt, Field(description="Upper bound of the block range to query (inclusive)") - ], - next_page: Annotated[ - StrictStr | None, - Field(description="Pagination token for retrieving the next set of results"), + network_id: Annotated[StrictStr, Field(description="Unique identifier for the blockchain network")], + protocol_name: Annotated[StrictStr, Field(description="Case-sensitive name of the blockchain protocol")], + contract_address: Annotated[StrictStr, Field(description="EVM address of the smart contract (42 characters, including '0x', in lowercase)")], + contract_name: Annotated[StrictStr, Field(description="Case-sensitive name of the specific contract within the project")], + event_name: Annotated[StrictStr, Field(description="Case-sensitive name of the event to filter for in the contract's logs")], + from_block_height: Annotated[StrictInt, Field(description="Lower bound of the block range to query (inclusive)")], + to_block_height: Annotated[StrictInt, Field(description="Upper bound of the block range to query (inclusive)")], + next_page: Annotated[Optional[StrictStr], Field(description="Pagination token for retrieving the next set of results")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[ContractEventList]: """List contract events @@ -222,7 +198,8 @@ def list_contract_events_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_contract_events_serialize( network_id=network_id, protocol_name=protocol_name, @@ -235,60 +212,45 @@ def list_contract_events_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ContractEventList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ContractEventList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def list_contract_events_without_preload_content( self, - network_id: Annotated[ - StrictStr, Field(description="Unique identifier for the blockchain network") - ], - protocol_name: Annotated[ - StrictStr, Field(description="Case-sensitive name of the blockchain protocol") - ], - contract_address: Annotated[ - StrictStr, - Field( - description="EVM address of the smart contract (42 characters, including '0x', in lowercase)" - ), - ], - contract_name: Annotated[ - StrictStr, - Field(description="Case-sensitive name of the specific contract within the project"), - ], - event_name: Annotated[ - StrictStr, - Field( - description="Case-sensitive name of the event to filter for in the contract's logs" - ), - ], - from_block_height: Annotated[ - StrictInt, Field(description="Lower bound of the block range to query (inclusive)") - ], - to_block_height: Annotated[ - StrictInt, Field(description="Upper bound of the block range to query (inclusive)") - ], - next_page: Annotated[ - StrictStr | None, - Field(description="Pagination token for retrieving the next set of results"), + network_id: Annotated[StrictStr, Field(description="Unique identifier for the blockchain network")], + protocol_name: Annotated[StrictStr, Field(description="Case-sensitive name of the blockchain protocol")], + contract_address: Annotated[StrictStr, Field(description="EVM address of the smart contract (42 characters, including '0x', in lowercase)")], + contract_name: Annotated[StrictStr, Field(description="Case-sensitive name of the specific contract within the project")], + event_name: Annotated[StrictStr, Field(description="Case-sensitive name of the event to filter for in the contract's logs")], + from_block_height: Annotated[StrictInt, Field(description="Lower bound of the block range to query (inclusive)")], + to_block_height: Annotated[StrictInt, Field(description="Upper bound of the block range to query (inclusive)")], + next_page: Annotated[Optional[StrictStr], Field(description="Pagination token for retrieving the next set of results")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """List contract events @@ -331,7 +293,8 @@ def list_contract_events_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_contract_events_serialize( network_id=network_id, protocol_name=protocol_name, @@ -344,15 +307,19 @@ def list_contract_events_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ContractEventList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ContractEventList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _list_contract_events_serialize( self, network_id, @@ -368,55 +335,70 @@ def _list_contract_events_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if network_id is not None: - _path_params["network_id"] = network_id + _path_params['network_id'] = network_id if contract_address is not None: - _path_params["contract_address"] = contract_address + _path_params['contract_address'] = contract_address # process the query parameters if protocol_name is not None: - _query_params.append(("protocol_name", protocol_name)) - + + _query_params.append(('protocol_name', protocol_name)) + if contract_name is not None: - _query_params.append(("contract_name", contract_name)) - + + _query_params.append(('contract_name', contract_name)) + if event_name is not None: - _query_params.append(("event_name", event_name)) - + + _query_params.append(('event_name', event_name)) + if from_block_height is not None: - _query_params.append(("from_block_height", from_block_height)) - + + _query_params.append(('from_block_height', from_block_height)) + if to_block_height is not None: - _query_params.append(("to_block_height", to_block_height)) - + + _query_params.append(('to_block_height', to_block_height)) + if next_page is not None: - _query_params.append(("next_page", next_page)) - + + _query_params.append(('next_page', next_page)) + # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/networks/{network_id}/smart_contracts/{contract_address}/events", + method='GET', + resource_path='/v1/networks/{network_id}/smart_contracts/{contract_address}/events', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -426,5 +408,7 @@ def _list_contract_events_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + diff --git a/cdp/client/api/contract_invocations_api.py b/cdp/client/api/contract_invocations_api.py index c77a02c..d4330fa 100644 --- a/cdp/client/api/contract_invocations_api.py +++ b/cdp/client/api/contract_invocations_api.py @@ -1,25 +1,31 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from typing import Annotated, Any + Do not edit the class manually. +""" # noqa: E501 -from pydantic import Field, StrictFloat, StrictInt, StrictStr, validate_call +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated -from cdp.client.api_client import ApiClient, RequestSerialized -from cdp.client.api_response import ApiResponse -from cdp.client.models.broadcast_contract_invocation_request import ( - BroadcastContractInvocationRequest, -) +from pydantic import Field, StrictInt, StrictStr +from typing import Optional +from typing_extensions import Annotated +from cdp.client.models.broadcast_contract_invocation_request import BroadcastContractInvocationRequest from cdp.client.models.contract_invocation import ContractInvocation from cdp.client.models.contract_invocation_list import ContractInvocationList from cdp.client.models.create_contract_invocation_request import CreateContractInvocationRequest + +from cdp.client.api_client import ApiClient, RequestSerialized +from cdp.client.api_response import ApiResponse from cdp.client.rest import RESTResponseType @@ -35,26 +41,25 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def broadcast_contract_invocation( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The ID of the address the contract invocation belongs to."), - ], - contract_invocation_id: Annotated[ - StrictStr, Field(description="The ID of the contract invocation to broadcast.") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the contract invocation belongs to.")], + contract_invocation_id: Annotated[StrictStr, Field(description="The ID of the contract invocation to broadcast.")], broadcast_contract_invocation_request: BroadcastContractInvocationRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ContractInvocation: """Broadcast a contract invocation. @@ -89,7 +94,8 @@ def broadcast_contract_invocation( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._broadcast_contract_invocation_serialize( wallet_id=wallet_id, address_id=address_id, @@ -98,39 +104,41 @@ def broadcast_contract_invocation( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ContractInvocation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ContractInvocation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def broadcast_contract_invocation_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The ID of the address the contract invocation belongs to."), - ], - contract_invocation_id: Annotated[ - StrictStr, Field(description="The ID of the contract invocation to broadcast.") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the contract invocation belongs to.")], + contract_invocation_id: Annotated[StrictStr, Field(description="The ID of the contract invocation to broadcast.")], broadcast_contract_invocation_request: BroadcastContractInvocationRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[ContractInvocation]: """Broadcast a contract invocation. @@ -165,7 +173,8 @@ def broadcast_contract_invocation_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._broadcast_contract_invocation_serialize( wallet_id=wallet_id, address_id=address_id, @@ -174,39 +183,41 @@ def broadcast_contract_invocation_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ContractInvocation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ContractInvocation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def broadcast_contract_invocation_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The ID of the address the contract invocation belongs to."), - ], - contract_invocation_id: Annotated[ - StrictStr, Field(description="The ID of the contract invocation to broadcast.") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the contract invocation belongs to.")], + contract_invocation_id: Annotated[StrictStr, Field(description="The ID of the contract invocation to broadcast.")], broadcast_contract_invocation_request: BroadcastContractInvocationRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Broadcast a contract invocation. @@ -241,7 +252,8 @@ def broadcast_contract_invocation_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._broadcast_contract_invocation_serialize( wallet_id=wallet_id, address_id=address_id, @@ -250,15 +262,19 @@ def broadcast_contract_invocation_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ContractInvocation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ContractInvocation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _broadcast_contract_invocation_serialize( self, wallet_id, @@ -270,24 +286,26 @@ def _broadcast_contract_invocation_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id if contract_invocation_id is not None: - _path_params["contract_invocation_id"] = contract_invocation_id + _path_params['contract_invocation_id'] = contract_invocation_id # process the query parameters # process the header parameters # process the form parameters @@ -295,24 +313,36 @@ def _broadcast_contract_invocation_serialize( if broadcast_contract_invocation_request is not None: _body_params = broadcast_contract_invocation_request + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` if _content_type: - _header_params["Content-Type"] = _content_type + _header_params['Content-Type'] = _content_type else: - _default_content_type = self.api_client.select_header_content_type(["application/json"]) + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) if _default_content_type is not None: - _header_params["Content-Type"] = _default_content_type + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="POST", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/contract_invocations/{contract_invocation_id}/broadcast", + method='POST', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/contract_invocations/{contract_invocation_id}/broadcast', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -322,25 +352,29 @@ def _broadcast_contract_invocation_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def create_contract_invocation( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the source address belongs to.") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to invoke the contract from.") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the source address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to invoke the contract from.")], create_contract_invocation_request: CreateContractInvocationRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ContractInvocation: """Create a new contract invocation for an address. @@ -373,7 +407,8 @@ def create_contract_invocation( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_contract_invocation_serialize( wallet_id=wallet_id, address_id=address_id, @@ -381,35 +416,40 @@ def create_contract_invocation( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ContractInvocation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ContractInvocation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def create_contract_invocation_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the source address belongs to.") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to invoke the contract from.") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the source address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to invoke the contract from.")], create_contract_invocation_request: CreateContractInvocationRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[ContractInvocation]: """Create a new contract invocation for an address. @@ -442,7 +482,8 @@ def create_contract_invocation_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_contract_invocation_serialize( wallet_id=wallet_id, address_id=address_id, @@ -450,35 +491,40 @@ def create_contract_invocation_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ContractInvocation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ContractInvocation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def create_contract_invocation_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the source address belongs to.") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to invoke the contract from.") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the source address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to invoke the contract from.")], create_contract_invocation_request: CreateContractInvocationRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Create a new contract invocation for an address. @@ -511,7 +557,8 @@ def create_contract_invocation_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_contract_invocation_serialize( wallet_id=wallet_id, address_id=address_id, @@ -519,15 +566,19 @@ def create_contract_invocation_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ContractInvocation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ContractInvocation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _create_contract_invocation_serialize( self, wallet_id, @@ -538,22 +589,24 @@ def _create_contract_invocation_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id # process the query parameters # process the header parameters # process the form parameters @@ -561,24 +614,36 @@ def _create_contract_invocation_serialize( if create_contract_invocation_request is not None: _body_params = create_contract_invocation_request + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` if _content_type: - _header_params["Content-Type"] = _content_type + _header_params['Content-Type'] = _content_type else: - _default_content_type = self.api_client.select_header_content_type(["application/json"]) + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) if _default_content_type is not None: - _header_params["Content-Type"] = _default_content_type + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="POST", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/contract_invocations", + method='POST', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/contract_invocations', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -588,28 +653,29 @@ def _create_contract_invocation_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def get_contract_invocation( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The ID of the address the contract invocation belongs to."), - ], - contract_invocation_id: Annotated[ - StrictStr, Field(description="The ID of the contract invocation to fetch.") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the contract invocation belongs to.")], + contract_invocation_id: Annotated[StrictStr, Field(description="The ID of the contract invocation to fetch.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ContractInvocation: """Get a contract invocation by ID. @@ -642,7 +708,8 @@ def get_contract_invocation( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_contract_invocation_serialize( wallet_id=wallet_id, address_id=address_id, @@ -650,38 +717,40 @@ def get_contract_invocation( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ContractInvocation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ContractInvocation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def get_contract_invocation_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The ID of the address the contract invocation belongs to."), - ], - contract_invocation_id: Annotated[ - StrictStr, Field(description="The ID of the contract invocation to fetch.") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the contract invocation belongs to.")], + contract_invocation_id: Annotated[StrictStr, Field(description="The ID of the contract invocation to fetch.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[ContractInvocation]: """Get a contract invocation by ID. @@ -714,7 +783,8 @@ def get_contract_invocation_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_contract_invocation_serialize( wallet_id=wallet_id, address_id=address_id, @@ -722,38 +792,40 @@ def get_contract_invocation_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ContractInvocation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ContractInvocation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def get_contract_invocation_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The ID of the address the contract invocation belongs to."), - ], - contract_invocation_id: Annotated[ - StrictStr, Field(description="The ID of the contract invocation to fetch.") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the contract invocation belongs to.")], + contract_invocation_id: Annotated[StrictStr, Field(description="The ID of the contract invocation to fetch.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Get a contract invocation by ID. @@ -786,7 +858,8 @@ def get_contract_invocation_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_contract_invocation_serialize( wallet_id=wallet_id, address_id=address_id, @@ -794,15 +867,19 @@ def get_contract_invocation_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ContractInvocation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ContractInvocation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _get_contract_invocation_serialize( self, wallet_id, @@ -813,39 +890,48 @@ def _get_contract_invocation_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id if contract_invocation_id is not None: - _path_params["contract_invocation_id"] = contract_invocation_id + _path_params['contract_invocation_id'] = contract_invocation_id # process the query parameters # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/contract_invocations/{contract_invocation_id}", + method='GET', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/contract_invocations/{contract_invocation_id}', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -855,36 +941,30 @@ def _get_contract_invocation_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def list_contract_invocations( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to list contract invocations for.") - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to list contract invocations for.")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ContractInvocationList: """List contract invocations for an address. @@ -919,7 +999,8 @@ def list_contract_invocations( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_contract_invocations_serialize( wallet_id=wallet_id, address_id=address_id, @@ -928,46 +1009,41 @@ def list_contract_invocations( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ContractInvocationList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ContractInvocationList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def list_contract_invocations_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to list contract invocations for.") - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to list contract invocations for.")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[ContractInvocationList]: """List contract invocations for an address. @@ -1002,7 +1078,8 @@ def list_contract_invocations_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_contract_invocations_serialize( wallet_id=wallet_id, address_id=address_id, @@ -1011,46 +1088,41 @@ def list_contract_invocations_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ContractInvocationList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ContractInvocationList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def list_contract_invocations_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to list contract invocations for.") - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to list contract invocations for.")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), - ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """List contract invocations for an address. @@ -1085,7 +1157,8 @@ def list_contract_invocations_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_contract_invocations_serialize( wallet_id=wallet_id, address_id=address_id, @@ -1094,15 +1167,19 @@ def list_contract_invocations_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ContractInvocationList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ContractInvocationList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _list_contract_invocations_serialize( self, wallet_id, @@ -1114,43 +1191,54 @@ def _list_contract_invocations_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id # process the query parameters if limit is not None: - _query_params.append(("limit", limit)) - + + _query_params.append(('limit', limit)) + if page is not None: - _query_params.append(("page", page)) - + + _query_params.append(('page', page)) + # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/contract_invocations", + method='GET', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/contract_invocations', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -1160,5 +1248,7 @@ def _list_contract_invocations_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + diff --git a/cdp/client/api/external_addresses_api.py b/cdp/client/api/external_addresses_api.py index 5a8b065..197bf46 100644 --- a/cdp/client/api/external_addresses_api.py +++ b/cdp/client/api/external_addresses_api.py @@ -1,23 +1,30 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from typing import Annotated, Any + Do not edit the class manually. +""" # noqa: E501 -from pydantic import Field, StrictFloat, StrictInt, StrictStr, validate_call +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated -from cdp.client.api_client import ApiClient, RequestSerialized -from cdp.client.api_response import ApiResponse +from pydantic import Field, StrictStr +from typing import Optional +from typing_extensions import Annotated from cdp.client.models.address_balance_list import AddressBalanceList -from cdp.client.models.address_transaction_list import AddressTransactionList from cdp.client.models.balance import Balance from cdp.client.models.faucet_transaction import FaucetTransaction + +from cdp.client.api_client import ApiClient, RequestSerialized +from cdp.client.api_response import ApiResponse from cdp.client.rest import RESTResponseType @@ -33,22 +40,24 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def get_external_address_balance( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to fetch the balance for") - ], - asset_id: Annotated[ - StrictStr, Field(description="The ID of the asset to fetch the balance for") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the balance for")], + asset_id: Annotated[StrictStr, Field(description="The ID of the asset to fetch the balance for")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Balance: """Get the balance of an asset in an external address @@ -81,7 +90,8 @@ def get_external_address_balance( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_external_address_balance_serialize( network_id=network_id, address_id=address_id, @@ -89,35 +99,40 @@ def get_external_address_balance( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Balance", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Balance", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def get_external_address_balance_with_http_info( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to fetch the balance for") - ], - asset_id: Annotated[ - StrictStr, Field(description="The ID of the asset to fetch the balance for") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the balance for")], + asset_id: Annotated[StrictStr, Field(description="The ID of the asset to fetch the balance for")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[Balance]: """Get the balance of an asset in an external address @@ -150,7 +165,8 @@ def get_external_address_balance_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_external_address_balance_serialize( network_id=network_id, address_id=address_id, @@ -158,35 +174,40 @@ def get_external_address_balance_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Balance", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Balance", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def get_external_address_balance_without_preload_content( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to fetch the balance for") - ], - asset_id: Annotated[ - StrictStr, Field(description="The ID of the asset to fetch the balance for") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the balance for")], + asset_id: Annotated[StrictStr, Field(description="The ID of the asset to fetch the balance for")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Get the balance of an asset in an external address @@ -219,7 +240,8 @@ def get_external_address_balance_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_external_address_balance_serialize( network_id=network_id, address_id=address_id, @@ -227,15 +249,19 @@ def get_external_address_balance_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Balance", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Balance", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _get_external_address_balance_serialize( self, network_id, @@ -246,39 +272,48 @@ def _get_external_address_balance_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if network_id is not None: - _path_params["network_id"] = network_id + _path_params['network_id'] = network_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id if asset_id is not None: - _path_params["asset_id"] = asset_id + _path_params['asset_id'] = asset_id # process the query parameters # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/networks/{network_id}/addresses/{address_id}/balances/{asset_id}", + method='GET', + resource_path='/v1/networks/{network_id}/addresses/{address_id}/balances/{asset_id}', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -288,327 +323,29 @@ def _get_external_address_balance_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, - ) - - @validate_call - def list_address_transactions( - self, - network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to fetch the transactions for.") - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), - ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> AddressTransactionList: - """List transactions for an address. - - List all transactions that interact with the address. - - :param network_id: The ID of the blockchain network (required) - :type network_id: str - :param address_id: The ID of the address to fetch the transactions for. (required) - :type address_id: str - :param limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. - :type limit: int - :param page: A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. - :type page: str - :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. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ - _param = self._list_address_transactions_serialize( - network_id=network_id, - address_id=address_id, - limit=limit, - page=page, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index, - ) - - _response_types_map: dict[str, str | None] = { - "200": "AddressTransactionList", - } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ).data - - @validate_call - def list_address_transactions_with_http_info( - self, - network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to fetch the transactions for.") - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), - ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> ApiResponse[AddressTransactionList]: - """List transactions for an address. - - List all transactions that interact with the address. - - :param network_id: The ID of the blockchain network (required) - :type network_id: str - :param address_id: The ID of the address to fetch the transactions for. (required) - :type address_id: str - :param limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. - :type limit: int - :param page: A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. - :type page: str - :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. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ - _param = self._list_address_transactions_serialize( - network_id=network_id, - address_id=address_id, - limit=limit, - page=page, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index, - ) - - _response_types_map: dict[str, str | None] = { - "200": "AddressTransactionList", - } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) - response_data.read() - return self.api_client.response_deserialize( - response_data=response_data, - response_types_map=_response_types_map, - ) - - @validate_call - def list_address_transactions_without_preload_content( - self, - network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to fetch the transactions for.") - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), - ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, - _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, - ) -> RESTResponseType: - """List transactions for an address. - - List all transactions that interact with the address. - - :param network_id: The ID of the blockchain network (required) - :type network_id: str - :param address_id: The ID of the address to fetch the transactions for. (required) - :type address_id: str - :param limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. - :type limit: int - :param page: A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. - :type page: str - :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. - :type _request_timeout: int, tuple(int, int), optional - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the - authentication in the spec for a single request. - :type _request_auth: dict, optional - :param _content_type: force content-type for the request. - :type _content_type: str, Optional - :param _headers: set to override the headers for a single - request; this effectively ignores the headers - in the spec for a single request. - :type _headers: dict, optional - :param _host_index: set to override the host_index for a single - request; this effectively ignores the host_index - in the spec for a single request. - :type _host_index: int, optional - :return: Returns the result object. - """ - _param = self._list_address_transactions_serialize( - network_id=network_id, - address_id=address_id, - limit=limit, - page=page, - _request_auth=_request_auth, - _content_type=_content_type, - _headers=_headers, - _host_index=_host_index, + _request_auth=_request_auth ) - _response_types_map: dict[str, str | None] = { - "200": "AddressTransactionList", - } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) - return response_data.response - - def _list_address_transactions_serialize( - self, - network_id, - address_id, - limit, - page, - _request_auth, - _content_type, - _headers, - _host_index, - ) -> RequestSerialized: - _host = None - - _collection_formats: dict[str, str] = {} - - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None - - # process the path parameters - if network_id is not None: - _path_params["network_id"] = network_id - if address_id is not None: - _path_params["address_id"] = address_id - # process the query parameters - if limit is not None: - _query_params.append(("limit", limit)) - if page is not None: - _query_params.append(("page", page)) - # process the header parameters - # process the form parameters - # process the body parameter - - # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) - - # authentication setting - _auth_settings: list[str] = [] - - return self.api_client.param_serialize( - method="GET", - resource_path="/v1/networks/{network_id}/addresses/{address_id}/transactions", - path_params=_path_params, - query_params=_query_params, - header_params=_header_params, - body=_body_params, - post_params=_form_params, - files=_files, - auth_settings=_auth_settings, - collection_formats=_collection_formats, - _host=_host, - _request_auth=_request_auth, - ) @validate_call def list_external_address_balances( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to fetch the balance for") - ], - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the balance for")], + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> AddressBalanceList: """Get the balances of an external address @@ -641,7 +378,8 @@ def list_external_address_balances( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_external_address_balances_serialize( network_id=network_id, address_id=address_id, @@ -649,38 +387,40 @@ def list_external_address_balances( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "AddressBalanceList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressBalanceList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def list_external_address_balances_with_http_info( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to fetch the balance for") - ], - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the balance for")], + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[AddressBalanceList]: """Get the balances of an external address @@ -713,7 +453,8 @@ def list_external_address_balances_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_external_address_balances_serialize( network_id=network_id, address_id=address_id, @@ -721,38 +462,40 @@ def list_external_address_balances_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "AddressBalanceList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressBalanceList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def list_external_address_balances_without_preload_content( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to fetch the balance for") - ], - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the balance for")], + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Get the balances of an external address @@ -785,7 +528,8 @@ def list_external_address_balances_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_external_address_balances_serialize( network_id=network_id, address_id=address_id, @@ -793,15 +537,19 @@ def list_external_address_balances_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "AddressBalanceList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressBalanceList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _list_external_address_balances_serialize( self, network_id, @@ -812,40 +560,50 @@ def _list_external_address_balances_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if network_id is not None: - _path_params["network_id"] = network_id + _path_params['network_id'] = network_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id # process the query parameters if page is not None: - _query_params.append(("page", page)) - + + _query_params.append(('page', page)) + # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/networks/{network_id}/addresses/{address_id}/balances", + method='GET', + resource_path='/v1/networks/{network_id}/addresses/{address_id}/balances', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -855,28 +613,29 @@ def _list_external_address_balances_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def request_external_faucet_funds( self, - network_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The onchain address of the address that is being fetched."), - ], - asset_id: Annotated[ - StrictStr | None, Field(description="The ID of the asset to transfer from the faucet.") + network_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address that is being fetched.")], + asset_id: Annotated[Optional[StrictStr], Field(description="The ID of the asset to transfer from the faucet.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> FaucetTransaction: """Request faucet funds for external address. @@ -909,7 +668,8 @@ def request_external_faucet_funds( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._request_external_faucet_funds_serialize( network_id=network_id, address_id=address_id, @@ -917,38 +677,40 @@ def request_external_faucet_funds( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "FaucetTransaction", + _response_types_map: Dict[str, Optional[str]] = { + '200': "FaucetTransaction", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def request_external_faucet_funds_with_http_info( self, - network_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The onchain address of the address that is being fetched."), - ], - asset_id: Annotated[ - StrictStr | None, Field(description="The ID of the asset to transfer from the faucet.") + network_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address that is being fetched.")], + asset_id: Annotated[Optional[StrictStr], Field(description="The ID of the asset to transfer from the faucet.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[FaucetTransaction]: """Request faucet funds for external address. @@ -981,7 +743,8 @@ def request_external_faucet_funds_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._request_external_faucet_funds_serialize( network_id=network_id, address_id=address_id, @@ -989,38 +752,40 @@ def request_external_faucet_funds_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "FaucetTransaction", + _response_types_map: Dict[str, Optional[str]] = { + '200': "FaucetTransaction", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def request_external_faucet_funds_without_preload_content( self, - network_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The onchain address of the address that is being fetched."), - ], - asset_id: Annotated[ - StrictStr | None, Field(description="The ID of the asset to transfer from the faucet.") + network_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address that is being fetched.")], + asset_id: Annotated[Optional[StrictStr], Field(description="The ID of the asset to transfer from the faucet.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Request faucet funds for external address. @@ -1053,7 +818,8 @@ def request_external_faucet_funds_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._request_external_faucet_funds_serialize( network_id=network_id, address_id=address_id, @@ -1061,15 +827,19 @@ def request_external_faucet_funds_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "FaucetTransaction", + _response_types_map: Dict[str, Optional[str]] = { + '200': "FaucetTransaction", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _request_external_faucet_funds_serialize( self, network_id, @@ -1080,40 +850,50 @@ def _request_external_faucet_funds_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if network_id is not None: - _path_params["network_id"] = network_id + _path_params['network_id'] = network_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id # process the query parameters if asset_id is not None: - _query_params.append(("asset_id", asset_id)) - + + _query_params.append(('asset_id', asset_id)) + # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="POST", - resource_path="/v1/networks/{network_id}/addresses/{address_id}/faucet", + method='POST', + resource_path='/v1/networks/{network_id}/addresses/{address_id}/faucet', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -1123,5 +903,7 @@ def _request_external_faucet_funds_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + diff --git a/cdp/client/api/networks_api.py b/cdp/client/api/networks_api.py index 2b33d9d..954fc20 100644 --- a/cdp/client/api/networks_api.py +++ b/cdp/client/api/networks_api.py @@ -1,20 +1,27 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 -from typing import Annotated, Any +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated -from pydantic import Field, StrictFloat, StrictInt, StrictStr, validate_call +from pydantic import Field, StrictStr +from typing_extensions import Annotated +from cdp.client.models.network import Network from cdp.client.api_client import ApiClient, RequestSerialized from cdp.client.api_response import ApiResponse -from cdp.client.models.network import Network from cdp.client.rest import RESTResponseType @@ -30,16 +37,22 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def get_network( self, network_id: Annotated[StrictStr, Field(description="The ID of the network to fetch.")], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Network: """Get network by ID @@ -68,35 +81,45 @@ def get_network( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_network_serialize( network_id=network_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Network", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Network", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def get_network_with_http_info( self, network_id: Annotated[StrictStr, Field(description="The ID of the network to fetch.")], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[Network]: """Get network by ID @@ -125,35 +148,45 @@ def get_network_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_network_serialize( network_id=network_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Network", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Network", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def get_network_without_preload_content( self, network_id: Annotated[StrictStr, Field(description="The ID of the network to fetch.")], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Get network by ID @@ -182,21 +215,26 @@ def get_network_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_network_serialize( network_id=network_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Network", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Network", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _get_network_serialize( self, network_id, @@ -205,35 +243,44 @@ def _get_network_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if network_id is not None: - _path_params["network_id"] = network_id + _path_params['network_id'] = network_id # process the query parameters # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/networks/{network_id}", + method='GET', + resource_path='/v1/networks/{network_id}', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -243,5 +290,7 @@ def _get_network_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + diff --git a/cdp/client/api/server_signers_api.py b/cdp/client/api/server_signers_api.py index a101cb8..7c570c2 100644 --- a/cdp/client/api/server_signers_api.py +++ b/cdp/client/api/server_signers_api.py @@ -1,25 +1,33 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from typing import Annotated, Any + Do not edit the class manually. +""" # noqa: E501 -from pydantic import Field, StrictFloat, StrictInt, StrictStr, validate_call +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated -from cdp.client.api_client import ApiClient, RequestSerialized -from cdp.client.api_response import ApiResponse +from pydantic import Field, StrictInt, StrictStr +from typing import Optional +from typing_extensions import Annotated from cdp.client.models.create_server_signer_request import CreateServerSignerRequest from cdp.client.models.seed_creation_event_result import SeedCreationEventResult from cdp.client.models.server_signer import ServerSigner from cdp.client.models.server_signer_event_list import ServerSignerEventList from cdp.client.models.server_signer_list import ServerSignerList from cdp.client.models.signature_creation_event_result import SignatureCreationEventResult + +from cdp.client.api_client import ApiClient, RequestSerialized +from cdp.client.api_response import ApiResponse from cdp.client.rest import RESTResponseType @@ -35,16 +43,22 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def create_server_signer( self, - create_server_signer_request: CreateServerSignerRequest | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + create_server_signer_request: Optional[CreateServerSignerRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ServerSigner: """Create a new Server-Signer @@ -73,35 +87,45 @@ def create_server_signer( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_server_signer_serialize( create_server_signer_request=create_server_signer_request, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ServerSigner", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ServerSigner", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def create_server_signer_with_http_info( self, - create_server_signer_request: CreateServerSignerRequest | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + create_server_signer_request: Optional[CreateServerSignerRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[ServerSigner]: """Create a new Server-Signer @@ -130,35 +154,45 @@ def create_server_signer_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_server_signer_serialize( create_server_signer_request=create_server_signer_request, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ServerSigner", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ServerSigner", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def create_server_signer_without_preload_content( self, - create_server_signer_request: CreateServerSignerRequest | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + create_server_signer_request: Optional[CreateServerSignerRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Create a new Server-Signer @@ -187,21 +221,26 @@ def create_server_signer_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_server_signer_serialize( create_server_signer_request=create_server_signer_request, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ServerSigner", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ServerSigner", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _create_server_signer_serialize( self, create_server_signer_request, @@ -210,16 +249,18 @@ def _create_server_signer_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters # process the query parameters @@ -229,24 +270,36 @@ def _create_server_signer_serialize( if create_server_signer_request is not None: _body_params = create_server_signer_request + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` if _content_type: - _header_params["Content-Type"] = _content_type + _header_params['Content-Type'] = _content_type else: - _default_content_type = self.api_client.select_header_content_type(["application/json"]) + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) if _default_content_type is not None: - _header_params["Content-Type"] = _default_content_type + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="POST", - resource_path="/v1/server_signers", + method='POST', + resource_path='/v1/server_signers', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -256,21 +309,27 @@ def _create_server_signer_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def get_server_signer( self, - server_signer_id: Annotated[ - StrictStr, Field(description="The ID of the server signer to fetch") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + server_signer_id: Annotated[StrictStr, Field(description="The ID of the server signer to fetch")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ServerSigner: """Get a server signer by ID @@ -299,37 +358,45 @@ def get_server_signer( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_server_signer_serialize( server_signer_id=server_signer_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ServerSigner", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ServerSigner", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def get_server_signer_with_http_info( self, - server_signer_id: Annotated[ - StrictStr, Field(description="The ID of the server signer to fetch") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + server_signer_id: Annotated[StrictStr, Field(description="The ID of the server signer to fetch")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[ServerSigner]: """Get a server signer by ID @@ -358,37 +425,45 @@ def get_server_signer_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_server_signer_serialize( server_signer_id=server_signer_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ServerSigner", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ServerSigner", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def get_server_signer_without_preload_content( self, - server_signer_id: Annotated[ - StrictStr, Field(description="The ID of the server signer to fetch") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + server_signer_id: Annotated[StrictStr, Field(description="The ID of the server signer to fetch")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Get a server signer by ID @@ -417,21 +492,26 @@ def get_server_signer_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_server_signer_serialize( server_signer_id=server_signer_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ServerSigner", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ServerSigner", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _get_server_signer_serialize( self, server_signer_id, @@ -440,35 +520,44 @@ def _get_server_signer_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if server_signer_id is not None: - _path_params["server_signer_id"] = server_signer_id + _path_params['server_signer_id'] = server_signer_id # process the query parameters # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/server_signers/{server_signer_id}", + method='GET', + resource_path='/v1/server_signers/{server_signer_id}', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -478,36 +567,32 @@ def _get_server_signer_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def list_server_signer_events( self, - server_signer_id: Annotated[ - StrictStr, Field(description="The ID of the server signer to fetch events for") - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + server_signer_id: Annotated[StrictStr, Field(description="The ID of the server signer to fetch events for")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ServerSignerEventList: - """List events for a server signer + """(Deprecated) List events for a server signer List events for a server signer @@ -537,7 +622,9 @@ def list_server_signer_events( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + warnings.warn("GET /v1/server_signers/{server_signer_id}/events is deprecated.", DeprecationWarning) + _param = self._list_server_signer_events_serialize( server_signer_id=server_signer_id, limit=limit, @@ -545,46 +632,43 @@ def list_server_signer_events( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ServerSignerEventList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ServerSignerEventList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def list_server_signer_events_with_http_info( self, - server_signer_id: Annotated[ - StrictStr, Field(description="The ID of the server signer to fetch events for") - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + server_signer_id: Annotated[StrictStr, Field(description="The ID of the server signer to fetch events for")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[ServerSignerEventList]: - """List events for a server signer + """(Deprecated) List events for a server signer List events for a server signer @@ -614,7 +698,9 @@ def list_server_signer_events_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + warnings.warn("GET /v1/server_signers/{server_signer_id}/events is deprecated.", DeprecationWarning) + _param = self._list_server_signer_events_serialize( server_signer_id=server_signer_id, limit=limit, @@ -622,46 +708,43 @@ def list_server_signer_events_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ServerSignerEventList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ServerSignerEventList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def list_server_signer_events_without_preload_content( self, - server_signer_id: Annotated[ - StrictStr, Field(description="The ID of the server signer to fetch events for") - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + server_signer_id: Annotated[StrictStr, Field(description="The ID of the server signer to fetch events for")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """List events for a server signer + """(Deprecated) List events for a server signer List events for a server signer @@ -691,7 +774,9 @@ def list_server_signer_events_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + warnings.warn("GET /v1/server_signers/{server_signer_id}/events is deprecated.", DeprecationWarning) + _param = self._list_server_signer_events_serialize( server_signer_id=server_signer_id, limit=limit, @@ -699,15 +784,19 @@ def list_server_signer_events_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ServerSignerEventList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ServerSignerEventList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _list_server_signer_events_serialize( self, server_signer_id, @@ -718,41 +807,52 @@ def _list_server_signer_events_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if server_signer_id is not None: - _path_params["server_signer_id"] = server_signer_id + _path_params['server_signer_id'] = server_signer_id # process the query parameters if limit is not None: - _query_params.append(("limit", limit)) - + + _query_params.append(('limit', limit)) + if page is not None: - _query_params.append(("page", page)) - + + _query_params.append(('page', page)) + # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/server_signers/{server_signer_id}/events", + method='GET', + resource_path='/v1/server_signers/{server_signer_id}/events', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -762,30 +862,28 @@ def _list_server_signer_events_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def list_server_signers( self, - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ServerSignerList: """List server signers for the current project @@ -816,47 +914,47 @@ def list_server_signers( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_server_signers_serialize( limit=limit, page=page, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ServerSignerList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ServerSignerList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def list_server_signers_with_http_info( self, - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[ServerSignerList]: """List server signers for the current project @@ -887,47 +985,47 @@ def list_server_signers_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_server_signers_serialize( limit=limit, page=page, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ServerSignerList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ServerSignerList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def list_server_signers_without_preload_content( self, - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """List server signers for the current project @@ -958,22 +1056,27 @@ def list_server_signers_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_server_signers_serialize( limit=limit, page=page, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ServerSignerList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ServerSignerList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _list_server_signers_serialize( self, limit, @@ -983,39 +1086,50 @@ def _list_server_signers_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters # process the query parameters if limit is not None: - _query_params.append(("limit", limit)) - + + _query_params.append(('limit', limit)) + if page is not None: - _query_params.append(("page", page)) - + + _query_params.append(('page', page)) + # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/server_signers", + method='GET', + resource_path='/v1/server_signers', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -1025,23 +1139,28 @@ def _list_server_signers_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def submit_server_signer_seed_event_result( self, - server_signer_id: Annotated[ - StrictStr, - Field(description="The ID of the server signer to submit the event result for"), - ], - seed_creation_event_result: SeedCreationEventResult | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + server_signer_id: Annotated[StrictStr, Field(description="The ID of the server signer to submit the event result for")], + seed_creation_event_result: Optional[SeedCreationEventResult] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SeedCreationEventResult: """Submit the result of a server signer event @@ -1072,40 +1191,47 @@ def submit_server_signer_seed_event_result( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._submit_server_signer_seed_event_result_serialize( server_signer_id=server_signer_id, seed_creation_event_result=seed_creation_event_result, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "SeedCreationEventResult", + _response_types_map: Dict[str, Optional[str]] = { + '200': "SeedCreationEventResult", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def submit_server_signer_seed_event_result_with_http_info( self, - server_signer_id: Annotated[ - StrictStr, - Field(description="The ID of the server signer to submit the event result for"), - ], - seed_creation_event_result: SeedCreationEventResult | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + server_signer_id: Annotated[StrictStr, Field(description="The ID of the server signer to submit the event result for")], + seed_creation_event_result: Optional[SeedCreationEventResult] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SeedCreationEventResult]: """Submit the result of a server signer event @@ -1136,40 +1262,47 @@ def submit_server_signer_seed_event_result_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._submit_server_signer_seed_event_result_serialize( server_signer_id=server_signer_id, seed_creation_event_result=seed_creation_event_result, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "SeedCreationEventResult", + _response_types_map: Dict[str, Optional[str]] = { + '200': "SeedCreationEventResult", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def submit_server_signer_seed_event_result_without_preload_content( self, - server_signer_id: Annotated[ - StrictStr, - Field(description="The ID of the server signer to submit the event result for"), - ], - seed_creation_event_result: SeedCreationEventResult | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + server_signer_id: Annotated[StrictStr, Field(description="The ID of the server signer to submit the event result for")], + seed_creation_event_result: Optional[SeedCreationEventResult] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Submit the result of a server signer event @@ -1200,22 +1333,27 @@ def submit_server_signer_seed_event_result_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._submit_server_signer_seed_event_result_serialize( server_signer_id=server_signer_id, seed_creation_event_result=seed_creation_event_result, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "SeedCreationEventResult", + _response_types_map: Dict[str, Optional[str]] = { + '200': "SeedCreationEventResult", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _submit_server_signer_seed_event_result_serialize( self, server_signer_id, @@ -1225,20 +1363,22 @@ def _submit_server_signer_seed_event_result_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if server_signer_id is not None: - _path_params["server_signer_id"] = server_signer_id + _path_params['server_signer_id'] = server_signer_id # process the query parameters # process the header parameters # process the form parameters @@ -1246,24 +1386,36 @@ def _submit_server_signer_seed_event_result_serialize( if seed_creation_event_result is not None: _body_params = seed_creation_event_result + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` if _content_type: - _header_params["Content-Type"] = _content_type + _header_params['Content-Type'] = _content_type else: - _default_content_type = self.api_client.select_header_content_type(["application/json"]) + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) if _default_content_type is not None: - _header_params["Content-Type"] = _default_content_type + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="POST", - resource_path="/v1/server_signers/{server_signer_id}/seed_event_result", + method='POST', + resource_path='/v1/server_signers/{server_signer_id}/seed_event_result', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -1273,23 +1425,28 @@ def _submit_server_signer_seed_event_result_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def submit_server_signer_signature_event_result( self, - server_signer_id: Annotated[ - StrictStr, - Field(description="The ID of the server signer to submit the event result for"), - ], - signature_creation_event_result: SignatureCreationEventResult | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + server_signer_id: Annotated[StrictStr, Field(description="The ID of the server signer to submit the event result for")], + signature_creation_event_result: Optional[SignatureCreationEventResult] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SignatureCreationEventResult: """Submit the result of a server signer event @@ -1320,40 +1477,47 @@ def submit_server_signer_signature_event_result( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._submit_server_signer_signature_event_result_serialize( server_signer_id=server_signer_id, signature_creation_event_result=signature_creation_event_result, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "SignatureCreationEventResult", + _response_types_map: Dict[str, Optional[str]] = { + '200': "SignatureCreationEventResult", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def submit_server_signer_signature_event_result_with_http_info( self, - server_signer_id: Annotated[ - StrictStr, - Field(description="The ID of the server signer to submit the event result for"), - ], - signature_creation_event_result: SignatureCreationEventResult | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + server_signer_id: Annotated[StrictStr, Field(description="The ID of the server signer to submit the event result for")], + signature_creation_event_result: Optional[SignatureCreationEventResult] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SignatureCreationEventResult]: """Submit the result of a server signer event @@ -1384,40 +1548,47 @@ def submit_server_signer_signature_event_result_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._submit_server_signer_signature_event_result_serialize( server_signer_id=server_signer_id, signature_creation_event_result=signature_creation_event_result, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "SignatureCreationEventResult", + _response_types_map: Dict[str, Optional[str]] = { + '200': "SignatureCreationEventResult", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def submit_server_signer_signature_event_result_without_preload_content( self, - server_signer_id: Annotated[ - StrictStr, - Field(description="The ID of the server signer to submit the event result for"), - ], - signature_creation_event_result: SignatureCreationEventResult | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + server_signer_id: Annotated[StrictStr, Field(description="The ID of the server signer to submit the event result for")], + signature_creation_event_result: Optional[SignatureCreationEventResult] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Submit the result of a server signer event @@ -1448,22 +1619,27 @@ def submit_server_signer_signature_event_result_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._submit_server_signer_signature_event_result_serialize( server_signer_id=server_signer_id, signature_creation_event_result=signature_creation_event_result, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "SignatureCreationEventResult", + _response_types_map: Dict[str, Optional[str]] = { + '200': "SignatureCreationEventResult", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _submit_server_signer_signature_event_result_serialize( self, server_signer_id, @@ -1473,20 +1649,22 @@ def _submit_server_signer_signature_event_result_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if server_signer_id is not None: - _path_params["server_signer_id"] = server_signer_id + _path_params['server_signer_id'] = server_signer_id # process the query parameters # process the header parameters # process the form parameters @@ -1494,24 +1672,36 @@ def _submit_server_signer_signature_event_result_serialize( if signature_creation_event_result is not None: _body_params = signature_creation_event_result + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` if _content_type: - _header_params["Content-Type"] = _content_type + _header_params['Content-Type'] = _content_type else: - _default_content_type = self.api_client.select_header_content_type(["application/json"]) + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) if _default_content_type is not None: - _header_params["Content-Type"] = _default_content_type + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="POST", - resource_path="/v1/server_signers/{server_signer_id}/signature_event_result", + method='POST', + resource_path='/v1/server_signers/{server_signer_id}/signature_event_result', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -1521,5 +1711,7 @@ def _submit_server_signer_signature_event_result_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + diff --git a/cdp/client/api/smart_contracts_api.py b/cdp/client/api/smart_contracts_api.py index 95d46e7..a507b57 100644 --- a/cdp/client/api/smart_contracts_api.py +++ b/cdp/client/api/smart_contracts_api.py @@ -1,23 +1,30 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from typing import Annotated, Any + Do not edit the class manually. +""" # noqa: E501 -from pydantic import Field, StrictFloat, StrictInt, StrictStr, validate_call +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated -from cdp.client.api_client import ApiClient, RequestSerialized -from cdp.client.api_response import ApiResponse +from pydantic import Field, StrictStr +from typing_extensions import Annotated from cdp.client.models.create_smart_contract_request import CreateSmartContractRequest from cdp.client.models.deploy_smart_contract_request import DeploySmartContractRequest from cdp.client.models.smart_contract import SmartContract from cdp.client.models.smart_contract_list import SmartContractList + +from cdp.client.api_client import ApiClient, RequestSerialized +from cdp.client.api_response import ApiResponse from cdp.client.rest import RESTResponseType @@ -33,22 +40,24 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def create_smart_contract( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to deploy the smart contract from.") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to deploy the smart contract from.")], create_smart_contract_request: CreateSmartContractRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SmartContract: """Create a new smart contract @@ -81,7 +90,8 @@ def create_smart_contract( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_smart_contract_serialize( wallet_id=wallet_id, address_id=address_id, @@ -89,35 +99,40 @@ def create_smart_contract( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "SmartContract", + _response_types_map: Dict[str, Optional[str]] = { + '200': "SmartContract", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def create_smart_contract_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to deploy the smart contract from.") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to deploy the smart contract from.")], create_smart_contract_request: CreateSmartContractRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SmartContract]: """Create a new smart contract @@ -150,7 +165,8 @@ def create_smart_contract_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_smart_contract_serialize( wallet_id=wallet_id, address_id=address_id, @@ -158,35 +174,40 @@ def create_smart_contract_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "SmartContract", + _response_types_map: Dict[str, Optional[str]] = { + '200': "SmartContract", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def create_smart_contract_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to deploy the smart contract from.") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to deploy the smart contract from.")], create_smart_contract_request: CreateSmartContractRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Create a new smart contract @@ -219,7 +240,8 @@ def create_smart_contract_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_smart_contract_serialize( wallet_id=wallet_id, address_id=address_id, @@ -227,15 +249,19 @@ def create_smart_contract_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "SmartContract", + _response_types_map: Dict[str, Optional[str]] = { + '200': "SmartContract", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _create_smart_contract_serialize( self, wallet_id, @@ -246,22 +272,24 @@ def _create_smart_contract_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id # process the query parameters # process the header parameters # process the form parameters @@ -269,24 +297,36 @@ def _create_smart_contract_serialize( if create_smart_contract_request is not None: _body_params = create_smart_contract_request + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` if _content_type: - _header_params["Content-Type"] = _content_type + _header_params['Content-Type'] = _content_type else: - _default_content_type = self.api_client.select_header_content_type(["application/json"]) + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) if _default_content_type is not None: - _header_params["Content-Type"] = _default_content_type + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="POST", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/smart_contracts", + method='POST', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/smart_contracts', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -296,29 +336,30 @@ def _create_smart_contract_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def deploy_smart_contract( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to broadcast the transaction from.") - ], - smart_contract_id: Annotated[ - StrictStr, - Field(description="The UUID of the smart contract to broadcast the transaction to."), - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to broadcast the transaction from.")], + smart_contract_id: Annotated[StrictStr, Field(description="The UUID of the smart contract to broadcast the transaction to.")], deploy_smart_contract_request: DeploySmartContractRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SmartContract: """Deploy a smart contract @@ -353,7 +394,8 @@ def deploy_smart_contract( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._deploy_smart_contract_serialize( wallet_id=wallet_id, address_id=address_id, @@ -362,39 +404,41 @@ def deploy_smart_contract( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "SmartContract", + _response_types_map: Dict[str, Optional[str]] = { + '200': "SmartContract", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def deploy_smart_contract_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to broadcast the transaction from.") - ], - smart_contract_id: Annotated[ - StrictStr, - Field(description="The UUID of the smart contract to broadcast the transaction to."), - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to broadcast the transaction from.")], + smart_contract_id: Annotated[StrictStr, Field(description="The UUID of the smart contract to broadcast the transaction to.")], deploy_smart_contract_request: DeploySmartContractRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SmartContract]: """Deploy a smart contract @@ -429,7 +473,8 @@ def deploy_smart_contract_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._deploy_smart_contract_serialize( wallet_id=wallet_id, address_id=address_id, @@ -438,39 +483,41 @@ def deploy_smart_contract_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "SmartContract", + _response_types_map: Dict[str, Optional[str]] = { + '200': "SmartContract", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def deploy_smart_contract_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to broadcast the transaction from.") - ], - smart_contract_id: Annotated[ - StrictStr, - Field(description="The UUID of the smart contract to broadcast the transaction to."), - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to broadcast the transaction from.")], + smart_contract_id: Annotated[StrictStr, Field(description="The UUID of the smart contract to broadcast the transaction to.")], deploy_smart_contract_request: DeploySmartContractRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Deploy a smart contract @@ -505,7 +552,8 @@ def deploy_smart_contract_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._deploy_smart_contract_serialize( wallet_id=wallet_id, address_id=address_id, @@ -514,15 +562,19 @@ def deploy_smart_contract_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "SmartContract", + _response_types_map: Dict[str, Optional[str]] = { + '200': "SmartContract", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _deploy_smart_contract_serialize( self, wallet_id, @@ -534,24 +586,26 @@ def _deploy_smart_contract_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id if smart_contract_id is not None: - _path_params["smart_contract_id"] = smart_contract_id + _path_params['smart_contract_id'] = smart_contract_id # process the query parameters # process the header parameters # process the form parameters @@ -559,24 +613,36 @@ def _deploy_smart_contract_serialize( if deploy_smart_contract_request is not None: _body_params = deploy_smart_contract_request + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` if _content_type: - _header_params["Content-Type"] = _content_type + _header_params['Content-Type'] = _content_type else: - _default_content_type = self.api_client.select_header_content_type(["application/json"]) + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) if _default_content_type is not None: - _header_params["Content-Type"] = _default_content_type + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="POST", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/smart_contracts/{smart_contract_id}/deploy", + method='POST', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/smart_contracts/{smart_contract_id}/deploy', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -586,27 +652,29 @@ def _deploy_smart_contract_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def get_smart_contract( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to fetch the smart contract for.") - ], - smart_contract_id: Annotated[ - StrictStr, Field(description="The UUID of the smart contract to fetch.") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the smart contract for.")], + smart_contract_id: Annotated[StrictStr, Field(description="The UUID of the smart contract to fetch.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SmartContract: """Get a specific smart contract deployed by address @@ -639,7 +707,8 @@ def get_smart_contract( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_smart_contract_serialize( wallet_id=wallet_id, address_id=address_id, @@ -647,37 +716,40 @@ def get_smart_contract( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "SmartContract", + _response_types_map: Dict[str, Optional[str]] = { + '200': "SmartContract", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def get_smart_contract_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to fetch the smart contract for.") - ], - smart_contract_id: Annotated[ - StrictStr, Field(description="The UUID of the smart contract to fetch.") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the smart contract for.")], + smart_contract_id: Annotated[StrictStr, Field(description="The UUID of the smart contract to fetch.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SmartContract]: """Get a specific smart contract deployed by address @@ -710,7 +782,8 @@ def get_smart_contract_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_smart_contract_serialize( wallet_id=wallet_id, address_id=address_id, @@ -718,37 +791,40 @@ def get_smart_contract_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "SmartContract", + _response_types_map: Dict[str, Optional[str]] = { + '200': "SmartContract", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def get_smart_contract_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to fetch the smart contract for.") - ], - smart_contract_id: Annotated[ - StrictStr, Field(description="The UUID of the smart contract to fetch.") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the smart contract for.")], + smart_contract_id: Annotated[StrictStr, Field(description="The UUID of the smart contract to fetch.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Get a specific smart contract deployed by address @@ -781,7 +857,8 @@ def get_smart_contract_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_smart_contract_serialize( wallet_id=wallet_id, address_id=address_id, @@ -789,15 +866,19 @@ def get_smart_contract_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "SmartContract", + _response_types_map: Dict[str, Optional[str]] = { + '200': "SmartContract", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _get_smart_contract_serialize( self, wallet_id, @@ -808,39 +889,48 @@ def _get_smart_contract_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id if smart_contract_id is not None: - _path_params["smart_contract_id"] = smart_contract_id + _path_params['smart_contract_id'] = smart_contract_id # process the query parameters # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/smart_contracts/{smart_contract_id}", + method='GET', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/smart_contracts/{smart_contract_id}', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -850,24 +940,28 @@ def _get_smart_contract_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def list_smart_contracts( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to fetch the smart contracts for.") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the smart contracts for.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SmartContractList: """List smart contracts deployed by address @@ -898,41 +992,47 @@ def list_smart_contracts( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_smart_contracts_serialize( wallet_id=wallet_id, address_id=address_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "SmartContractList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "SmartContractList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def list_smart_contracts_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to fetch the smart contracts for.") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the smart contracts for.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SmartContractList]: """List smart contracts deployed by address @@ -963,41 +1063,47 @@ def list_smart_contracts_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_smart_contracts_serialize( wallet_id=wallet_id, address_id=address_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "SmartContractList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "SmartContractList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def list_smart_contracts_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to fetch the smart contracts for.") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the smart contracts for.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """List smart contracts deployed by address @@ -1028,22 +1134,27 @@ def list_smart_contracts_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_smart_contracts_serialize( wallet_id=wallet_id, address_id=address_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "SmartContractList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "SmartContractList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _list_smart_contracts_serialize( self, wallet_id, @@ -1053,37 +1164,46 @@ def _list_smart_contracts_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id # process the query parameters # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/smart_contracts", + method='GET', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/smart_contracts', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -1093,5 +1213,7 @@ def _list_smart_contracts_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + diff --git a/cdp/client/api/stake_api.py b/cdp/client/api/stake_api.py index 086b404..ff3f4f8 100644 --- a/cdp/client/api/stake_api.py +++ b/cdp/client/api/stake_api.py @@ -1,29 +1,35 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from datetime import datetime -from typing import Annotated, Any + Do not edit the class manually. +""" # noqa: E501 -from pydantic import Field, StrictFloat, StrictInt, StrictStr, validate_call +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated -from cdp.client.api_client import ApiClient, RequestSerialized -from cdp.client.api_response import ApiResponse +from datetime import datetime +from pydantic import Field, StrictInt, StrictStr +from typing import Optional +from typing_extensions import Annotated from cdp.client.models.build_staking_operation_request import BuildStakingOperationRequest -from cdp.client.models.fetch_historical_staking_balances200_response import ( - FetchHistoricalStakingBalances200Response, -) +from cdp.client.models.fetch_historical_staking_balances200_response import FetchHistoricalStakingBalances200Response from cdp.client.models.fetch_staking_rewards200_response import FetchStakingRewards200Response from cdp.client.models.fetch_staking_rewards_request import FetchStakingRewardsRequest from cdp.client.models.get_staking_context_request import GetStakingContextRequest from cdp.client.models.staking_context import StakingContext from cdp.client.models.staking_operation import StakingOperation + +from cdp.client.api_client import ApiClient, RequestSerialized +from cdp.client.api_response import ApiResponse from cdp.client.rest import RESTResponseType @@ -39,16 +45,22 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def build_staking_operation( self, build_staking_operation_request: BuildStakingOperationRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> StakingOperation: """Build a new staking operation @@ -77,35 +89,45 @@ def build_staking_operation( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._build_staking_operation_serialize( build_staking_operation_request=build_staking_operation_request, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "StakingOperation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def build_staking_operation_with_http_info( self, build_staking_operation_request: BuildStakingOperationRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[StakingOperation]: """Build a new staking operation @@ -134,35 +156,45 @@ def build_staking_operation_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._build_staking_operation_serialize( build_staking_operation_request=build_staking_operation_request, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "StakingOperation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def build_staking_operation_without_preload_content( self, build_staking_operation_request: BuildStakingOperationRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Build a new staking operation @@ -191,21 +223,26 @@ def build_staking_operation_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._build_staking_operation_serialize( build_staking_operation_request=build_staking_operation_request, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "StakingOperation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _build_staking_operation_serialize( self, build_staking_operation_request, @@ -214,16 +251,18 @@ def _build_staking_operation_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters # process the query parameters @@ -233,24 +272,36 @@ def _build_staking_operation_serialize( if build_staking_operation_request is not None: _body_params = build_staking_operation_request + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` if _content_type: - _header_params["Content-Type"] = _content_type + _header_params['Content-Type'] = _content_type else: - _default_content_type = self.api_client.select_header_content_type(["application/json"]) + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) if _default_content_type is not None: - _header_params["Content-Type"] = _default_content_type + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="POST", - resource_path="/v1/stake/build", + method='POST', + resource_path='/v1/stake/build', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -260,56 +311,33 @@ def _build_staking_operation_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def fetch_historical_staking_balances( self, - network_id: Annotated[ - str, - Field(strict=True, max_length=5000, description="The ID of the blockchain network."), - ], - asset_id: Annotated[ - str, - Field( - strict=True, - max_length=5000, - description="The ID of the asset for which the historical staking balances are being fetched.", - ), - ], - address_id: Annotated[ - str, - Field( - strict=True, - max_length=5000, - description="The onchain address for which the historical staking balances are being fetched.", - ), - ], - start_time: Annotated[ - datetime, Field(description="The start time of this historical staking balance period.") - ], - end_time: Annotated[ - datetime, Field(description="The end time of this historical staking balance period.") - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + network_id: Annotated[str, Field(strict=True, max_length=5000, description="The ID of the blockchain network.")], + asset_id: Annotated[str, Field(strict=True, max_length=5000, description="The ID of the asset for which the historical staking balances are being fetched.")], + address_id: Annotated[str, Field(strict=True, max_length=5000, description="The onchain address for which the historical staking balances are being fetched.")], + start_time: Annotated[datetime, Field(description="The start time of this historical staking balance period.")], + end_time: Annotated[datetime, Field(description="The end time of this historical staking balance period.")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> FetchHistoricalStakingBalances200Response: """Fetch historical staking balances @@ -350,7 +378,8 @@ def fetch_historical_staking_balances( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._fetch_historical_staking_balances_serialize( network_id=network_id, asset_id=asset_id, @@ -362,66 +391,44 @@ def fetch_historical_staking_balances( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "FetchHistoricalStakingBalances200Response", + _response_types_map: Dict[str, Optional[str]] = { + '200': "FetchHistoricalStakingBalances200Response", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def fetch_historical_staking_balances_with_http_info( self, - network_id: Annotated[ - str, - Field(strict=True, max_length=5000, description="The ID of the blockchain network."), - ], - asset_id: Annotated[ - str, - Field( - strict=True, - max_length=5000, - description="The ID of the asset for which the historical staking balances are being fetched.", - ), - ], - address_id: Annotated[ - str, - Field( - strict=True, - max_length=5000, - description="The onchain address for which the historical staking balances are being fetched.", - ), - ], - start_time: Annotated[ - datetime, Field(description="The start time of this historical staking balance period.") - ], - end_time: Annotated[ - datetime, Field(description="The end time of this historical staking balance period.") - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + network_id: Annotated[str, Field(strict=True, max_length=5000, description="The ID of the blockchain network.")], + asset_id: Annotated[str, Field(strict=True, max_length=5000, description="The ID of the asset for which the historical staking balances are being fetched.")], + address_id: Annotated[str, Field(strict=True, max_length=5000, description="The onchain address for which the historical staking balances are being fetched.")], + start_time: Annotated[datetime, Field(description="The start time of this historical staking balance period.")], + end_time: Annotated[datetime, Field(description="The end time of this historical staking balance period.")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[FetchHistoricalStakingBalances200Response]: """Fetch historical staking balances @@ -462,7 +469,8 @@ def fetch_historical_staking_balances_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._fetch_historical_staking_balances_serialize( network_id=network_id, asset_id=asset_id, @@ -474,66 +482,44 @@ def fetch_historical_staking_balances_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "FetchHistoricalStakingBalances200Response", + _response_types_map: Dict[str, Optional[str]] = { + '200': "FetchHistoricalStakingBalances200Response", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def fetch_historical_staking_balances_without_preload_content( self, - network_id: Annotated[ - str, - Field(strict=True, max_length=5000, description="The ID of the blockchain network."), - ], - asset_id: Annotated[ - str, - Field( - strict=True, - max_length=5000, - description="The ID of the asset for which the historical staking balances are being fetched.", - ), - ], - address_id: Annotated[ - str, - Field( - strict=True, - max_length=5000, - description="The onchain address for which the historical staking balances are being fetched.", - ), - ], - start_time: Annotated[ - datetime, Field(description="The start time of this historical staking balance period.") - ], - end_time: Annotated[ - datetime, Field(description="The end time of this historical staking balance period.") - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + network_id: Annotated[str, Field(strict=True, max_length=5000, description="The ID of the blockchain network.")], + asset_id: Annotated[str, Field(strict=True, max_length=5000, description="The ID of the asset for which the historical staking balances are being fetched.")], + address_id: Annotated[str, Field(strict=True, max_length=5000, description="The onchain address for which the historical staking balances are being fetched.")], + start_time: Annotated[datetime, Field(description="The start time of this historical staking balance period.")], + end_time: Annotated[datetime, Field(description="The end time of this historical staking balance period.")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Fetch historical staking balances @@ -574,7 +560,8 @@ def fetch_historical_staking_balances_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._fetch_historical_staking_balances_serialize( network_id=network_id, asset_id=asset_id, @@ -586,15 +573,19 @@ def fetch_historical_staking_balances_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "FetchHistoricalStakingBalances200Response", + _response_types_map: Dict[str, Optional[str]] = { + '200': "FetchHistoricalStakingBalances200Response", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _fetch_historical_staking_balances_serialize( self, network_id, @@ -609,65 +600,84 @@ def _fetch_historical_staking_balances_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if network_id is not None: - _path_params["network_id"] = network_id + _path_params['network_id'] = network_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id # process the query parameters if limit is not None: - _query_params.append(("limit", limit)) - + + _query_params.append(('limit', limit)) + if page is not None: - _query_params.append(("page", page)) - + + _query_params.append(('page', page)) + if asset_id is not None: - _query_params.append(("asset_id", asset_id)) - + + _query_params.append(('asset_id', asset_id)) + if start_time is not None: if isinstance(start_time, datetime): _query_params.append( ( - "start_time", - start_time.strftime(self.api_client.configuration.datetime_format), + 'start_time', + start_time.strftime( + self.api_client.configuration.datetime_format + ) ) ) else: - _query_params.append(("start_time", start_time)) - + _query_params.append(('start_time', start_time)) + if end_time is not None: if isinstance(end_time, datetime): _query_params.append( - ("end_time", end_time.strftime(self.api_client.configuration.datetime_format)) + ( + 'end_time', + end_time.strftime( + self.api_client.configuration.datetime_format + ) + ) ) else: - _query_params.append(("end_time", end_time)) - + _query_params.append(('end_time', end_time)) + # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/networks/{network_id}/addresses/{address_id}/stake/balances", + method='GET', + resource_path='/v1/networks/{network_id}/addresses/{address_id}/stake/balances', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -677,31 +687,29 @@ def _fetch_historical_staking_balances_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def fetch_staking_rewards( self, fetch_staking_rewards_request: FetchStakingRewardsRequest, - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> FetchStakingRewards200Response: """Fetch staking rewards @@ -734,7 +742,8 @@ def fetch_staking_rewards( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._fetch_staking_rewards_serialize( fetch_staking_rewards_request=fetch_staking_rewards_request, limit=limit, @@ -742,41 +751,40 @@ def fetch_staking_rewards( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "FetchStakingRewards200Response", + _response_types_map: Dict[str, Optional[str]] = { + '200': "FetchStakingRewards200Response", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def fetch_staking_rewards_with_http_info( self, fetch_staking_rewards_request: FetchStakingRewardsRequest, - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50." - ), + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), - ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[FetchStakingRewards200Response]: """Fetch staking rewards @@ -809,7 +817,8 @@ def fetch_staking_rewards_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._fetch_staking_rewards_serialize( fetch_staking_rewards_request=fetch_staking_rewards_request, limit=limit, @@ -817,41 +826,40 @@ def fetch_staking_rewards_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "FetchStakingRewards200Response", + _response_types_map: Dict[str, Optional[str]] = { + '200': "FetchStakingRewards200Response", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def fetch_staking_rewards_without_preload_content( self, fetch_staking_rewards_request: FetchStakingRewardsRequest, - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50." - ), + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), - ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Fetch staking rewards @@ -884,7 +892,8 @@ def fetch_staking_rewards_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._fetch_staking_rewards_serialize( fetch_staking_rewards_request=fetch_staking_rewards_request, limit=limit, @@ -892,15 +901,19 @@ def fetch_staking_rewards_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "FetchStakingRewards200Response", + _response_types_map: Dict[str, Optional[str]] = { + '200': "FetchStakingRewards200Response", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _fetch_staking_rewards_serialize( self, fetch_staking_rewards_request, @@ -911,49 +924,65 @@ def _fetch_staking_rewards_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters # process the query parameters if limit is not None: - _query_params.append(("limit", limit)) - + + _query_params.append(('limit', limit)) + if page is not None: - _query_params.append(("page", page)) - + + _query_params.append(('page', page)) + # process the header parameters # process the form parameters # process the body parameter if fetch_staking_rewards_request is not None: _body_params = fetch_staking_rewards_request + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` if _content_type: - _header_params["Content-Type"] = _content_type + _header_params['Content-Type'] = _content_type else: - _default_content_type = self.api_client.select_header_content_type(["application/json"]) + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) if _default_content_type is not None: - _header_params["Content-Type"] = _default_content_type + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="POST", - resource_path="/v1/stake/rewards/search", + method='POST', + resource_path='/v1/stake/rewards/search', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -963,25 +992,29 @@ def _fetch_staking_rewards_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def get_external_staking_operation( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to fetch the staking operation for") - ], - staking_operation_id: Annotated[ - StrictStr, Field(description="The ID of the staking operation") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the staking operation for")], + staking_operation_id: Annotated[StrictStr, Field(description="The ID of the staking operation")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> StakingOperation: """Get the latest state of a staking operation @@ -1014,7 +1047,8 @@ def get_external_staking_operation( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_external_staking_operation_serialize( network_id=network_id, address_id=address_id, @@ -1022,35 +1056,40 @@ def get_external_staking_operation( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "StakingOperation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def get_external_staking_operation_with_http_info( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to fetch the staking operation for") - ], - staking_operation_id: Annotated[ - StrictStr, Field(description="The ID of the staking operation") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the staking operation for")], + staking_operation_id: Annotated[StrictStr, Field(description="The ID of the staking operation")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[StakingOperation]: """Get the latest state of a staking operation @@ -1083,7 +1122,8 @@ def get_external_staking_operation_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_external_staking_operation_serialize( network_id=network_id, address_id=address_id, @@ -1091,35 +1131,40 @@ def get_external_staking_operation_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "StakingOperation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def get_external_staking_operation_without_preload_content( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to fetch the staking operation for") - ], - staking_operation_id: Annotated[ - StrictStr, Field(description="The ID of the staking operation") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the staking operation for")], + staking_operation_id: Annotated[StrictStr, Field(description="The ID of the staking operation")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Get the latest state of a staking operation @@ -1152,7 +1197,8 @@ def get_external_staking_operation_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_external_staking_operation_serialize( network_id=network_id, address_id=address_id, @@ -1160,15 +1206,19 @@ def get_external_staking_operation_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "StakingOperation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _get_external_staking_operation_serialize( self, network_id, @@ -1179,39 +1229,48 @@ def _get_external_staking_operation_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if network_id is not None: - _path_params["network_id"] = network_id + _path_params['network_id'] = network_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id if staking_operation_id is not None: - _path_params["staking_operation_id"] = staking_operation_id + _path_params['staking_operation_id'] = staking_operation_id # process the query parameters # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/networks/{network_id}/addresses/{address_id}/staking_operations/{staking_operation_id}", + method='GET', + resource_path='/v1/networks/{network_id}/addresses/{address_id}/staking_operations/{staking_operation_id}', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -1221,19 +1280,27 @@ def _get_external_staking_operation_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def get_staking_context( self, get_staking_context_request: GetStakingContextRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> StakingContext: """Get staking context @@ -1262,35 +1329,45 @@ def get_staking_context( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_staking_context_serialize( get_staking_context_request=get_staking_context_request, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "StakingContext", + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingContext", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def get_staking_context_with_http_info( self, get_staking_context_request: GetStakingContextRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[StakingContext]: """Get staking context @@ -1319,35 +1396,45 @@ def get_staking_context_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_staking_context_serialize( get_staking_context_request=get_staking_context_request, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "StakingContext", + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingContext", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def get_staking_context_without_preload_content( self, get_staking_context_request: GetStakingContextRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Get staking context @@ -1376,21 +1463,26 @@ def get_staking_context_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_staking_context_serialize( get_staking_context_request=get_staking_context_request, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "StakingContext", + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingContext", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _get_staking_context_serialize( self, get_staking_context_request, @@ -1399,16 +1491,18 @@ def _get_staking_context_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters # process the query parameters @@ -1418,24 +1512,36 @@ def _get_staking_context_serialize( if get_staking_context_request is not None: _body_params = get_staking_context_request + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` if _content_type: - _header_params["Content-Type"] = _content_type + _header_params['Content-Type'] = _content_type else: - _default_content_type = self.api_client.select_header_content_type(["application/json"]) + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) if _default_content_type is not None: - _header_params["Content-Type"] = _default_content_type + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="POST", - resource_path="/v1/stake/context", + method='POST', + resource_path='/v1/stake/context', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -1445,5 +1551,7 @@ def _get_staking_context_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + diff --git a/cdp/client/api/trades_api.py b/cdp/client/api/trades_api.py index 5829a15..fd58ed4 100644 --- a/cdp/client/api/trades_api.py +++ b/cdp/client/api/trades_api.py @@ -1,23 +1,31 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from typing import Annotated, Any + Do not edit the class manually. +""" # noqa: E501 -from pydantic import Field, StrictFloat, StrictInt, StrictStr, validate_call +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated -from cdp.client.api_client import ApiClient, RequestSerialized -from cdp.client.api_response import ApiResponse +from pydantic import Field, StrictInt, StrictStr +from typing import Optional +from typing_extensions import Annotated from cdp.client.models.broadcast_trade_request import BroadcastTradeRequest from cdp.client.models.create_trade_request import CreateTradeRequest from cdp.client.models.trade import Trade from cdp.client.models.trade_list import TradeList + +from cdp.client.api_client import ApiClient, RequestSerialized +from cdp.client.api_response import ApiResponse from cdp.client.rest import RESTResponseType @@ -33,23 +41,25 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def broadcast_trade( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address the trade belongs to") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the trade belongs to")], trade_id: Annotated[StrictStr, Field(description="The ID of the trade to broadcast")], broadcast_trade_request: BroadcastTradeRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Trade: """Broadcast a trade @@ -84,7 +94,8 @@ def broadcast_trade( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._broadcast_trade_serialize( wallet_id=wallet_id, address_id=address_id, @@ -93,36 +104,41 @@ def broadcast_trade( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Trade", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Trade", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def broadcast_trade_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address the trade belongs to") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the trade belongs to")], trade_id: Annotated[StrictStr, Field(description="The ID of the trade to broadcast")], broadcast_trade_request: BroadcastTradeRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[Trade]: """Broadcast a trade @@ -157,7 +173,8 @@ def broadcast_trade_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._broadcast_trade_serialize( wallet_id=wallet_id, address_id=address_id, @@ -166,36 +183,41 @@ def broadcast_trade_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Trade", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Trade", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def broadcast_trade_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address the trade belongs to") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the trade belongs to")], trade_id: Annotated[StrictStr, Field(description="The ID of the trade to broadcast")], broadcast_trade_request: BroadcastTradeRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Broadcast a trade @@ -230,7 +252,8 @@ def broadcast_trade_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._broadcast_trade_serialize( wallet_id=wallet_id, address_id=address_id, @@ -239,15 +262,19 @@ def broadcast_trade_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Trade", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Trade", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _broadcast_trade_serialize( self, wallet_id, @@ -259,24 +286,26 @@ def _broadcast_trade_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id if trade_id is not None: - _path_params["trade_id"] = trade_id + _path_params['trade_id'] = trade_id # process the query parameters # process the header parameters # process the form parameters @@ -284,24 +313,36 @@ def _broadcast_trade_serialize( if broadcast_trade_request is not None: _body_params = broadcast_trade_request + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` if _content_type: - _header_params["Content-Type"] = _content_type + _header_params['Content-Type'] = _content_type else: - _default_content_type = self.api_client.select_header_content_type(["application/json"]) + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) if _default_content_type is not None: - _header_params["Content-Type"] = _default_content_type + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="POST", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/trades/{trade_id}/broadcast", + method='POST', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/trades/{trade_id}/broadcast', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -311,25 +352,29 @@ def _broadcast_trade_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def create_trade( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the source address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to conduct the trade from") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the source address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to conduct the trade from")], create_trade_request: CreateTradeRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Trade: """Create a new trade for an address @@ -362,7 +407,8 @@ def create_trade( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_trade_serialize( wallet_id=wallet_id, address_id=address_id, @@ -370,35 +416,40 @@ def create_trade( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Trade", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Trade", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def create_trade_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the source address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to conduct the trade from") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the source address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to conduct the trade from")], create_trade_request: CreateTradeRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[Trade]: """Create a new trade for an address @@ -431,7 +482,8 @@ def create_trade_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_trade_serialize( wallet_id=wallet_id, address_id=address_id, @@ -439,35 +491,40 @@ def create_trade_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Trade", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Trade", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def create_trade_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the source address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to conduct the trade from") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the source address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to conduct the trade from")], create_trade_request: CreateTradeRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Create a new trade for an address @@ -500,7 +557,8 @@ def create_trade_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_trade_serialize( wallet_id=wallet_id, address_id=address_id, @@ -508,15 +566,19 @@ def create_trade_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Trade", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Trade", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _create_trade_serialize( self, wallet_id, @@ -527,22 +589,24 @@ def _create_trade_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id # process the query parameters # process the header parameters # process the form parameters @@ -550,24 +614,36 @@ def _create_trade_serialize( if create_trade_request is not None: _body_params = create_trade_request + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` if _content_type: - _header_params["Content-Type"] = _content_type + _header_params['Content-Type'] = _content_type else: - _default_content_type = self.api_client.select_header_content_type(["application/json"]) + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) if _default_content_type is not None: - _header_params["Content-Type"] = _default_content_type + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="POST", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/trades", + method='POST', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/trades', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -577,25 +653,29 @@ def _create_trade_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def get_trade( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address the trade belongs to") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the trade belongs to")], trade_id: Annotated[StrictStr, Field(description="The ID of the trade to fetch")], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Trade: """Get a trade by ID @@ -628,7 +708,8 @@ def get_trade( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_trade_serialize( wallet_id=wallet_id, address_id=address_id, @@ -636,35 +717,40 @@ def get_trade( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Trade", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Trade", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def get_trade_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address the trade belongs to") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the trade belongs to")], trade_id: Annotated[StrictStr, Field(description="The ID of the trade to fetch")], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[Trade]: """Get a trade by ID @@ -697,7 +783,8 @@ def get_trade_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_trade_serialize( wallet_id=wallet_id, address_id=address_id, @@ -705,35 +792,40 @@ def get_trade_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Trade", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Trade", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def get_trade_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address the trade belongs to") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the trade belongs to")], trade_id: Annotated[StrictStr, Field(description="The ID of the trade to fetch")], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Get a trade by ID @@ -766,7 +858,8 @@ def get_trade_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_trade_serialize( wallet_id=wallet_id, address_id=address_id, @@ -774,15 +867,19 @@ def get_trade_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Trade", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Trade", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _get_trade_serialize( self, wallet_id, @@ -793,39 +890,48 @@ def _get_trade_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id if trade_id is not None: - _path_params["trade_id"] = trade_id + _path_params['trade_id'] = trade_id # process the query parameters # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/trades/{trade_id}", + method='GET', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/trades/{trade_id}', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -835,36 +941,30 @@ def _get_trade_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def list_trades( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to list trades for") - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to list trades for")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> TradeList: """List trades for an address. @@ -899,7 +999,8 @@ def list_trades( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_trades_serialize( wallet_id=wallet_id, address_id=address_id, @@ -908,46 +1009,41 @@ def list_trades( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "TradeList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "TradeList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def list_trades_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to list trades for") - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to list trades for")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[TradeList]: """List trades for an address. @@ -982,7 +1078,8 @@ def list_trades_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_trades_serialize( wallet_id=wallet_id, address_id=address_id, @@ -991,46 +1088,41 @@ def list_trades_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "TradeList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "TradeList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def list_trades_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to list trades for") - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to list trades for")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), - ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """List trades for an address. @@ -1065,7 +1157,8 @@ def list_trades_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_trades_serialize( wallet_id=wallet_id, address_id=address_id, @@ -1074,15 +1167,19 @@ def list_trades_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "TradeList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "TradeList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _list_trades_serialize( self, wallet_id, @@ -1094,43 +1191,54 @@ def _list_trades_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id # process the query parameters if limit is not None: - _query_params.append(("limit", limit)) - + + _query_params.append(('limit', limit)) + if page is not None: - _query_params.append(("page", page)) - + + _query_params.append(('page', page)) + # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/trades", + method='GET', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/trades', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -1140,5 +1248,7 @@ def _list_trades_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + diff --git a/cdp/client/api/transaction_history_api.py b/cdp/client/api/transaction_history_api.py new file mode 100644 index 0000000..785824a --- /dev/null +++ b/cdp/client/api/transaction_history_api.py @@ -0,0 +1,346 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from pydantic import Field, StrictInt, StrictStr +from typing import Optional +from typing_extensions import Annotated +from cdp.client.models.address_transaction_list import AddressTransactionList + +from cdp.client.api_client import ApiClient, RequestSerialized +from cdp.client.api_response import ApiResponse +from cdp.client.rest import RESTResponseType + + +class TransactionHistoryApi: + """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) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def list_address_transactions( + self, + network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the transactions for.")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> AddressTransactionList: + """List transactions for an address. + + List all transactions that interact with the address. + + :param network_id: The ID of the blockchain network (required) + :type network_id: str + :param address_id: The ID of the address to fetch the transactions for. (required) + :type address_id: str + :param limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + :type limit: int + :param page: A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + :type page: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_address_transactions_serialize( + network_id=network_id, + address_id=address_id, + limit=limit, + page=page, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressTransactionList", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def list_address_transactions_with_http_info( + self, + network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the transactions for.")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[AddressTransactionList]: + """List transactions for an address. + + List all transactions that interact with the address. + + :param network_id: The ID of the blockchain network (required) + :type network_id: str + :param address_id: The ID of the address to fetch the transactions for. (required) + :type address_id: str + :param limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + :type limit: int + :param page: A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + :type page: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_address_transactions_serialize( + network_id=network_id, + address_id=address_id, + limit=limit, + page=page, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressTransactionList", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def list_address_transactions_without_preload_content( + self, + network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the transactions for.")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List transactions for an address. + + List all transactions that interact with the address. + + :param network_id: The ID of the blockchain network (required) + :type network_id: str + :param address_id: The ID of the address to fetch the transactions for. (required) + :type address_id: str + :param limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + :type limit: int + :param page: A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + :type page: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_address_transactions_serialize( + network_id=network_id, + address_id=address_id, + limit=limit, + page=page, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressTransactionList", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _list_address_transactions_serialize( + self, + network_id, + address_id, + limit, + page, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if network_id is not None: + _path_params['network_id'] = network_id + if address_id is not None: + _path_params['address_id'] = address_id + # process the query parameters + if limit is not None: + + _query_params.append(('limit', limit)) + + if page is not None: + + _query_params.append(('page', page)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v1/networks/{network_id}/addresses/{address_id}/transactions', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/cdp/client/api/transfers_api.py b/cdp/client/api/transfers_api.py index 6e5e1ad..0ed5523 100644 --- a/cdp/client/api/transfers_api.py +++ b/cdp/client/api/transfers_api.py @@ -1,23 +1,31 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from typing import Annotated, Any + Do not edit the class manually. +""" # noqa: E501 -from pydantic import Field, StrictFloat, StrictInt, StrictStr, validate_call +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated -from cdp.client.api_client import ApiClient, RequestSerialized -from cdp.client.api_response import ApiResponse +from pydantic import Field, StrictInt, StrictStr +from typing import Optional +from typing_extensions import Annotated from cdp.client.models.broadcast_transfer_request import BroadcastTransferRequest from cdp.client.models.create_transfer_request import CreateTransferRequest from cdp.client.models.transfer import Transfer from cdp.client.models.transfer_list import TransferList + +from cdp.client.api_client import ApiClient, RequestSerialized +from cdp.client.api_response import ApiResponse from cdp.client.rest import RESTResponseType @@ -33,23 +41,25 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def broadcast_transfer( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address the transfer belongs to") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the transfer belongs to")], transfer_id: Annotated[StrictStr, Field(description="The ID of the transfer to broadcast")], broadcast_transfer_request: BroadcastTransferRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Transfer: """Broadcast a transfer @@ -84,7 +94,8 @@ def broadcast_transfer( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._broadcast_transfer_serialize( wallet_id=wallet_id, address_id=address_id, @@ -93,36 +104,41 @@ def broadcast_transfer( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Transfer", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Transfer", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def broadcast_transfer_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address the transfer belongs to") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the transfer belongs to")], transfer_id: Annotated[StrictStr, Field(description="The ID of the transfer to broadcast")], broadcast_transfer_request: BroadcastTransferRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[Transfer]: """Broadcast a transfer @@ -157,7 +173,8 @@ def broadcast_transfer_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._broadcast_transfer_serialize( wallet_id=wallet_id, address_id=address_id, @@ -166,36 +183,41 @@ def broadcast_transfer_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Transfer", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Transfer", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def broadcast_transfer_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address the transfer belongs to") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the transfer belongs to")], transfer_id: Annotated[StrictStr, Field(description="The ID of the transfer to broadcast")], broadcast_transfer_request: BroadcastTransferRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Broadcast a transfer @@ -230,7 +252,8 @@ def broadcast_transfer_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._broadcast_transfer_serialize( wallet_id=wallet_id, address_id=address_id, @@ -239,15 +262,19 @@ def broadcast_transfer_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Transfer", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Transfer", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _broadcast_transfer_serialize( self, wallet_id, @@ -259,24 +286,26 @@ def _broadcast_transfer_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id if transfer_id is not None: - _path_params["transfer_id"] = transfer_id + _path_params['transfer_id'] = transfer_id # process the query parameters # process the header parameters # process the form parameters @@ -284,24 +313,36 @@ def _broadcast_transfer_serialize( if broadcast_transfer_request is not None: _body_params = broadcast_transfer_request + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` if _content_type: - _header_params["Content-Type"] = _content_type + _header_params['Content-Type'] = _content_type else: - _default_content_type = self.api_client.select_header_content_type(["application/json"]) + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) if _default_content_type is not None: - _header_params["Content-Type"] = _default_content_type + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="POST", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/transfers/{transfer_id}/broadcast", + method='POST', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/transfers/{transfer_id}/broadcast', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -311,25 +352,29 @@ def _broadcast_transfer_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def create_transfer( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the source address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to transfer from") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the source address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to transfer from")], create_transfer_request: CreateTransferRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Transfer: """Create a new transfer for an address @@ -362,7 +407,8 @@ def create_transfer( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_transfer_serialize( wallet_id=wallet_id, address_id=address_id, @@ -370,35 +416,40 @@ def create_transfer( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Transfer", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Transfer", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def create_transfer_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the source address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to transfer from") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the source address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to transfer from")], create_transfer_request: CreateTransferRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[Transfer]: """Create a new transfer for an address @@ -431,7 +482,8 @@ def create_transfer_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_transfer_serialize( wallet_id=wallet_id, address_id=address_id, @@ -439,35 +491,40 @@ def create_transfer_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Transfer", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Transfer", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def create_transfer_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the source address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to transfer from") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the source address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to transfer from")], create_transfer_request: CreateTransferRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Create a new transfer for an address @@ -500,7 +557,8 @@ def create_transfer_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_transfer_serialize( wallet_id=wallet_id, address_id=address_id, @@ -508,15 +566,19 @@ def create_transfer_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Transfer", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Transfer", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _create_transfer_serialize( self, wallet_id, @@ -527,22 +589,24 @@ def _create_transfer_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id # process the query parameters # process the header parameters # process the form parameters @@ -550,24 +614,36 @@ def _create_transfer_serialize( if create_transfer_request is not None: _body_params = create_transfer_request + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` if _content_type: - _header_params["Content-Type"] = _content_type + _header_params['Content-Type'] = _content_type else: - _default_content_type = self.api_client.select_header_content_type(["application/json"]) + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) if _default_content_type is not None: - _header_params["Content-Type"] = _default_content_type + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="POST", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/transfers", + method='POST', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/transfers', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -577,25 +653,29 @@ def _create_transfer_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def get_transfer( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address the transfer belongs to") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the transfer belongs to")], transfer_id: Annotated[StrictStr, Field(description="The ID of the transfer to fetch")], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Transfer: """Get a transfer by ID @@ -628,7 +708,8 @@ def get_transfer( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_transfer_serialize( wallet_id=wallet_id, address_id=address_id, @@ -636,35 +717,40 @@ def get_transfer( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Transfer", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Transfer", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def get_transfer_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address the transfer belongs to") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the transfer belongs to")], transfer_id: Annotated[StrictStr, Field(description="The ID of the transfer to fetch")], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[Transfer]: """Get a transfer by ID @@ -697,7 +783,8 @@ def get_transfer_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_transfer_serialize( wallet_id=wallet_id, address_id=address_id, @@ -705,35 +792,40 @@ def get_transfer_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Transfer", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Transfer", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def get_transfer_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address the transfer belongs to") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the transfer belongs to")], transfer_id: Annotated[StrictStr, Field(description="The ID of the transfer to fetch")], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Get a transfer by ID @@ -766,7 +858,8 @@ def get_transfer_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_transfer_serialize( wallet_id=wallet_id, address_id=address_id, @@ -774,15 +867,19 @@ def get_transfer_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Transfer", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Transfer", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _get_transfer_serialize( self, wallet_id, @@ -793,39 +890,48 @@ def _get_transfer_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id if transfer_id is not None: - _path_params["transfer_id"] = transfer_id + _path_params['transfer_id'] = transfer_id # process the query parameters # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/transfers/{transfer_id}", + method='GET', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/transfers/{transfer_id}', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -835,36 +941,30 @@ def _get_transfer_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def list_transfers( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to list transfers for") - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to list transfers for")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> TransferList: """List transfers for an address. @@ -899,7 +999,8 @@ def list_transfers( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_transfers_serialize( wallet_id=wallet_id, address_id=address_id, @@ -908,46 +1009,41 @@ def list_transfers( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "TransferList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "TransferList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def list_transfers_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to list transfers for") - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to list transfers for")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[TransferList]: """List transfers for an address. @@ -982,7 +1078,8 @@ def list_transfers_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_transfers_serialize( wallet_id=wallet_id, address_id=address_id, @@ -991,46 +1088,41 @@ def list_transfers_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "TransferList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "TransferList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def list_transfers_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address to list transfers for") - ], - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to list transfers for")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), - ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """List transfers for an address. @@ -1065,7 +1157,8 @@ def list_transfers_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_transfers_serialize( wallet_id=wallet_id, address_id=address_id, @@ -1074,15 +1167,19 @@ def list_transfers_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "TransferList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "TransferList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _list_transfers_serialize( self, wallet_id, @@ -1094,43 +1191,54 @@ def _list_transfers_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id # process the query parameters if limit is not None: - _query_params.append(("limit", limit)) - + + _query_params.append(('limit', limit)) + if page is not None: - _query_params.append(("page", page)) - + + _query_params.append(('page', page)) + # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/transfers", + method='GET', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/transfers', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -1140,5 +1248,7 @@ def _list_transfers_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + diff --git a/cdp/client/api/users_api.py b/cdp/client/api/users_api.py index 584ac8f..8afc9b9 100644 --- a/cdp/client/api/users_api.py +++ b/cdp/client/api/users_api.py @@ -1,20 +1,25 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 -from typing import Annotated, Any +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated -from pydantic import Field, StrictFloat, StrictInt, StrictStr, validate_call +from cdp.client.models.user import User from cdp.client.api_client import ApiClient, RequestSerialized from cdp.client.api_response import ApiResponse -from cdp.client.models.user import User from cdp.client.rest import RESTResponseType @@ -30,15 +35,21 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def get_current_user( self, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> User: """Get current user @@ -65,33 +76,43 @@ def get_current_user( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_current_user_serialize( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "User", + _response_types_map: Dict[str, Optional[str]] = { + '200': "User", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def get_current_user_with_http_info( self, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[User]: """Get current user @@ -118,33 +139,43 @@ def get_current_user_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_current_user_serialize( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "User", + _response_types_map: Dict[str, Optional[str]] = { + '200': "User", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def get_current_user_without_preload_content( self, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Get current user @@ -171,20 +202,25 @@ def get_current_user_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_current_user_serialize( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "User", + _response_types_map: Dict[str, Optional[str]] = { + '200': "User", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _get_current_user_serialize( self, _request_auth, @@ -192,16 +228,18 @@ def _get_current_user_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters # process the query parameters @@ -209,16 +247,23 @@ def _get_current_user_serialize( # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/users/me", + method='GET', + resource_path='/v1/users/me', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -228,5 +273,7 @@ def _get_current_user_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + diff --git a/cdp/client/api/validators_api.py b/cdp/client/api/validators_api.py index 01cde90..66e62b8 100644 --- a/cdp/client/api/validators_api.py +++ b/cdp/client/api/validators_api.py @@ -1,22 +1,30 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from typing import Annotated, Any + Do not edit the class manually. +""" # noqa: E501 -from pydantic import Field, StrictFloat, StrictInt, StrictStr, validate_call +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated -from cdp.client.api_client import ApiClient, RequestSerialized -from cdp.client.api_response import ApiResponse +from pydantic import Field, StrictInt, StrictStr +from typing import Optional +from typing_extensions import Annotated from cdp.client.models.validator import Validator from cdp.client.models.validator_list import ValidatorList from cdp.client.models.validator_status import ValidatorStatus + +from cdp.client.api_client import ApiClient, RequestSerialized +from cdp.client.api_response import ApiResponse from cdp.client.rest import RESTResponseType @@ -32,22 +40,24 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def get_validator( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network.")], - asset_id: Annotated[ - StrictStr, Field(description="The symbol of the asset to get the validator for.") - ], - validator_id: Annotated[ - StrictStr, Field(description="The unique id of the validator to fetch details for.") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + asset_id: Annotated[StrictStr, Field(description="The symbol of the asset to get the validator for.")], + validator_id: Annotated[StrictStr, Field(description="The unique id of the validator to fetch details for.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Validator: """Get a validator belonging to the CDP project @@ -80,7 +90,8 @@ def get_validator( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_validator_serialize( network_id=network_id, asset_id=asset_id, @@ -88,35 +99,40 @@ def get_validator( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Validator", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Validator", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def get_validator_with_http_info( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network.")], - asset_id: Annotated[ - StrictStr, Field(description="The symbol of the asset to get the validator for.") - ], - validator_id: Annotated[ - StrictStr, Field(description="The unique id of the validator to fetch details for.") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + asset_id: Annotated[StrictStr, Field(description="The symbol of the asset to get the validator for.")], + validator_id: Annotated[StrictStr, Field(description="The unique id of the validator to fetch details for.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[Validator]: """Get a validator belonging to the CDP project @@ -149,7 +165,8 @@ def get_validator_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_validator_serialize( network_id=network_id, asset_id=asset_id, @@ -157,35 +174,40 @@ def get_validator_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Validator", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Validator", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def get_validator_without_preload_content( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network.")], - asset_id: Annotated[ - StrictStr, Field(description="The symbol of the asset to get the validator for.") - ], - validator_id: Annotated[ - StrictStr, Field(description="The unique id of the validator to fetch details for.") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + asset_id: Annotated[StrictStr, Field(description="The symbol of the asset to get the validator for.")], + validator_id: Annotated[StrictStr, Field(description="The unique id of the validator to fetch details for.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Get a validator belonging to the CDP project @@ -218,7 +240,8 @@ def get_validator_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_validator_serialize( network_id=network_id, asset_id=asset_id, @@ -226,15 +249,19 @@ def get_validator_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Validator", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Validator", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _get_validator_serialize( self, network_id, @@ -245,39 +272,48 @@ def _get_validator_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if network_id is not None: - _path_params["network_id"] = network_id + _path_params['network_id'] = network_id if asset_id is not None: - _path_params["asset_id"] = asset_id + _path_params['asset_id'] = asset_id if validator_id is not None: - _path_params["validator_id"] = validator_id + _path_params['validator_id'] = validator_id # process the query parameters # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/networks/{network_id}/assets/{asset_id}/validators/{validator_id}", + method='GET', + resource_path='/v1/networks/{network_id}/assets/{asset_id}/validators/{validator_id}', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -287,38 +323,31 @@ def _get_validator_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def list_validators( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network.")], - asset_id: Annotated[ - StrictStr, Field(description="The symbol of the asset to get the validators for.") - ], - status: Annotated[ - ValidatorStatus | None, - Field(description="A filter to list validators based on a status."), - ] = None, - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + asset_id: Annotated[StrictStr, Field(description="The symbol of the asset to get the validators for.")], + status: Annotated[Optional[ValidatorStatus], Field(description="A filter to list validators based on a status.")] = None, + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ValidatorList: """List validators belonging to the CDP project @@ -355,7 +384,8 @@ def list_validators( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_validators_serialize( network_id=network_id, asset_id=asset_id, @@ -365,48 +395,42 @@ def list_validators( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ValidatorList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ValidatorList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def list_validators_with_http_info( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network.")], - asset_id: Annotated[ - StrictStr, Field(description="The symbol of the asset to get the validators for.") - ], - status: Annotated[ - ValidatorStatus | None, - Field(description="A filter to list validators based on a status."), + asset_id: Annotated[StrictStr, Field(description="The symbol of the asset to get the validators for.")], + status: Annotated[Optional[ValidatorStatus], Field(description="A filter to list validators based on a status.")] = None, + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), - ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[ValidatorList]: """List validators belonging to the CDP project @@ -443,7 +467,8 @@ def list_validators_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_validators_serialize( network_id=network_id, asset_id=asset_id, @@ -453,48 +478,42 @@ def list_validators_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ValidatorList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ValidatorList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def list_validators_without_preload_content( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network.")], - asset_id: Annotated[ - StrictStr, Field(description="The symbol of the asset to get the validators for.") - ], - status: Annotated[ - ValidatorStatus | None, - Field(description="A filter to list validators based on a status."), - ] = None, - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + asset_id: Annotated[StrictStr, Field(description="The symbol of the asset to get the validators for.")], + status: Annotated[Optional[ValidatorStatus], Field(description="A filter to list validators based on a status.")] = None, + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """List validators belonging to the CDP project @@ -531,7 +550,8 @@ def list_validators_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_validators_serialize( network_id=network_id, asset_id=asset_id, @@ -541,15 +561,19 @@ def list_validators_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "ValidatorList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "ValidatorList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _list_validators_serialize( self, network_id, @@ -562,46 +586,58 @@ def _list_validators_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if network_id is not None: - _path_params["network_id"] = network_id + _path_params['network_id'] = network_id if asset_id is not None: - _path_params["asset_id"] = asset_id + _path_params['asset_id'] = asset_id # process the query parameters if status is not None: - _query_params.append(("status", status.value)) - + + _query_params.append(('status', status.value)) + if limit is not None: - _query_params.append(("limit", limit)) - + + _query_params.append(('limit', limit)) + if page is not None: - _query_params.append(("page", page)) - + + _query_params.append(('page', page)) + # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/networks/{network_id}/assets/{asset_id}/validators", + method='GET', + resource_path='/v1/networks/{network_id}/assets/{asset_id}/validators', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -611,5 +647,7 @@ def _list_validators_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + diff --git a/cdp/client/api/wallet_stake_api.py b/cdp/client/api/wallet_stake_api.py index e9d8a89..1e51cbd 100644 --- a/cdp/client/api/wallet_stake_api.py +++ b/cdp/client/api/wallet_stake_api.py @@ -1,22 +1,29 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from typing import Annotated, Any + Do not edit the class manually. +""" # noqa: E501 -from pydantic import Field, StrictFloat, StrictInt, StrictStr, validate_call +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated -from cdp.client.api_client import ApiClient, RequestSerialized -from cdp.client.api_response import ApiResponse +from pydantic import Field, StrictStr +from typing_extensions import Annotated from cdp.client.models.broadcast_staking_operation_request import BroadcastStakingOperationRequest from cdp.client.models.create_staking_operation_request import CreateStakingOperationRequest from cdp.client.models.staking_operation import StakingOperation + +from cdp.client.api_client import ApiClient, RequestSerialized +from cdp.client.api_response import ApiResponse from cdp.client.rest import RESTResponseType @@ -32,25 +39,25 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def broadcast_staking_operation( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address the staking operation belongs to.") - ], - staking_operation_id: Annotated[ - StrictStr, Field(description="The ID of the staking operation to broadcast.") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the staking operation belongs to.")], + staking_operation_id: Annotated[StrictStr, Field(description="The ID of the staking operation to broadcast.")], broadcast_staking_operation_request: BroadcastStakingOperationRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> StakingOperation: """Broadcast a staking operation @@ -85,7 +92,8 @@ def broadcast_staking_operation( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._broadcast_staking_operation_serialize( wallet_id=wallet_id, address_id=address_id, @@ -94,38 +102,41 @@ def broadcast_staking_operation( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "StakingOperation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def broadcast_staking_operation_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address the staking operation belongs to.") - ], - staking_operation_id: Annotated[ - StrictStr, Field(description="The ID of the staking operation to broadcast.") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the staking operation belongs to.")], + staking_operation_id: Annotated[StrictStr, Field(description="The ID of the staking operation to broadcast.")], broadcast_staking_operation_request: BroadcastStakingOperationRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[StakingOperation]: """Broadcast a staking operation @@ -160,7 +171,8 @@ def broadcast_staking_operation_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._broadcast_staking_operation_serialize( wallet_id=wallet_id, address_id=address_id, @@ -169,38 +181,41 @@ def broadcast_staking_operation_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "StakingOperation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def broadcast_staking_operation_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, Field(description="The ID of the address the staking operation belongs to.") - ], - staking_operation_id: Annotated[ - StrictStr, Field(description="The ID of the staking operation to broadcast.") - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the staking operation belongs to.")], + staking_operation_id: Annotated[StrictStr, Field(description="The ID of the staking operation to broadcast.")], broadcast_staking_operation_request: BroadcastStakingOperationRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Broadcast a staking operation @@ -235,7 +250,8 @@ def broadcast_staking_operation_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._broadcast_staking_operation_serialize( wallet_id=wallet_id, address_id=address_id, @@ -244,15 +260,19 @@ def broadcast_staking_operation_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "StakingOperation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _broadcast_staking_operation_serialize( self, wallet_id, @@ -264,24 +284,26 @@ def _broadcast_staking_operation_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id if staking_operation_id is not None: - _path_params["staking_operation_id"] = staking_operation_id + _path_params['staking_operation_id'] = staking_operation_id # process the query parameters # process the header parameters # process the form parameters @@ -289,24 +311,36 @@ def _broadcast_staking_operation_serialize( if broadcast_staking_operation_request is not None: _body_params = broadcast_staking_operation_request + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` if _content_type: - _header_params["Content-Type"] = _content_type + _header_params['Content-Type'] = _content_type else: - _default_content_type = self.api_client.select_header_content_type(["application/json"]) + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) if _default_content_type is not None: - _header_params["Content-Type"] = _default_content_type + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="POST", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/staking_operations/{staking_operation_id}/broadcast", + method='POST', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/staking_operations/{staking_operation_id}/broadcast', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -316,26 +350,29 @@ def _broadcast_staking_operation_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def create_staking_operation( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The ID of the address to create the staking operation for."), - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to create the staking operation for.")], create_staking_operation_request: CreateStakingOperationRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> StakingOperation: """Create a new staking operation for an address @@ -368,7 +405,8 @@ def create_staking_operation( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_staking_operation_serialize( wallet_id=wallet_id, address_id=address_id, @@ -376,36 +414,40 @@ def create_staking_operation( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "StakingOperation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def create_staking_operation_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The ID of the address to create the staking operation for."), - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to create the staking operation for.")], create_staking_operation_request: CreateStakingOperationRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[StakingOperation]: """Create a new staking operation for an address @@ -438,7 +480,8 @@ def create_staking_operation_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_staking_operation_serialize( wallet_id=wallet_id, address_id=address_id, @@ -446,36 +489,40 @@ def create_staking_operation_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "StakingOperation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def create_staking_operation_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to.") - ], - address_id: Annotated[ - StrictStr, - Field(description="The ID of the address to create the staking operation for."), - ], + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to create the staking operation for.")], create_staking_operation_request: CreateStakingOperationRequest, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Create a new staking operation for an address @@ -508,7 +555,8 @@ def create_staking_operation_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_staking_operation_serialize( wallet_id=wallet_id, address_id=address_id, @@ -516,15 +564,19 @@ def create_staking_operation_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "StakingOperation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _create_staking_operation_serialize( self, wallet_id, @@ -535,22 +587,24 @@ def _create_staking_operation_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id # process the query parameters # process the header parameters # process the form parameters @@ -558,24 +612,36 @@ def _create_staking_operation_serialize( if create_staking_operation_request is not None: _body_params = create_staking_operation_request + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` if _content_type: - _header_params["Content-Type"] = _content_type + _header_params['Content-Type'] = _content_type else: - _default_content_type = self.api_client.select_header_content_type(["application/json"]) + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) if _default_content_type is not None: - _header_params["Content-Type"] = _default_content_type + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="POST", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/staking_operations", + method='POST', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/staking_operations', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -585,28 +651,29 @@ def _create_staking_operation_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def get_staking_operation( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to") - ], - address_id: Annotated[ - StrictStr, - Field(description="The ID of the address to fetch the staking operation for."), - ], - staking_operation_id: Annotated[ - StrictStr, Field(description="The ID of the staking operation.") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the staking operation for.")], + staking_operation_id: Annotated[StrictStr, Field(description="The ID of the staking operation.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> StakingOperation: """Get the latest state of a staking operation @@ -639,7 +706,8 @@ def get_staking_operation( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_staking_operation_serialize( wallet_id=wallet_id, address_id=address_id, @@ -647,38 +715,40 @@ def get_staking_operation( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "StakingOperation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def get_staking_operation_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to") - ], - address_id: Annotated[ - StrictStr, - Field(description="The ID of the address to fetch the staking operation for."), - ], - staking_operation_id: Annotated[ - StrictStr, Field(description="The ID of the staking operation.") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the staking operation for.")], + staking_operation_id: Annotated[StrictStr, Field(description="The ID of the staking operation.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[StakingOperation]: """Get the latest state of a staking operation @@ -711,7 +781,8 @@ def get_staking_operation_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_staking_operation_serialize( wallet_id=wallet_id, address_id=address_id, @@ -719,38 +790,40 @@ def get_staking_operation_with_http_info( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "StakingOperation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def get_staking_operation_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet the address belongs to") - ], - address_id: Annotated[ - StrictStr, - Field(description="The ID of the address to fetch the staking operation for."), - ], - staking_operation_id: Annotated[ - StrictStr, Field(description="The ID of the staking operation.") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the staking operation for.")], + staking_operation_id: Annotated[StrictStr, Field(description="The ID of the staking operation.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Get the latest state of a staking operation @@ -783,7 +856,8 @@ def get_staking_operation_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_staking_operation_serialize( wallet_id=wallet_id, address_id=address_id, @@ -791,15 +865,19 @@ def get_staking_operation_without_preload_content( _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "StakingOperation", + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _get_staking_operation_serialize( self, wallet_id, @@ -810,39 +888,48 @@ def _get_staking_operation_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if address_id is not None: - _path_params["address_id"] = address_id + _path_params['address_id'] = address_id if staking_operation_id is not None: - _path_params["staking_operation_id"] = staking_operation_id + _path_params['staking_operation_id'] = staking_operation_id # process the query parameters # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/wallets/{wallet_id}/addresses/{address_id}/staking_operations/{staking_operation_id}", + method='GET', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/staking_operations/{staking_operation_id}', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -852,5 +939,7 @@ def _get_staking_operation_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + diff --git a/cdp/client/api/wallets_api.py b/cdp/client/api/wallets_api.py index bec76ef..86cd94b 100644 --- a/cdp/client/api/wallets_api.py +++ b/cdp/client/api/wallets_api.py @@ -1,24 +1,32 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from typing import Annotated, Any + Do not edit the class manually. +""" # noqa: E501 -from pydantic import Field, StrictFloat, StrictInt, StrictStr, validate_call +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated -from cdp.client.api_client import ApiClient, RequestSerialized -from cdp.client.api_response import ApiResponse +from pydantic import Field, StrictInt, StrictStr +from typing import Optional +from typing_extensions import Annotated from cdp.client.models.address_balance_list import AddressBalanceList from cdp.client.models.balance import Balance from cdp.client.models.create_wallet_request import CreateWalletRequest from cdp.client.models.wallet import Wallet from cdp.client.models.wallet_list import WalletList + +from cdp.client.api_client import ApiClient, RequestSerialized +from cdp.client.api_response import ApiResponse from cdp.client.rest import RESTResponseType @@ -34,16 +42,22 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def create_wallet( self, - create_wallet_request: CreateWalletRequest | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + create_wallet_request: Optional[CreateWalletRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Wallet: """Create a new wallet @@ -72,35 +86,45 @@ def create_wallet( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_wallet_serialize( create_wallet_request=create_wallet_request, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Wallet", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Wallet", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def create_wallet_with_http_info( self, - create_wallet_request: CreateWalletRequest | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + create_wallet_request: Optional[CreateWalletRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[Wallet]: """Create a new wallet @@ -129,35 +153,45 @@ def create_wallet_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_wallet_serialize( create_wallet_request=create_wallet_request, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Wallet", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Wallet", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def create_wallet_without_preload_content( self, - create_wallet_request: CreateWalletRequest | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + create_wallet_request: Optional[CreateWalletRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Create a new wallet @@ -186,21 +220,26 @@ def create_wallet_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_wallet_serialize( create_wallet_request=create_wallet_request, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Wallet", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Wallet", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _create_wallet_serialize( self, create_wallet_request, @@ -209,16 +248,18 @@ def _create_wallet_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters # process the query parameters @@ -228,24 +269,36 @@ def _create_wallet_serialize( if create_wallet_request is not None: _body_params = create_wallet_request + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` if _content_type: - _header_params["Content-Type"] = _content_type + _header_params['Content-Type'] = _content_type else: - _default_content_type = self.api_client.select_header_content_type(["application/json"]) + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) if _default_content_type is not None: - _header_params["Content-Type"] = _default_content_type + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="POST", - resource_path="/v1/wallets", + method='POST', + resource_path='/v1/wallets', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -255,19 +308,27 @@ def _create_wallet_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def get_wallet( self, wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet to fetch")], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Wallet: """Get wallet by ID @@ -296,35 +357,45 @@ def get_wallet( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_wallet_serialize( wallet_id=wallet_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Wallet", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Wallet", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def get_wallet_with_http_info( self, wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet to fetch")], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[Wallet]: """Get wallet by ID @@ -353,35 +424,45 @@ def get_wallet_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_wallet_serialize( wallet_id=wallet_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Wallet", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Wallet", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def get_wallet_without_preload_content( self, wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet to fetch")], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Get wallet by ID @@ -410,21 +491,26 @@ def get_wallet_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_wallet_serialize( wallet_id=wallet_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Wallet", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Wallet", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _get_wallet_serialize( self, wallet_id, @@ -433,35 +519,44 @@ def _get_wallet_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id # process the query parameters # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/wallets/{wallet_id}", + method='GET', + resource_path='/v1/wallets/{wallet_id}', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -471,24 +566,28 @@ def _get_wallet_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def get_wallet_balance( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet to fetch the balance for") - ], - asset_id: Annotated[ - StrictStr, Field(description="The symbol of the asset to fetch the balance for") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet to fetch the balance for")], + asset_id: Annotated[StrictStr, Field(description="The symbol of the asset to fetch the balance for")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Balance: """Get the balance of an asset in the wallet @@ -519,41 +618,47 @@ def get_wallet_balance( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_wallet_balance_serialize( wallet_id=wallet_id, asset_id=asset_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Balance", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Balance", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def get_wallet_balance_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet to fetch the balance for") - ], - asset_id: Annotated[ - StrictStr, Field(description="The symbol of the asset to fetch the balance for") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet to fetch the balance for")], + asset_id: Annotated[StrictStr, Field(description="The symbol of the asset to fetch the balance for")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[Balance]: """Get the balance of an asset in the wallet @@ -584,41 +689,47 @@ def get_wallet_balance_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_wallet_balance_serialize( wallet_id=wallet_id, asset_id=asset_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Balance", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Balance", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def get_wallet_balance_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet to fetch the balance for") - ], - asset_id: Annotated[ - StrictStr, Field(description="The symbol of the asset to fetch the balance for") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet to fetch the balance for")], + asset_id: Annotated[StrictStr, Field(description="The symbol of the asset to fetch the balance for")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Get the balance of an asset in the wallet @@ -649,22 +760,27 @@ def get_wallet_balance_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._get_wallet_balance_serialize( wallet_id=wallet_id, asset_id=asset_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Balance", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Balance", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _get_wallet_balance_serialize( self, wallet_id, @@ -674,37 +790,46 @@ def _get_wallet_balance_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id if asset_id is not None: - _path_params["asset_id"] = asset_id + _path_params['asset_id'] = asset_id # process the query parameters # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/wallets/{wallet_id}/balances/{asset_id}", + method='GET', + resource_path='/v1/wallets/{wallet_id}/balances/{asset_id}', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -714,21 +839,27 @@ def _get_wallet_balance_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def list_wallet_balances( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet to fetch the balances for") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet to fetch the balances for")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> AddressBalanceList: """List wallet balances @@ -757,37 +888,45 @@ def list_wallet_balances( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_wallet_balances_serialize( wallet_id=wallet_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "AddressBalanceList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressBalanceList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def list_wallet_balances_with_http_info( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet to fetch the balances for") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet to fetch the balances for")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[AddressBalanceList]: """List wallet balances @@ -816,37 +955,45 @@ def list_wallet_balances_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_wallet_balances_serialize( wallet_id=wallet_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "AddressBalanceList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressBalanceList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def list_wallet_balances_without_preload_content( self, - wallet_id: Annotated[ - StrictStr, Field(description="The ID of the wallet to fetch the balances for") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet to fetch the balances for")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """List wallet balances @@ -875,21 +1022,26 @@ def list_wallet_balances_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_wallet_balances_serialize( wallet_id=wallet_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "AddressBalanceList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressBalanceList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _list_wallet_balances_serialize( self, wallet_id, @@ -898,35 +1050,44 @@ def _list_wallet_balances_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if wallet_id is not None: - _path_params["wallet_id"] = wallet_id + _path_params['wallet_id'] = wallet_id # process the query parameters # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/wallets/{wallet_id}/balances", + method='GET', + resource_path='/v1/wallets/{wallet_id}/balances', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -936,30 +1097,28 @@ def _list_wallet_balances_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def list_wallets( self, - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> WalletList: """List wallets @@ -990,47 +1149,47 @@ def list_wallets( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_wallets_serialize( limit=limit, page=page, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "WalletList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "WalletList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def list_wallets_with_http_info( self, - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[WalletList]: """List wallets @@ -1061,47 +1220,47 @@ def list_wallets_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_wallets_serialize( limit=limit, page=page, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "WalletList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "WalletList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def list_wallets_without_preload_content( self, - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), - ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """List wallets @@ -1132,22 +1291,27 @@ def list_wallets_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_wallets_serialize( limit=limit, page=page, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "WalletList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "WalletList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _list_wallets_serialize( self, limit, @@ -1157,39 +1321,50 @@ def _list_wallets_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters # process the query parameters if limit is not None: - _query_params.append(("limit", limit)) - + + _query_params.append(('limit', limit)) + if page is not None: - _query_params.append(("page", page)) - + + _query_params.append(('page', page)) + # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/wallets", + method='GET', + resource_path='/v1/wallets', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -1199,5 +1374,7 @@ def _list_wallets_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + diff --git a/cdp/client/api/webhooks_api.py b/cdp/client/api/webhooks_api.py index d17fa49..7e0f4c7 100644 --- a/cdp/client/api/webhooks_api.py +++ b/cdp/client/api/webhooks_api.py @@ -1,23 +1,32 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from typing import Annotated, Any + Do not edit the class manually. +""" # noqa: E501 -from pydantic import Field, StrictFloat, StrictInt, StrictStr, validate_call +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated -from cdp.client.api_client import ApiClient, RequestSerialized -from cdp.client.api_response import ApiResponse +from pydantic import Field, StrictInt, StrictStr +from typing import Optional +from typing_extensions import Annotated +from cdp.client.models.create_wallet_webhook_request import CreateWalletWebhookRequest from cdp.client.models.create_webhook_request import CreateWebhookRequest from cdp.client.models.update_webhook_request import UpdateWebhookRequest from cdp.client.models.webhook import Webhook from cdp.client.models.webhook_list import WebhookList + +from cdp.client.api_client import ApiClient, RequestSerialized +from cdp.client.api_response import ApiResponse from cdp.client.rest import RESTResponseType @@ -33,16 +42,308 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + + @validate_call + def create_wallet_webhook( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet to create the webhook for.")], + create_wallet_webhook_request: Optional[CreateWalletWebhookRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Webhook: + """Create a new webhook scoped to a wallet + + Create a new webhook scoped to a wallet + + :param wallet_id: The ID of the wallet to create the webhook for. (required) + :type wallet_id: str + :param create_wallet_webhook_request: + :type create_wallet_webhook_request: CreateWalletWebhookRequest + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_wallet_webhook_serialize( + wallet_id=wallet_id, + create_wallet_webhook_request=create_wallet_webhook_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Webhook", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def create_wallet_webhook_with_http_info( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet to create the webhook for.")], + create_wallet_webhook_request: Optional[CreateWalletWebhookRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Webhook]: + """Create a new webhook scoped to a wallet + + Create a new webhook scoped to a wallet + + :param wallet_id: The ID of the wallet to create the webhook for. (required) + :type wallet_id: str + :param create_wallet_webhook_request: + :type create_wallet_webhook_request: CreateWalletWebhookRequest + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_wallet_webhook_serialize( + wallet_id=wallet_id, + create_wallet_webhook_request=create_wallet_webhook_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Webhook", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def create_wallet_webhook_without_preload_content( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet to create the webhook for.")], + create_wallet_webhook_request: Optional[CreateWalletWebhookRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Create a new webhook scoped to a wallet + + Create a new webhook scoped to a wallet + + :param wallet_id: The ID of the wallet to create the webhook for. (required) + :type wallet_id: str + :param create_wallet_webhook_request: + :type create_wallet_webhook_request: CreateWalletWebhookRequest + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_wallet_webhook_serialize( + wallet_id=wallet_id, + create_wallet_webhook_request=create_wallet_webhook_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Webhook", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _create_wallet_webhook_serialize( + self, + wallet_id, + create_wallet_webhook_request, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if wallet_id is not None: + _path_params['wallet_id'] = wallet_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if create_wallet_webhook_request is not None: + _body_params = create_wallet_webhook_request + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/v1/wallets/{wallet_id}/webhooks', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + @validate_call def create_webhook( self, - create_webhook_request: CreateWebhookRequest | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + create_webhook_request: Optional[CreateWebhookRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Webhook: """Create a new webhook @@ -71,35 +372,45 @@ def create_webhook( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_webhook_serialize( create_webhook_request=create_webhook_request, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Webhook", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Webhook", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def create_webhook_with_http_info( self, - create_webhook_request: CreateWebhookRequest | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + create_webhook_request: Optional[CreateWebhookRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[Webhook]: """Create a new webhook @@ -128,35 +439,45 @@ def create_webhook_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_webhook_serialize( create_webhook_request=create_webhook_request, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Webhook", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Webhook", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def create_webhook_without_preload_content( self, - create_webhook_request: CreateWebhookRequest | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + create_webhook_request: Optional[CreateWebhookRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Create a new webhook @@ -185,21 +506,26 @@ def create_webhook_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._create_webhook_serialize( create_webhook_request=create_webhook_request, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Webhook", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Webhook", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _create_webhook_serialize( self, create_webhook_request, @@ -208,16 +534,18 @@ def _create_webhook_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters # process the query parameters @@ -227,24 +555,36 @@ def _create_webhook_serialize( if create_webhook_request is not None: _body_params = create_webhook_request + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` if _content_type: - _header_params["Content-Type"] = _content_type + _header_params['Content-Type'] = _content_type else: - _default_content_type = self.api_client.select_header_content_type(["application/json"]) + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) if _default_content_type is not None: - _header_params["Content-Type"] = _default_content_type + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="POST", - resource_path="/v1/webhooks", + method='POST', + resource_path='/v1/webhooks', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -254,21 +594,27 @@ def _create_webhook_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def delete_webhook( self, - webhook_id: Annotated[ - StrictStr, Field(description="The Webhook uuid that needs to be deleted") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + webhook_id: Annotated[StrictStr, Field(description="The Webhook uuid that needs to be deleted")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: """Delete a webhook @@ -297,37 +643,45 @@ def delete_webhook( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._delete_webhook_serialize( webhook_id=webhook_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": None, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def delete_webhook_with_http_info( self, - webhook_id: Annotated[ - StrictStr, Field(description="The Webhook uuid that needs to be deleted") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + webhook_id: Annotated[StrictStr, Field(description="The Webhook uuid that needs to be deleted")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[None]: """Delete a webhook @@ -356,37 +710,45 @@ def delete_webhook_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._delete_webhook_serialize( webhook_id=webhook_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": None, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def delete_webhook_without_preload_content( self, - webhook_id: Annotated[ - StrictStr, Field(description="The Webhook uuid that needs to be deleted") - ], - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + webhook_id: Annotated[StrictStr, Field(description="The Webhook uuid that needs to be deleted")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Delete a webhook @@ -415,21 +777,26 @@ def delete_webhook_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._delete_webhook_serialize( webhook_id=webhook_id, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": None, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _delete_webhook_serialize( self, webhook_id, @@ -438,35 +805,44 @@ def _delete_webhook_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if webhook_id is not None: - _path_params["webhook_id"] = webhook_id + _path_params['webhook_id'] = webhook_id # process the query parameters # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="DELETE", - resource_path="/v1/webhooks/{webhook_id}", + method='DELETE', + resource_path='/v1/webhooks/{webhook_id}', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -476,30 +852,28 @@ def _delete_webhook_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def list_webhooks( self, - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> WebhookList: """List webhooks @@ -530,47 +904,47 @@ def list_webhooks( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_webhooks_serialize( limit=limit, page=page, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "WebhookList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "WebhookList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def list_webhooks_with_http_info( self, - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[WebhookList]: """List webhooks @@ -601,47 +975,47 @@ def list_webhooks_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_webhooks_serialize( limit=limit, page=page, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "WebhookList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "WebhookList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def list_webhooks_without_preload_content( self, - limit: Annotated[ - StrictInt | None, - Field( - description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10." - ), - ] = None, - page: Annotated[ - Annotated[str, Field(strict=True, max_length=5000)] | None, - Field( - description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results." - ), + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] ] = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """List webhooks @@ -672,22 +1046,27 @@ def list_webhooks_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._list_webhooks_serialize( limit=limit, page=page, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "WebhookList", + _response_types_map: Dict[str, Optional[str]] = { + '200': "WebhookList", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _list_webhooks_serialize( self, limit, @@ -697,39 +1076,50 @@ def _list_webhooks_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters # process the query parameters if limit is not None: - _query_params.append(("limit", limit)) - + + _query_params.append(('limit', limit)) + if page is not None: - _query_params.append(("page", page)) - + + _query_params.append(('page', page)) + # process the header parameters # process the form parameters # process the body parameter + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="GET", - resource_path="/v1/webhooks", + method='GET', + resource_path='/v1/webhooks', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -739,22 +1129,28 @@ def _list_webhooks_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + + @validate_call def update_webhook( self, - webhook_id: Annotated[ - StrictStr, Field(description="The Webhook id that needs to be updated") - ], - update_webhook_request: UpdateWebhookRequest | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + webhook_id: Annotated[StrictStr, Field(description="The Webhook id that needs to be updated")], + update_webhook_request: Optional[UpdateWebhookRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Webhook: """Update a webhook @@ -785,39 +1181,47 @@ def update_webhook( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._update_webhook_serialize( webhook_id=webhook_id, update_webhook_request=update_webhook_request, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Webhook", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Webhook", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ).data + @validate_call def update_webhook_with_http_info( self, - webhook_id: Annotated[ - StrictStr, Field(description="The Webhook id that needs to be updated") - ], - update_webhook_request: UpdateWebhookRequest | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + webhook_id: Annotated[StrictStr, Field(description="The Webhook id that needs to be updated")], + update_webhook_request: Optional[UpdateWebhookRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[Webhook]: """Update a webhook @@ -848,39 +1252,47 @@ def update_webhook_with_http_info( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._update_webhook_serialize( webhook_id=webhook_id, update_webhook_request=update_webhook_request, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Webhook", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Webhook", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) response_data.read() return self.api_client.response_deserialize( response_data=response_data, response_types_map=_response_types_map, ) + @validate_call def update_webhook_without_preload_content( self, - webhook_id: Annotated[ - StrictStr, Field(description="The Webhook id that needs to be updated") - ], - update_webhook_request: UpdateWebhookRequest | None = None, - _request_timeout: None - | Annotated[StrictFloat, Field(gt=0)] - | tuple[Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]] = None, - _request_auth: dict[StrictStr, Any] | None = None, - _content_type: StrictStr | None = None, - _headers: dict[StrictStr, Any] | None = None, + webhook_id: Annotated[StrictStr, Field(description="The Webhook id that needs to be updated")], + update_webhook_request: Optional[UpdateWebhookRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: """Update a webhook @@ -911,22 +1323,27 @@ def update_webhook_without_preload_content( in the spec for a single request. :type _host_index: int, optional :return: Returns the result object. - """ + """ # noqa: E501 + _param = self._update_webhook_serialize( webhook_id=webhook_id, update_webhook_request=update_webhook_request, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, - _host_index=_host_index, + _host_index=_host_index ) - _response_types_map: dict[str, str | None] = { - "200": "Webhook", + _response_types_map: Dict[str, Optional[str]] = { + '200': "Webhook", } - response_data = self.api_client.call_api(*_param, _request_timeout=_request_timeout) + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) return response_data.response + def _update_webhook_serialize( self, webhook_id, @@ -936,20 +1353,22 @@ def _update_webhook_serialize( _headers, _host_index, ) -> RequestSerialized: + _host = None - _collection_formats: dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - _path_params: dict[str, str] = {} - _query_params: list[tuple[str, str]] = [] - _header_params: dict[str, str | None] = _headers or {} - _form_params: list[tuple[str, str]] = [] - _files: dict[str, str | bytes] = {} - _body_params: bytes | None = None + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None # process the path parameters if webhook_id is not None: - _path_params["webhook_id"] = webhook_id + _path_params['webhook_id'] = webhook_id # process the query parameters # process the header parameters # process the form parameters @@ -957,24 +1376,36 @@ def _update_webhook_serialize( if update_webhook_request is not None: _body_params = update_webhook_request + # set the HTTP header `Accept` - if "Accept" not in _header_params: - _header_params["Accept"] = self.api_client.select_header_accept(["application/json"]) + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` if _content_type: - _header_params["Content-Type"] = _content_type + _header_params['Content-Type'] = _content_type else: - _default_content_type = self.api_client.select_header_content_type(["application/json"]) + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) if _default_content_type is not None: - _header_params["Content-Type"] = _default_content_type + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: list[str] = [] + _auth_settings: List[str] = [ + ] return self.api_client.param_serialize( - method="PUT", - resource_path="/v1/webhooks/{webhook_id}", + method='PUT', + resource_path='/v1/webhooks/{webhook_id}', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -984,5 +1415,7 @@ def _update_webhook_serialize( auth_settings=_auth_settings, collection_formats=_collection_formats, _host=_host, - _request_auth=_request_auth, + _request_auth=_request_auth ) + + diff --git a/cdp/client/api_client.py b/cdp/client/api_client.py index 7e29fa1..52369de 100644 --- a/cdp/client/api_client.py +++ b/cdp/client/api_client.py @@ -1,38 +1,46 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 -Do not edit the class manually. -""" import datetime +from dateutil.parser import parse +from enum import Enum import decimal import json import mimetypes import os import re import tempfile -from enum import Enum -from urllib.parse import quote -from dateutil.parser import parse +from urllib.parse import quote +from typing import Tuple, Optional, List, Dict, Union from pydantic import SecretStr +from cdp.client.configuration import Configuration +from cdp.client.api_response import ApiResponse, T as ApiResponseT import cdp.client.models from cdp.client import rest -from cdp.client.api_response import ApiResponse -from cdp.client.api_response import T as ApiResponseT -from cdp.client.configuration import Configuration from cdp.client.exceptions import ( - ApiException, ApiValueError, + ApiException, + BadRequestException, + UnauthorizedException, + ForbiddenException, + NotFoundException, + ServiceException ) -RequestSerialized = tuple[str, str, dict[str, str], str | None, list[str]] - +RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]] class ApiClient: """Generic API client for OpenAPI client library builds. @@ -52,20 +60,24 @@ class ApiClient: PRIMITIVE_TYPES = (float, bool, bytes, str, int) NATIVE_TYPES_MAPPING = { - "int": int, - "long": int, # TODO remove as only py3 is supported? - "float": float, - "str": str, - "bool": bool, - "date": datetime.date, - "datetime": datetime.datetime, - "decimal": decimal.Decimal, - "object": object, + 'int': int, + 'long': int, # TODO remove as only py3 is supported? + 'float': float, + 'str': str, + 'bool': bool, + 'date': datetime.date, + 'datetime': datetime.datetime, + 'decimal': decimal.Decimal, + 'object': object, } _pool = None def __init__( - self, configuration=None, header_name=None, header_value=None, cookie=None + self, + configuration=None, + header_name=None, + header_value=None, + cookie=None ) -> None: # use default configuration if none is provided if configuration is None: @@ -78,7 +90,7 @@ def __init__( self.default_headers[header_name] = header_value self.cookie = cookie # Set default User-Agent. - self.user_agent = "OpenAPI-Generator/1.0.0/python" + self.user_agent = 'OpenAPI-Generator/1.0.0/python' self.client_side_validation = configuration.client_side_validation def __enter__(self): @@ -90,15 +102,16 @@ def __exit__(self, exc_type, exc_value, traceback): @property def user_agent(self): """User agent for this API client""" - return self.default_headers["User-Agent"] + return self.default_headers['User-Agent'] @user_agent.setter def user_agent(self, value): - self.default_headers["User-Agent"] = value + self.default_headers['User-Agent'] = value def set_default_header(self, header_name, header_value): self.default_headers[header_name] = header_value + _default = None @classmethod @@ -134,12 +147,12 @@ def param_serialize( header_params=None, body=None, post_params=None, - files=None, - auth_settings=None, + files=None, auth_settings=None, collection_formats=None, _host=None, - _request_auth=None, + _request_auth=None ) -> RequestSerialized: + """Builds the HTTP request params needed by the request. :param method: Method to call. :param resource_path: Path to method endpoint. @@ -161,32 +174,42 @@ def param_serialize( :return: tuple of form (path, http_method, query_params, header_params, body, post_params, files) """ + config = self.configuration # header parameters header_params = header_params or {} header_params.update(self.default_headers) if self.cookie: - header_params["Cookie"] = 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)) + 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) + 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) + '{%s}' % k, + quote(str(v), safe=config.safe_chars_for_path_param) ) # post parameters if post_params or files: post_params = post_params if post_params else [] post_params = self.sanitize_for_serialization(post_params) - post_params = self.parameters_to_tuples(post_params, collection_formats) + post_params = self.parameters_to_tuples( + post_params, + collection_formats + ) if files: post_params.extend(self.files_parameters(files)) @@ -198,7 +221,7 @@ def param_serialize( resource_path, method, body, - request_auth=_request_auth, + request_auth=_request_auth ) # body @@ -215,13 +238,23 @@ def param_serialize( # query parameters if query_params: query_params = self.sanitize_for_serialization(query_params) - url_query = self.parameters_to_url_query(query_params, collection_formats) + url_query = self.parameters_to_url_query( + query_params, + collection_formats + ) url += "?" + url_query return method, url, header_params, body, post_params + def call_api( - self, method, url, header_params=None, body=None, post_params=None, _request_timeout=None + self, + method, + url, + header_params=None, + body=None, + post_params=None, + _request_timeout=None ) -> rest.RESTResponse: """Makes the HTTP request (synchronous) :param method: Method to call. @@ -234,15 +267,14 @@ def call_api( :param _request_timeout: timeout setting for this request. :return: RESTResponse """ + try: # perform request and return response response_data = self.rest_client.request( - method, - url, + method, url, headers=header_params, - body=body, - post_params=post_params, - _request_timeout=_request_timeout, + body=body, post_params=post_params, + _request_timeout=_request_timeout ) except ApiException as e: @@ -253,22 +285,19 @@ def call_api( def response_deserialize( self, response_data: rest.RESTResponse, - response_types_map: dict[str, ApiResponseT] | None = None, + response_types_map: Optional[Dict[str, ApiResponseT]]=None ) -> ApiResponse[ApiResponseT]: """Deserializes response into an object. :param response_data: RESTResponse object to be deserialized. :param response_types_map: dict of response types. :return: ApiResponse """ + msg = "RESTResponse.read() must be called before passing it to response_deserialize()" assert response_data.data is not None, msg response_type = response_types_map.get(str(response_data.status), None) - if ( - not response_type - and isinstance(response_data.status, int) - and 100 <= response_data.status <= 599 - ): + if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599: # if not found, look for '1XX', '2XX', etc. response_type = response_types_map.get(str(response_data.status)[0] + "XX", None) @@ -282,7 +311,7 @@ def response_deserialize( return_data = self.__deserialize_file(response_data) elif response_type is not None: match = None - content_type = response_data.getheader("content-type") + content_type = response_data.getheader('content-type') if content_type is not None: match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) encoding = match.group(1) if match else "utf-8" @@ -297,10 +326,10 @@ def response_deserialize( ) return ApiResponse( - status_code=response_data.status, - data=return_data, - headers=response_data.getheaders(), - raw_data=response_data.data, + status_code = response_data.status, + data = return_data, + headers = response_data.getheaders(), + raw_data = response_data.data ) def sanitize_for_serialization(self, obj): @@ -328,9 +357,13 @@ def sanitize_for_serialization(self, obj): elif isinstance(obj, self.PRIMITIVE_TYPES): return obj elif isinstance(obj, list): - return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] + 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) + return tuple( + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ) elif isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() elif isinstance(obj, decimal.Decimal): @@ -344,14 +377,17 @@ def sanitize_for_serialization(self, obj): # and attributes which value is not None. # Convert attribute name to json key in # model definition for request. - if hasattr(obj, "to_dict") and callable(obj.to_dict): + if hasattr(obj, 'to_dict') and callable(getattr(obj, 'to_dict')): obj_dict = obj.to_dict() else: obj_dict = obj.__dict__ - return {key: self.sanitize_for_serialization(val) for key, val in obj_dict.items()} + return { + key: self.sanitize_for_serialization(val) + for key, val in obj_dict.items() + } - def deserialize(self, response_text: str, response_type: str, content_type: str | None): + def deserialize(self, response_text: str, response_type: str, content_type: Optional[str]): """Deserializes response into an object. :param response: RESTResponse object to be deserialized. @@ -361,6 +397,7 @@ def deserialize(self, response_text: str, response_type: str, content_type: str :return: deserialized object. """ + # fetch data from response object if content_type is None: try: @@ -375,7 +412,10 @@ def deserialize(self, response_text: str, response_type: str, content_type: str elif content_type.startswith("text/plain"): data = response_text else: - raise ApiException(status=0, reason=f"Unsupported content type: {content_type}") + raise ApiException( + status=0, + reason="Unsupported content type: {0}".format(content_type) + ) return self.__deserialize(data, response_type) @@ -391,17 +431,19 @@ def __deserialize(self, data, klass): return None if isinstance(klass, str): - if klass.startswith("List["): - m = re.match(r"List\[(.*)]", klass) + if klass.startswith('List['): + m = re.match(r'List\[(.*)]', klass) assert m is not None, "Malformed List type definition" sub_kls = m.group(1) - return [self.__deserialize(sub_data, sub_kls) for sub_data in data] + return [self.__deserialize(sub_data, sub_kls) + for sub_data in data] - if klass.startswith("Dict["): - m = re.match(r"Dict\[([^,]*), (.*)]", klass) + if klass.startswith('Dict['): + m = re.match(r'Dict\[([^,]*), (.*)]', klass) assert m is not None, "Malformed Dict type definition" sub_kls = m.group(2) - return {k: self.__deserialize(v, sub_kls) for k, v in data.items()} + return {k: self.__deserialize(v, sub_kls) + for k, v in data.items()} # convert str to class if klass in self.NATIVE_TYPES_MAPPING: @@ -431,24 +473,25 @@ def parameters_to_tuples(self, params, collection_formats): :param dict collection_formats: Parameter collection formats :return: Parameters as list of tuples, collections formatted """ - new_params: list[tuple[str, str]] = [] + new_params: List[Tuple[str, str]] = [] if collection_formats is None: collection_formats = {} for k, v in params.items() if isinstance(params, dict) else params: if k in collection_formats: collection_format = collection_formats[k] - if collection_format == "multi": + 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 = "|" + 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))) + delimiter = ',' + new_params.append( + (k, delimiter.join(str(value) for value in v))) else: new_params.append((k, v)) return new_params @@ -460,7 +503,7 @@ def parameters_to_url_query(self, params, collection_formats): :param dict collection_formats: Parameter collection formats :return: URL query string (e.g. a=Hello%20World&b=123) """ - new_params: list[tuple[str, str]] = [] + new_params: List[Tuple[str, str]] = [] if collection_formats is None: collection_formats = {} for k, v in params.items() if isinstance(params, dict) else params: @@ -473,24 +516,26 @@ def parameters_to_url_query(self, params, collection_formats): if k in collection_formats: collection_format = collection_formats[k] - if collection_format == "multi": + if collection_format == 'multi': new_params.extend((k, str(value)) for value in v) else: - if collection_format == "ssv": - delimiter = " " - elif collection_format == "tsv": - delimiter = "\t" - elif collection_format == "pipes": - delimiter = "|" + 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(quote(str(value)) for value in v))) + delimiter = ',' + new_params.append( + (k, delimiter.join(quote(str(value)) for value in v)) + ) else: new_params.append((k, quote(str(v)))) return "&".join(["=".join(map(str, item)) for item in new_params]) - def files_parameters(self, files: dict[str, str | bytes]): + def files_parameters(self, files: Dict[str, Union[str, bytes]]): """Builds form parameters. :param files: File parameters. @@ -499,7 +544,7 @@ def files_parameters(self, files: dict[str, str | bytes]): params = [] for k, v in files.items(): if isinstance(v, str): - with open(v, "rb") as f: + with open(v, 'rb') as f: filename = os.path.basename(f.name) filedata = f.read() elif isinstance(v, bytes): @@ -507,11 +552,16 @@ def files_parameters(self, files: dict[str, str | bytes]): filedata = v else: raise ValueError("Unsupported file value") - mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream" - params.append(tuple([k, tuple([filename, filedata, mimetype])])) + 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: list[str]) -> str | None: + def select_header_accept(self, accepts: List[str]) -> Optional[str]: """Returns `Accept` based on an array of accepts provided. :param accepts: List of headers. @@ -521,7 +571,7 @@ def select_header_accept(self, accepts: list[str]) -> str | None: return None for accept in accepts: - if re.search("json", accept, re.IGNORECASE): + if re.search('json', accept, re.IGNORECASE): return accept return accepts[0] @@ -536,13 +586,20 @@ def select_header_content_type(self, content_types): return None for content_type in content_types: - if re.search("json", content_type, re.IGNORECASE): + if re.search('json', content_type, re.IGNORECASE): return content_type return content_types[0] def update_params_for_auth( - self, headers, queries, auth_settings, resource_path, method, body, request_auth=None + self, + headers, + queries, + auth_settings, + resource_path, + method, + body, + request_auth=None ) -> None: """Updates header and query params based on authentication setting. @@ -560,17 +617,35 @@ def update_params_for_auth( return if request_auth: - self._apply_auth_params(headers, queries, resource_path, method, body, request_auth) + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + request_auth + ) else: for auth in auth_settings: auth_setting = self.configuration.auth_settings().get(auth) if auth_setting: self._apply_auth_params( - headers, queries, resource_path, method, body, auth_setting + headers, + queries, + resource_path, + method, + body, + auth_setting ) def _apply_auth_params( - self, headers, queries, resource_path, method, body, auth_setting + self, + headers, + queries, + resource_path, + method, + body, + auth_setting ) -> None: """Updates the request parameters based on a single auth_setting @@ -582,15 +657,17 @@ def _apply_auth_params( The object type is the return value of sanitize_for_serialization(). :param auth_setting: auth settings for the endpoint """ - if auth_setting["in"] == "cookie": - headers["Cookie"] = auth_setting["value"] - elif auth_setting["in"] == "header": - if auth_setting["type"] != "http-signature": - headers[auth_setting["key"]] = auth_setting["value"] - elif auth_setting["in"] == "query": - queries.append((auth_setting["key"], auth_setting["value"])) + if auth_setting['in'] == 'cookie': + headers['Cookie'] = auth_setting['value'] + elif auth_setting['in'] == 'header': + if auth_setting['type'] != 'http-signature': + headers[auth_setting['key']] = auth_setting['value'] + elif auth_setting['in'] == 'query': + queries.append((auth_setting['key'], auth_setting['value'])) else: - raise ApiValueError("Authentication token must be in `query` or `header`") + raise ApiValueError( + 'Authentication token must be in `query` or `header`' + ) def __deserialize_file(self, response): """Deserializes body to file @@ -610,7 +687,10 @@ def __deserialize_file(self, response): content_disposition = response.getheader("Content-Disposition") if content_disposition: - m = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition) + m = re.search( + r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition + ) assert m is not None, "Unexpected 'content-disposition' header value" filename = m.group(1) path = os.path.join(os.path.dirname(path), filename) @@ -653,7 +733,10 @@ def __deserialize_date(self, string): except ImportError: return string except ValueError: - raise rest.ApiException(status=0, reason=f"Failed to parse `{string}` as date object") + raise rest.ApiException( + status=0, + reason="Failed to parse `{0}` as date object".format(string) + ) def __deserialize_datetime(self, string): """Deserializes string to datetime. @@ -669,7 +752,11 @@ def __deserialize_datetime(self, string): return string except ValueError: raise rest.ApiException( - status=0, reason=(f"Failed to parse `{string}` as datetime object") + status=0, + reason=( + "Failed to parse `{0}` as datetime object" + .format(string) + ) ) def __deserialize_enum(self, data, klass): @@ -682,7 +769,13 @@ def __deserialize_enum(self, data, klass): try: return klass(data) except ValueError: - raise rest.ApiException(status=0, reason=(f"Failed to parse `{data}` as `{klass}`")) + raise rest.ApiException( + status=0, + reason=( + "Failed to parse `{0}` as `{1}`" + .format(data, klass) + ) + ) def __deserialize_model(self, data, klass): """Deserializes list or dict to model. @@ -691,4 +784,5 @@ def __deserialize_model(self, data, klass): :param klass: class literal. :return: model object. """ + return klass.from_dict(data) diff --git a/cdp/client/api_response.py b/cdp/client/api_response.py index 384e379..9bc7c11 100644 --- a/cdp/client/api_response.py +++ b/cdp/client/api_response.py @@ -1,21 +1,21 @@ """API response object.""" from __future__ import annotations - -from collections.abc import Mapping -from typing import Generic, TypeVar - -from pydantic import BaseModel, Field, StrictBytes, StrictInt +from typing import Optional, Generic, Mapping, TypeVar +from pydantic import Field, StrictInt, StrictBytes, BaseModel T = TypeVar("T") - class ApiResponse(BaseModel, Generic[T]): - """API response object""" + """ + API response object + """ status_code: StrictInt = Field(description="HTTP status code") - headers: Mapping[str, str] | None = Field(None, description="HTTP headers") + headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers") data: T = Field(description="Deserialized data given the data type") raw_data: StrictBytes = Field(description="Raw data (HTTP response body)") - model_config = {"arbitrary_types_allowed": True} + model_config = { + "arbitrary_types_allowed": True + } diff --git a/cdp/client/configuration.py b/cdp/client/configuration.py index 6e7f477..e995c53 100644 --- a/cdp/client/configuration.py +++ b/cdp/client/configuration.py @@ -1,36 +1,33 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 -Do not edit the class manually. -""" import copy -import http.client as httplib import logging +from logging import FileHandler import multiprocessing import sys -from logging import FileHandler - +from typing import Optional import urllib3 +import http.client as httplib + JSON_SCHEMA_VALIDATION_KEYWORDS = { - "multipleOf", - "maximum", - "exclusiveMaximum", - "minimum", - "exclusiveMinimum", - "maxLength", - "minLength", - "pattern", - "maxItems", - "minItems", + 'multipleOf', 'maximum', 'exclusiveMaximum', + 'minimum', 'exclusiveMinimum', 'maxLength', + 'minLength', 'pattern', 'maxItems', 'minItems' } - class Configuration: """This class contains various settings of the API client. @@ -66,25 +63,20 @@ class Configuration: _default = None - def __init__( - self, - host=None, - api_key=None, - api_key_prefix=None, - username=None, - password=None, - access_token=None, - server_index=None, - server_variables=None, - server_operation_index=None, - server_operation_variables=None, - ignore_operation_servers=False, - ssl_ca_cert=None, - retries=None, - *, - debug: bool | None = None, - ) -> None: - """Constructor""" + def __init__(self, host=None, + api_key=None, api_key_prefix=None, + username=None, password=None, + access_token=None, + server_index=None, server_variables=None, + server_operation_index=None, server_operation_variables=None, + ignore_operation_servers=False, + ssl_ca_cert=None, + retries=None, + *, + debug: Optional[bool] = None + ) -> None: + """Constructor + """ self._base_path = "https://api.cdp.coinbase.com/platform" if host is None else host """Default Base url """ @@ -130,13 +122,13 @@ def __init__( """ self.logger["package_logger"] = logging.getLogger("cdp.client") self.logger["urllib3_logger"] = logging.getLogger("urllib3") - self.logger_format = "%(asctime)s %(levelname)s %(message)s" + self.logger_format = '%(asctime)s %(levelname)s %(message)s' """Log format """ self.logger_stream_handler = None """Log stream handler """ - self.logger_file_handler: FileHandler | None = None + self.logger_file_handler: Optional[FileHandler] = None """Log file handler """ self.logger_file = None @@ -179,13 +171,13 @@ def __init__( cpu_count * 5 is used as default value to increase performance. """ - self.proxy: str | None = None + self.proxy: Optional[str] = None """Proxy URL """ self.proxy_headers = None """Proxy headers """ - self.safe_chars_for_path_param = "" + self.safe_chars_for_path_param = '' """Safe chars for path_param """ self.retries = retries @@ -211,7 +203,7 @@ def __deepcopy__(self, memo): result = cls.__new__(cls) memo[id(self)] = result for k, v in self.__dict__.items(): - if k not in ("logger", "logger_file_handler"): + if k not in ('logger', 'logger_file_handler'): setattr(result, k, copy.deepcopy(v, memo)) # shallow copy of loggers result.logger = copy.copy(self.logger) @@ -371,7 +363,9 @@ def get_basic_auth_token(self): password = "" if self.password is not None: password = self.password - return urllib3.util.make_headers(basic_auth=username + ":" + password).get("authorization") + return urllib3.util.make_headers( + basic_auth=username + ':' + password + ).get('authorization') def auth_settings(self): """Gets Auth Settings dict for api client. @@ -386,13 +380,12 @@ def to_debug_report(self): :return: The report for debugging. """ - return ( - "Python SDK Debug Report:\n" - f"OS: {sys.platform}\n" - f"Python Version: {sys.version}\n" - "Version of the API: 0.0.1-alpha\n" - "SDK Package Version: 1.0.0" - ) + return "Python SDK Debug Report:\n"\ + "OS: {env}\n"\ + "Python Version: {pyversion}\n"\ + "Version of the API: 0.0.1-alpha\n"\ + "SDK Package Version: 1.0.0".\ + format(env=sys.platform, pyversion=sys.version) def get_host_settings(self): """Gets an array of host settings @@ -401,8 +394,8 @@ def get_host_settings(self): """ return [ { - "url": "https://api.cdp.coinbase.com/platform", - "description": "No description provided", + 'url': "https://api.cdp.coinbase.com/platform", + 'description': "No description provided", } ] @@ -423,23 +416,23 @@ def get_host_from_settings(self, index, variables=None, servers=None): server = servers[index] except IndexError: raise ValueError( - f"Invalid index {index} when selecting the host settings. " - f"Must be less than {len(servers)}" - ) + "Invalid index {0} when selecting the host settings. " + "Must be less than {1}".format(index, len(servers))) - url = server["url"] + url = server['url'] # go through variables and replace placeholders - for variable_name, variable in server.get("variables", {}).items(): - used_value = variables.get(variable_name, variable["default_value"]) + for variable_name, variable in server.get('variables', {}).items(): + used_value = variables.get( + variable_name, variable['default_value']) - if "enum_values" in variable and used_value not in variable["enum_values"]: + if 'enum_values' in variable \ + and used_value not in variable['enum_values']: raise ValueError( "The variable `{0}` in the host URL has invalid value " "{1}. Must be {2}.".format( - variable_name, variables[variable_name], variable["enum_values"] - ) - ) + variable_name, variables[variable_name], + variable['enum_values'])) url = url.replace("{" + variable_name + "}", used_value) diff --git a/cdp/client/exceptions.py b/cdp/client/exceptions.py index fe26188..a126d9f 100644 --- a/cdp/client/exceptions.py +++ b/cdp/client/exceptions.py @@ -1,25 +1,27 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from typing import Any + Do not edit the class manually. +""" # noqa: E501 +from typing import Any, Optional from typing_extensions import Self - class OpenApiException(Exception): """The base exception class for all OpenAPIExceptions""" class ApiTypeError(OpenApiException, TypeError): - def __init__(self, msg, path_to_item=None, valid_classes=None, key_type=None) -> None: - """Raises an exception for TypeErrors + def __init__(self, msg, path_to_item=None, valid_classes=None, + key_type=None) -> None: + """ Raises an exception for TypeErrors Args: msg (str): the exception message @@ -35,37 +37,38 @@ def __init__(self, msg, path_to_item=None, valid_classes=None, key_type=None) -> True if it is a key in a dict False if our item is an item in a list None if unset - """ self.path_to_item = path_to_item self.valid_classes = valid_classes self.key_type = key_type full_msg = msg if path_to_item: - full_msg = f"{msg} at {render_path(path_to_item)}" + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) super(ApiTypeError, self).__init__(full_msg) class ApiValueError(OpenApiException, ValueError): def __init__(self, msg, path_to_item=None) -> None: - """Args: + """ + Args: msg (str): the exception message Keyword Args: path_to_item (list) the path to the exception in the received_data dict. None if unset - """ + self.path_to_item = path_to_item full_msg = msg if path_to_item: - full_msg = f"{msg} at {render_path(path_to_item)}" + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) super(ApiValueError, self).__init__(full_msg) class ApiAttributeError(OpenApiException, AttributeError): def __init__(self, msg, path_to_item=None) -> None: - """Raised when an attribute reference or assignment fails. + """ + Raised when an attribute reference or assignment fails. Args: msg (str): the exception message @@ -73,41 +76,41 @@ def __init__(self, msg, path_to_item=None) -> None: Keyword Args: path_to_item (None/list) the path to the exception in the received_data dict - """ self.path_to_item = path_to_item full_msg = msg if path_to_item: - full_msg = f"{msg} at {render_path(path_to_item)}" + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) super(ApiAttributeError, self).__init__(full_msg) class ApiKeyError(OpenApiException, KeyError): def __init__(self, msg, path_to_item=None) -> None: - """Args: + """ + Args: msg (str): the exception message Keyword Args: path_to_item (None/list) the path to the exception in the received_data dict - """ self.path_to_item = path_to_item full_msg = msg if path_to_item: - full_msg = f"{msg} at {render_path(path_to_item)}" + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) super(ApiKeyError, self).__init__(full_msg) class ApiException(OpenApiException): + def __init__( - self, - status=None, - reason=None, + self, + status=None, + reason=None, http_resp=None, *, - body: str | None = None, - data: Any | None = None, + body: Optional[str] = None, + data: Optional[Any] = None, ) -> None: self.status = status self.reason = reason @@ -122,18 +125,18 @@ def __init__( self.reason = http_resp.reason if self.body is None: try: - self.body = http_resp.data.decode("utf-8") + self.body = http_resp.data.decode('utf-8') except Exception: pass self.headers = http_resp.getheaders() @classmethod def from_response( - cls, - *, - http_resp, - body: str | None, - data: Any | None, + cls, + *, + http_resp, + body: Optional[str], + data: Optional[Any], ) -> Self: if http_resp.status == 400: raise BadRequestException(http_resp=http_resp, body=body, data=data) @@ -153,12 +156,14 @@ def from_response( def __str__(self): """Custom error messages for exception""" - error_message = f"({self.status})\n" f"Reason: {self.reason}\n" + error_message = "({0})\n"\ + "Reason: {1}\n".format(self.status, self.reason) if self.headers: - error_message += f"HTTP response headers: {self.headers}\n" + error_message += "HTTP response headers: {0}\n".format( + self.headers) if self.data or self.body: - error_message += f"HTTP response body: {self.data or self.body}\n" + error_message += "HTTP response body: {0}\n".format(self.data or self.body) return error_message @@ -188,7 +193,7 @@ def render_path(path_to_item): result = "" for pth in path_to_item: if isinstance(pth, int): - result += f"[{pth}]" + result += "[{0}]".format(pth) else: - result += f"['{pth}']" + result += "['{0}']".format(pth) return result diff --git a/cdp/client/models/__init__.py b/cdp/client/models/__init__.py index 4039ed0..679d3cb 100644 --- a/cdp/client/models/__init__.py +++ b/cdp/client/models/__init__.py @@ -2,16 +2,17 @@ # flake8: noqa """ -Coinbase Platform API + Coinbase Platform API -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -Do not edit the class manually. + Do not edit the class manually. """ # noqa: E501 + # import models into model package from cdp.client.models.address import Address from cdp.client.models.address_balance_list import AddressBalanceList @@ -20,9 +21,7 @@ from cdp.client.models.address_transaction_list import AddressTransactionList from cdp.client.models.asset import Asset from cdp.client.models.balance import Balance -from cdp.client.models.broadcast_contract_invocation_request import ( - BroadcastContractInvocationRequest, -) +from cdp.client.models.broadcast_contract_invocation_request import BroadcastContractInvocationRequest from cdp.client.models.broadcast_staking_operation_request import BroadcastStakingOperationRequest from cdp.client.models.broadcast_trade_request import BroadcastTradeRequest from cdp.client.models.broadcast_transfer_request import BroadcastTransferRequest @@ -41,6 +40,7 @@ from cdp.client.models.create_transfer_request import CreateTransferRequest from cdp.client.models.create_wallet_request import CreateWalletRequest from cdp.client.models.create_wallet_request_wallet import CreateWalletRequestWallet +from cdp.client.models.create_wallet_webhook_request import CreateWalletWebhookRequest from cdp.client.models.create_webhook_request import CreateWebhookRequest from cdp.client.models.deploy_smart_contract_request import DeploySmartContractRequest from cdp.client.models.erc20_transfer_event import ERC20TransferEvent @@ -53,13 +53,12 @@ from cdp.client.models.ethereum_validator_metadata import EthereumValidatorMetadata from cdp.client.models.faucet_transaction import FaucetTransaction from cdp.client.models.feature_set import FeatureSet -from cdp.client.models.fetch_historical_staking_balances200_response import ( - FetchHistoricalStakingBalances200Response, -) +from cdp.client.models.fetch_historical_staking_balances200_response import FetchHistoricalStakingBalances200Response from cdp.client.models.fetch_staking_rewards200_response import FetchStakingRewards200Response from cdp.client.models.fetch_staking_rewards_request import FetchStakingRewardsRequest from cdp.client.models.get_staking_context_request import GetStakingContextRequest from cdp.client.models.historical_balance import HistoricalBalance +from cdp.client.models.multi_token_contract_options import MultiTokenContractOptions from cdp.client.models.nft_contract_options import NFTContractOptions from cdp.client.models.network import Network from cdp.client.models.network_identifier import NetworkIdentifier @@ -74,9 +73,7 @@ from cdp.client.models.server_signer_list import ServerSignerList from cdp.client.models.signature_creation_event import SignatureCreationEvent from cdp.client.models.signature_creation_event_result import SignatureCreationEventResult -from cdp.client.models.signed_voluntary_exit_message_metadata import ( - SignedVoluntaryExitMessageMetadata, -) +from cdp.client.models.signed_voluntary_exit_message_metadata import SignedVoluntaryExitMessageMetadata from cdp.client.models.smart_contract import SmartContract from cdp.client.models.smart_contract_list import SmartContractList from cdp.client.models.smart_contract_options import SmartContractOptions diff --git a/cdp/client/models/address.py b/cdp/client/models/address.py index 1b2d739..61e1124 100644 --- a/cdp/client/models/address.py +++ b/cdp/client/models/address.py @@ -1,39 +1,37 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set from typing_extensions import Self - class Address(BaseModel): - """Address""" - + """ + Address + """ # noqa: E501 wallet_id: StrictStr = Field(description="The ID of the wallet that owns the address") network_id: StrictStr = Field(description="The ID of the blockchain network") public_key: StrictStr = Field(description="The public key from which the address is derived.") address_id: StrictStr = Field(description="The onchain address derived on the server-side.") index: StrictInt = Field(description="The index of the address in the wallet.") - __properties: ClassVar[list[str]] = [ - "wallet_id", - "network_id", - "public_key", - "address_id", - "index", - ] + __properties: ClassVar[List[str]] = ["wallet_id", "network_id", "public_key", "address_id", "index"] model_config = ConfigDict( populate_by_name=True, @@ -41,6 +39,7 @@ class Address(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -51,11 +50,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Address from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -65,7 +64,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -75,7 +75,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Address from a dict""" if obj is None: return None @@ -83,13 +83,13 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "wallet_id": obj.get("wallet_id"), - "network_id": obj.get("network_id"), - "public_key": obj.get("public_key"), - "address_id": obj.get("address_id"), - "index": obj.get("index"), - } - ) + _obj = cls.model_validate({ + "wallet_id": obj.get("wallet_id"), + "network_id": obj.get("network_id"), + "public_key": obj.get("public_key"), + "address_id": obj.get("address_id"), + "index": obj.get("index") + }) return _obj + + diff --git a/cdp/client/models/address_balance_list.py b/cdp/client/models/address_balance_list.py index 21905a2..b786d80 100644 --- a/cdp/client/models/address_balance_list.py +++ b/cdp/client/models/address_balance_list.py @@ -1,36 +1,37 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.balance import Balance - +from typing import Optional, Set +from typing_extensions import Self class AddressBalanceList(BaseModel): - """ """ - - data: list[Balance] - has_more: StrictBool = Field( - description="True if this list has another page of items after this one that can be fetched." - ) + """ + + """ # noqa: E501 + data: List[Balance] + has_more: StrictBool = Field(description="True if this list has another page of items after this one that can be fetched.") next_page: StrictStr = Field(description="The page token to be used to fetch the next page.") total_count: StrictInt = Field(description="The total number of balances for the wallet.") - __properties: ClassVar[list[str]] = ["data", "has_more", "next_page", "total_count"] + __properties: ClassVar[List[str]] = ["data", "has_more", "next_page", "total_count"] model_config = ConfigDict( populate_by_name=True, @@ -38,6 +39,7 @@ class AddressBalanceList(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -48,11 +50,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of AddressBalanceList from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -62,7 +64,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -75,11 +78,11 @@ def to_dict(self) -> dict[str, Any]: for _item_data in self.data: if _item_data: _items.append(_item_data.to_dict()) - _dict["data"] = _items + _dict['data'] = _items return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of AddressBalanceList from a dict""" if obj is None: return None @@ -87,14 +90,12 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "data": [Balance.from_dict(_item) for _item in obj["data"]] - if obj.get("data") is not None - else None, - "has_more": obj.get("has_more"), - "next_page": obj.get("next_page"), - "total_count": obj.get("total_count"), - } - ) + _obj = cls.model_validate({ + "data": [Balance.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None, + "has_more": obj.get("has_more"), + "next_page": obj.get("next_page"), + "total_count": obj.get("total_count") + }) return _obj + + diff --git a/cdp/client/models/address_historical_balance_list.py b/cdp/client/models/address_historical_balance_list.py index 3d1e030..3256b70 100644 --- a/cdp/client/models/address_historical_balance_list.py +++ b/cdp/client/models/address_historical_balance_list.py @@ -1,35 +1,36 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.historical_balance import HistoricalBalance - +from typing import Optional, Set +from typing_extensions import Self class AddressHistoricalBalanceList(BaseModel): - """ """ - - data: list[HistoricalBalance] - has_more: StrictBool = Field( - description="True if this list has another page of items after this one that can be fetched." - ) + """ + + """ # noqa: E501 + data: List[HistoricalBalance] + has_more: StrictBool = Field(description="True if this list has another page of items after this one that can be fetched.") next_page: StrictStr = Field(description="The page token to be used to fetch the next page.") - __properties: ClassVar[list[str]] = ["data", "has_more", "next_page"] + __properties: ClassVar[List[str]] = ["data", "has_more", "next_page"] model_config = ConfigDict( populate_by_name=True, @@ -37,6 +38,7 @@ class AddressHistoricalBalanceList(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -47,11 +49,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of AddressHistoricalBalanceList from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -61,7 +63,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -74,11 +77,11 @@ def to_dict(self) -> dict[str, Any]: for _item_data in self.data: if _item_data: _items.append(_item_data.to_dict()) - _dict["data"] = _items + _dict['data'] = _items return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of AddressHistoricalBalanceList from a dict""" if obj is None: return None @@ -86,13 +89,11 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "data": [HistoricalBalance.from_dict(_item) for _item in obj["data"]] - if obj.get("data") is not None - else None, - "has_more": obj.get("has_more"), - "next_page": obj.get("next_page"), - } - ) + _obj = cls.model_validate({ + "data": [HistoricalBalance.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None, + "has_more": obj.get("has_more"), + "next_page": obj.get("next_page") + }) return _obj + + diff --git a/cdp/client/models/address_list.py b/cdp/client/models/address_list.py index 63398e4..5211d3b 100644 --- a/cdp/client/models/address_list.py +++ b/cdp/client/models/address_list.py @@ -1,36 +1,37 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.address import Address - +from typing import Optional, Set +from typing_extensions import Self class AddressList(BaseModel): - """ """ - - data: list[Address] - has_more: StrictBool = Field( - description="True if this list has another page of items after this one that can be fetched." - ) + """ + + """ # noqa: E501 + data: List[Address] + has_more: StrictBool = Field(description="True if this list has another page of items after this one that can be fetched.") next_page: StrictStr = Field(description="The page token to be used to fetch the next page.") total_count: StrictInt = Field(description="The total number of addresses for the wallet.") - __properties: ClassVar[list[str]] = ["data", "has_more", "next_page", "total_count"] + __properties: ClassVar[List[str]] = ["data", "has_more", "next_page", "total_count"] model_config = ConfigDict( populate_by_name=True, @@ -38,6 +39,7 @@ class AddressList(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -48,11 +50,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of AddressList from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -62,7 +64,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -75,11 +78,11 @@ def to_dict(self) -> dict[str, Any]: for _item_data in self.data: if _item_data: _items.append(_item_data.to_dict()) - _dict["data"] = _items + _dict['data'] = _items return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of AddressList from a dict""" if obj is None: return None @@ -87,14 +90,12 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "data": [Address.from_dict(_item) for _item in obj["data"]] - if obj.get("data") is not None - else None, - "has_more": obj.get("has_more"), - "next_page": obj.get("next_page"), - "total_count": obj.get("total_count"), - } - ) + _obj = cls.model_validate({ + "data": [Address.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None, + "has_more": obj.get("has_more"), + "next_page": obj.get("next_page"), + "total_count": obj.get("total_count") + }) return _obj + + diff --git a/cdp/client/models/address_transaction_list.py b/cdp/client/models/address_transaction_list.py index 556f414..4249fa0 100644 --- a/cdp/client/models/address_transaction_list.py +++ b/cdp/client/models/address_transaction_list.py @@ -1,35 +1,36 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.transaction import Transaction - +from typing import Optional, Set +from typing_extensions import Self class AddressTransactionList(BaseModel): - """ """ - - data: list[Transaction] - has_more: StrictBool = Field( - description="True if this list has another page of items after this one that can be fetched." - ) + """ + + """ # noqa: E501 + data: List[Transaction] + has_more: StrictBool = Field(description="True if this list has another page of items after this one that can be fetched.") next_page: StrictStr = Field(description="The page token to be used to fetch the next page.") - __properties: ClassVar[list[str]] = ["data", "has_more", "next_page"] + __properties: ClassVar[List[str]] = ["data", "has_more", "next_page"] model_config = ConfigDict( populate_by_name=True, @@ -37,6 +38,7 @@ class AddressTransactionList(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -47,11 +49,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of AddressTransactionList from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -61,7 +63,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -74,11 +77,11 @@ def to_dict(self) -> dict[str, Any]: for _item_data in self.data: if _item_data: _items.append(_item_data.to_dict()) - _dict["data"] = _items + _dict['data'] = _items return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of AddressTransactionList from a dict""" if obj is None: return None @@ -86,13 +89,11 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "data": [Transaction.from_dict(_item) for _item in obj["data"]] - if obj.get("data") is not None - else None, - "has_more": obj.get("has_more"), - "next_page": obj.get("next_page"), - } - ) + _obj = cls.model_validate({ + "data": [Transaction.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None, + "has_more": obj.get("has_more"), + "next_page": obj.get("next_page") + }) return _obj + + diff --git a/cdp/client/models/asset.py b/cdp/client/models/asset.py index bd90287..bca3da5 100644 --- a/cdp/client/models/asset.py +++ b/cdp/client/models/asset.py @@ -1,38 +1,36 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set from typing_extensions import Self - class Asset(BaseModel): - """An asset onchain scoped to a particular network, e.g. ETH on base-sepolia, or the USDC ERC20 Token on ethereum-mainnet.""" - + """ + An asset onchain scoped to a particular network, e.g. ETH on base-sepolia, or the USDC ERC20 Token on ethereum-mainnet. + """ # noqa: E501 network_id: StrictStr = Field(description="The ID of the blockchain network") asset_id: StrictStr = Field(description="The ID for the asset on the network") - decimals: StrictInt | None = Field( - default=None, - description="The number of decimals the asset supports. This is used to convert from atomic units to base units.", - ) - contract_address: StrictStr | None = Field( - default=None, - description="The optional contract address for the asset. This will be specified for smart contract-based assets, for example ERC20s.", - ) - __properties: ClassVar[list[str]] = ["network_id", "asset_id", "decimals", "contract_address"] + decimals: Optional[StrictInt] = Field(default=None, description="The number of decimals the asset supports. This is used to convert from atomic units to base units.") + contract_address: Optional[StrictStr] = Field(default=None, description="The optional contract address for the asset. This will be specified for smart contract-based assets, for example ERC20s.") + __properties: ClassVar[List[str]] = ["network_id", "asset_id", "decimals", "contract_address"] model_config = ConfigDict( populate_by_name=True, @@ -40,6 +38,7 @@ class Asset(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -50,11 +49,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Asset from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -64,7 +63,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -74,7 +74,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Asset from a dict""" if obj is None: return None @@ -82,12 +82,12 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "network_id": obj.get("network_id"), - "asset_id": obj.get("asset_id"), - "decimals": obj.get("decimals"), - "contract_address": obj.get("contract_address"), - } - ) + _obj = cls.model_validate({ + "network_id": obj.get("network_id"), + "asset_id": obj.get("asset_id"), + "decimals": obj.get("decimals"), + "contract_address": obj.get("contract_address") + }) return _obj + + diff --git a/cdp/client/models/balance.py b/cdp/client/models/balance.py index 787a72f..7f3fe66 100644 --- a/cdp/client/models/balance.py +++ b/cdp/client/models/balance.py @@ -1,32 +1,35 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.asset import Asset - +from typing import Optional, Set +from typing_extensions import Self class Balance(BaseModel): - """The balance of an asset onchain""" - + """ + The balance of an asset onchain + """ # noqa: E501 amount: StrictStr = Field(description="The amount in the atomic units of the asset") asset: Asset - __properties: ClassVar[list[str]] = ["amount", "asset"] + __properties: ClassVar[List[str]] = ["amount", "asset"] model_config = ConfigDict( populate_by_name=True, @@ -34,6 +37,7 @@ class Balance(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -44,11 +48,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Balance from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -58,7 +62,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -67,11 +72,11 @@ def to_dict(self) -> dict[str, Any]: ) # override the default output from pydantic by calling `to_dict()` of asset if self.asset: - _dict["asset"] = self.asset.to_dict() + _dict['asset'] = self.asset.to_dict() return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Balance from a dict""" if obj is None: return None @@ -79,10 +84,10 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "amount": obj.get("amount"), - "asset": Asset.from_dict(obj["asset"]) if obj.get("asset") is not None else None, - } - ) + _obj = cls.model_validate({ + "amount": obj.get("amount"), + "asset": Asset.from_dict(obj["asset"]) if obj.get("asset") is not None else None + }) return _obj + + diff --git a/cdp/client/models/broadcast_contract_invocation_request.py b/cdp/client/models/broadcast_contract_invocation_request.py index b071099..f7dab98 100644 --- a/cdp/client/models/broadcast_contract_invocation_request.py +++ b/cdp/client/models/broadcast_contract_invocation_request.py @@ -1,31 +1,33 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set from typing_extensions import Self - class BroadcastContractInvocationRequest(BaseModel): - """BroadcastContractInvocationRequest""" - - signed_payload: StrictStr = Field( - description="The hex-encoded signed payload of the contract invocation" - ) - __properties: ClassVar[list[str]] = ["signed_payload"] + """ + BroadcastContractInvocationRequest + """ # noqa: E501 + signed_payload: StrictStr = Field(description="The hex-encoded signed payload of the contract invocation") + __properties: ClassVar[List[str]] = ["signed_payload"] model_config = ConfigDict( populate_by_name=True, @@ -33,6 +35,7 @@ class BroadcastContractInvocationRequest(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -43,11 +46,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of BroadcastContractInvocationRequest from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -57,7 +60,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -67,7 +71,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of BroadcastContractInvocationRequest from a dict""" if obj is None: return None @@ -75,5 +79,9 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({"signed_payload": obj.get("signed_payload")}) + _obj = cls.model_validate({ + "signed_payload": obj.get("signed_payload") + }) return _obj + + diff --git a/cdp/client/models/broadcast_staking_operation_request.py b/cdp/client/models/broadcast_staking_operation_request.py index be948fb..40dc326 100644 --- a/cdp/client/models/broadcast_staking_operation_request.py +++ b/cdp/client/models/broadcast_staking_operation_request.py @@ -1,34 +1,34 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set from typing_extensions import Self - class BroadcastStakingOperationRequest(BaseModel): - """BroadcastStakingOperationRequest""" - - signed_payload: StrictStr = Field( - description="The hex-encoded signed payload of the staking operation." - ) - transaction_index: StrictInt = Field( - description="The index in the transaction array of the staking operation." - ) - __properties: ClassVar[list[str]] = ["signed_payload", "transaction_index"] + """ + BroadcastStakingOperationRequest + """ # noqa: E501 + signed_payload: StrictStr = Field(description="The hex-encoded signed payload of the staking operation.") + transaction_index: StrictInt = Field(description="The index in the transaction array of the staking operation.") + __properties: ClassVar[List[str]] = ["signed_payload", "transaction_index"] model_config = ConfigDict( populate_by_name=True, @@ -36,6 +36,7 @@ class BroadcastStakingOperationRequest(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -46,11 +47,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of BroadcastStakingOperationRequest from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -60,7 +61,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -70,7 +72,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of BroadcastStakingOperationRequest from a dict""" if obj is None: return None @@ -78,10 +80,10 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "signed_payload": obj.get("signed_payload"), - "transaction_index": obj.get("transaction_index"), - } - ) + _obj = cls.model_validate({ + "signed_payload": obj.get("signed_payload"), + "transaction_index": obj.get("transaction_index") + }) return _obj + + diff --git a/cdp/client/models/broadcast_trade_request.py b/cdp/client/models/broadcast_trade_request.py index e2521e7..5a5a2d2 100644 --- a/cdp/client/models/broadcast_trade_request.py +++ b/cdp/client/models/broadcast_trade_request.py @@ -1,32 +1,34 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set from typing_extensions import Self - class BroadcastTradeRequest(BaseModel): - """BroadcastTradeRequest""" - + """ + BroadcastTradeRequest + """ # noqa: E501 signed_payload: StrictStr = Field(description="The hex-encoded signed payload of the trade") - approve_transaction_signed_payload: StrictStr | None = Field( - default=None, description="The hex-encoded signed payload of the approval transaction" - ) - __properties: ClassVar[list[str]] = ["signed_payload", "approve_transaction_signed_payload"] + approve_transaction_signed_payload: Optional[StrictStr] = Field(default=None, description="The hex-encoded signed payload of the approval transaction") + __properties: ClassVar[List[str]] = ["signed_payload", "approve_transaction_signed_payload"] model_config = ConfigDict( populate_by_name=True, @@ -34,6 +36,7 @@ class BroadcastTradeRequest(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -44,11 +47,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of BroadcastTradeRequest from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -58,7 +61,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -68,7 +72,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of BroadcastTradeRequest from a dict""" if obj is None: return None @@ -76,10 +80,10 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "signed_payload": obj.get("signed_payload"), - "approve_transaction_signed_payload": obj.get("approve_transaction_signed_payload"), - } - ) + _obj = cls.model_validate({ + "signed_payload": obj.get("signed_payload"), + "approve_transaction_signed_payload": obj.get("approve_transaction_signed_payload") + }) return _obj + + diff --git a/cdp/client/models/broadcast_transfer_request.py b/cdp/client/models/broadcast_transfer_request.py index 11ab3da..414e304 100644 --- a/cdp/client/models/broadcast_transfer_request.py +++ b/cdp/client/models/broadcast_transfer_request.py @@ -1,29 +1,33 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set from typing_extensions import Self - class BroadcastTransferRequest(BaseModel): - """BroadcastTransferRequest""" - + """ + BroadcastTransferRequest + """ # noqa: E501 signed_payload: StrictStr = Field(description="The hex-encoded signed payload of the transfer") - __properties: ClassVar[list[str]] = ["signed_payload"] + __properties: ClassVar[List[str]] = ["signed_payload"] model_config = ConfigDict( populate_by_name=True, @@ -31,6 +35,7 @@ class BroadcastTransferRequest(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -41,11 +46,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of BroadcastTransferRequest from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -55,7 +60,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -65,7 +71,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of BroadcastTransferRequest from a dict""" if obj is None: return None @@ -73,5 +79,9 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({"signed_payload": obj.get("signed_payload")}) + _obj = cls.model_validate({ + "signed_payload": obj.get("signed_payload") + }) return _obj + + diff --git a/cdp/client/models/build_staking_operation_request.py b/cdp/client/models/build_staking_operation_request.py index c9c4743..7238168 100644 --- a/cdp/client/models/build_staking_operation_request.py +++ b/cdp/client/models/build_staking_operation_request.py @@ -1,41 +1,37 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set from typing_extensions import Self - class BuildStakingOperationRequest(BaseModel): - """BuildStakingOperationRequest""" - + """ + BuildStakingOperationRequest + """ # noqa: E501 network_id: StrictStr = Field(description="The ID of the blockchain network") asset_id: StrictStr = Field(description="The ID of the asset being staked") - address_id: StrictStr = Field( - description="The onchain address from which the staking transaction originates and is responsible for signing the transaction." - ) + address_id: StrictStr = Field(description="The onchain address from which the staking transaction originates and is responsible for signing the transaction.") action: StrictStr = Field(description="The type of staking operation") - options: dict[str, StrictStr] - __properties: ClassVar[list[str]] = [ - "network_id", - "asset_id", - "address_id", - "action", - "options", - ] + options: Dict[str, StrictStr] + __properties: ClassVar[List[str]] = ["network_id", "asset_id", "address_id", "action", "options"] model_config = ConfigDict( populate_by_name=True, @@ -43,6 +39,7 @@ class BuildStakingOperationRequest(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -53,11 +50,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of BuildStakingOperationRequest from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -67,7 +64,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -77,7 +75,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of BuildStakingOperationRequest from a dict""" if obj is None: return None @@ -85,13 +83,13 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "network_id": obj.get("network_id"), - "asset_id": obj.get("asset_id"), - "address_id": obj.get("address_id"), - "action": obj.get("action"), - "options": obj.get("options"), - } - ) + _obj = cls.model_validate({ + "network_id": obj.get("network_id"), + "asset_id": obj.get("asset_id"), + "address_id": obj.get("address_id"), + "action": obj.get("action"), + "options": obj.get("options") + }) return _obj + + diff --git a/cdp/client/models/contract_event.py b/cdp/client/models/contract_event.py index 2a409cc..9e06e9a 100644 --- a/cdp/client/models/contract_event.py +++ b/cdp/client/models/contract_event.py @@ -1,62 +1,46 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from datetime import datetime -from typing import Any, ClassVar +import json +from datetime import datetime from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set from typing_extensions import Self - class ContractEvent(BaseModel): - """Represents a single decoded event emitted by a smart contract""" - + """ + Represents a single decoded event emitted by a smart contract + """ # noqa: E501 network_id: StrictStr = Field(description="The name of the blockchain network") protocol_name: StrictStr = Field(description="The name of the blockchain project or protocol") - contract_name: StrictStr = Field( - description="The name of the specific contract within the project" - ) + contract_name: StrictStr = Field(description="The name of the specific contract within the project") event_name: StrictStr = Field(description="The name of the event emitted by the contract") sig: StrictStr = Field(description="The signature of the event, including parameter types") - four_bytes: StrictStr = Field( - description="The first four bytes of the Keccak hash of the event signature" - ) + four_bytes: StrictStr = Field(description="The first four bytes of the Keccak hash of the event signature") contract_address: StrictStr = Field(description="The EVM address of the smart contract") - block_time: datetime = Field( - description="The timestamp of the block in which the event was emitted" - ) + block_time: datetime = Field(description="The timestamp of the block in which the event was emitted") block_height: StrictInt = Field(description="The block number in which the event was emitted") tx_hash: StrictStr = Field(description="The transaction hash in which the event was emitted") tx_index: StrictInt = Field(description="The index of the transaction within the block") event_index: StrictInt = Field(description="The index of the event within the transaction") data: StrictStr = Field(description="The event data in a stringified format") - __properties: ClassVar[list[str]] = [ - "network_id", - "protocol_name", - "contract_name", - "event_name", - "sig", - "four_bytes", - "contract_address", - "block_time", - "block_height", - "tx_hash", - "tx_index", - "event_index", - "data", - ] + __properties: ClassVar[List[str]] = ["network_id", "protocol_name", "contract_name", "event_name", "sig", "four_bytes", "contract_address", "block_time", "block_height", "tx_hash", "tx_index", "event_index", "data"] model_config = ConfigDict( populate_by_name=True, @@ -64,6 +48,7 @@ class ContractEvent(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -74,11 +59,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ContractEvent from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -88,7 +73,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -98,7 +84,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ContractEvent from a dict""" if obj is None: return None @@ -106,21 +92,21 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "network_id": obj.get("network_id"), - "protocol_name": obj.get("protocol_name"), - "contract_name": obj.get("contract_name"), - "event_name": obj.get("event_name"), - "sig": obj.get("sig"), - "four_bytes": obj.get("four_bytes"), - "contract_address": obj.get("contract_address"), - "block_time": obj.get("block_time"), - "block_height": obj.get("block_height"), - "tx_hash": obj.get("tx_hash"), - "tx_index": obj.get("tx_index"), - "event_index": obj.get("event_index"), - "data": obj.get("data"), - } - ) + _obj = cls.model_validate({ + "network_id": obj.get("network_id"), + "protocol_name": obj.get("protocol_name"), + "contract_name": obj.get("contract_name"), + "event_name": obj.get("event_name"), + "sig": obj.get("sig"), + "four_bytes": obj.get("four_bytes"), + "contract_address": obj.get("contract_address"), + "block_time": obj.get("block_time"), + "block_height": obj.get("block_height"), + "tx_hash": obj.get("tx_hash"), + "tx_index": obj.get("tx_index"), + "event_index": obj.get("event_index"), + "data": obj.get("data") + }) return _obj + + diff --git a/cdp/client/models/contract_event_list.py b/cdp/client/models/contract_event_list.py index f0dfff2..28505ae 100644 --- a/cdp/client/models/contract_event_list.py +++ b/cdp/client/models/contract_event_list.py @@ -1,35 +1,36 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.contract_event import ContractEvent - +from typing import Optional, Set +from typing_extensions import Self class ContractEventList(BaseModel): - """A list of contract events with pagination information""" - - data: list[ContractEvent] = Field(description="An array of ContractEvent objects") + """ + A list of contract events with pagination information + """ # noqa: E501 + data: List[ContractEvent] = Field(description="An array of ContractEvent objects") next_page: StrictStr = Field(description="The page token to be used to fetch the next page") - has_more: StrictBool = Field( - description="True if this list has another page of items after this one that can be fetched" - ) - __properties: ClassVar[list[str]] = ["data", "next_page", "has_more"] + has_more: StrictBool = Field(description="True if this list has another page of items after this one that can be fetched") + __properties: ClassVar[List[str]] = ["data", "next_page", "has_more"] model_config = ConfigDict( populate_by_name=True, @@ -37,6 +38,7 @@ class ContractEventList(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -47,11 +49,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ContractEventList from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -61,7 +63,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -74,11 +77,11 @@ def to_dict(self) -> dict[str, Any]: for _item_data in self.data: if _item_data: _items.append(_item_data.to_dict()) - _dict["data"] = _items + _dict['data'] = _items return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ContractEventList from a dict""" if obj is None: return None @@ -86,13 +89,11 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "data": [ContractEvent.from_dict(_item) for _item in obj["data"]] - if obj.get("data") is not None - else None, - "next_page": obj.get("next_page"), - "has_more": obj.get("has_more"), - } - ) + _obj = cls.model_validate({ + "data": [ContractEvent.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None, + "next_page": obj.get("next_page"), + "has_more": obj.get("has_more") + }) return _obj + + diff --git a/cdp/client/models/contract_invocation.py b/cdp/client/models/contract_invocation.py index 81c0a88..82713a2 100644 --- a/cdp/client/models/contract_invocation.py +++ b/cdp/client/models/contract_invocation.py @@ -1,55 +1,43 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List, Optional from cdp.client.models.transaction import Transaction - +from typing import Optional, Set +from typing_extensions import Self class ContractInvocation(BaseModel): - """A contract invocation onchain.""" - + """ + A contract invocation onchain. + """ # noqa: E501 network_id: StrictStr = Field(description="The ID of the blockchain network.") wallet_id: StrictStr = Field(description="The ID of the wallet that owns the address.") - address_id: StrictStr = Field( - description="The onchain address of the address invoking the contract." - ) + address_id: StrictStr = Field(description="The onchain address of the address invoking the contract.") contract_invocation_id: StrictStr = Field(description="The ID of the contract invocation.") contract_address: StrictStr = Field(description="The onchain address of the contract.") method: StrictStr = Field(description="The method to be invoked on the contract.") - args: StrictStr = Field( - description="The JSON-encoded arguments to pass to the contract method. The keys should be the argument names and the values should be the argument values." - ) - abi: StrictStr | None = Field(default=None, description="The JSON-encoded ABI of the contract.") + args: StrictStr = Field(description="The JSON-encoded arguments to pass to the contract method. The keys should be the argument names and the values should be the argument values.") + abi: Optional[StrictStr] = Field(default=None, description="The JSON-encoded ABI of the contract.") amount: StrictStr = Field(description="The amount to send to the contract for a payable method") transaction: Transaction - __properties: ClassVar[list[str]] = [ - "network_id", - "wallet_id", - "address_id", - "contract_invocation_id", - "contract_address", - "method", - "args", - "abi", - "amount", - "transaction", - ] + __properties: ClassVar[List[str]] = ["network_id", "wallet_id", "address_id", "contract_invocation_id", "contract_address", "method", "args", "abi", "amount", "transaction"] model_config = ConfigDict( populate_by_name=True, @@ -57,6 +45,7 @@ class ContractInvocation(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -67,11 +56,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ContractInvocation from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -81,7 +70,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -90,11 +80,11 @@ def to_dict(self) -> dict[str, Any]: ) # override the default output from pydantic by calling `to_dict()` of transaction if self.transaction: - _dict["transaction"] = self.transaction.to_dict() + _dict['transaction'] = self.transaction.to_dict() return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ContractInvocation from a dict""" if obj is None: return None @@ -102,20 +92,18 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "network_id": obj.get("network_id"), - "wallet_id": obj.get("wallet_id"), - "address_id": obj.get("address_id"), - "contract_invocation_id": obj.get("contract_invocation_id"), - "contract_address": obj.get("contract_address"), - "method": obj.get("method"), - "args": obj.get("args"), - "abi": obj.get("abi"), - "amount": obj.get("amount"), - "transaction": Transaction.from_dict(obj["transaction"]) - if obj.get("transaction") is not None - else None, - } - ) + _obj = cls.model_validate({ + "network_id": obj.get("network_id"), + "wallet_id": obj.get("wallet_id"), + "address_id": obj.get("address_id"), + "contract_invocation_id": obj.get("contract_invocation_id"), + "contract_address": obj.get("contract_address"), + "method": obj.get("method"), + "args": obj.get("args"), + "abi": obj.get("abi"), + "amount": obj.get("amount"), + "transaction": Transaction.from_dict(obj["transaction"]) if obj.get("transaction") is not None else None + }) return _obj + + diff --git a/cdp/client/models/contract_invocation_list.py b/cdp/client/models/contract_invocation_list.py index 395f43c..c5b7b1e 100644 --- a/cdp/client/models/contract_invocation_list.py +++ b/cdp/client/models/contract_invocation_list.py @@ -1,38 +1,37 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.contract_invocation import ContractInvocation - +from typing import Optional, Set +from typing_extensions import Self class ContractInvocationList(BaseModel): - """ContractInvocationList""" - - data: list[ContractInvocation] - has_more: StrictBool = Field( - description="True if this list has another page of items after this one that can be fetched." - ) + """ + ContractInvocationList + """ # noqa: E501 + data: List[ContractInvocation] + has_more: StrictBool = Field(description="True if this list has another page of items after this one that can be fetched.") next_page: StrictStr = Field(description="The page token to be used to fetch the next page.") - total_count: StrictInt = Field( - description="The total number of contract invocations for the address in the wallet." - ) - __properties: ClassVar[list[str]] = ["data", "has_more", "next_page", "total_count"] + total_count: StrictInt = Field(description="The total number of contract invocations for the address in the wallet.") + __properties: ClassVar[List[str]] = ["data", "has_more", "next_page", "total_count"] model_config = ConfigDict( populate_by_name=True, @@ -40,6 +39,7 @@ class ContractInvocationList(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -50,11 +50,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ContractInvocationList from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -64,7 +64,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -77,11 +78,11 @@ def to_dict(self) -> dict[str, Any]: for _item_data in self.data: if _item_data: _items.append(_item_data.to_dict()) - _dict["data"] = _items + _dict['data'] = _items return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ContractInvocationList from a dict""" if obj is None: return None @@ -89,14 +90,12 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "data": [ContractInvocation.from_dict(_item) for _item in obj["data"]] - if obj.get("data") is not None - else None, - "has_more": obj.get("has_more"), - "next_page": obj.get("next_page"), - "total_count": obj.get("total_count"), - } - ) + _obj = cls.model_validate({ + "data": [ContractInvocation.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None, + "has_more": obj.get("has_more"), + "next_page": obj.get("next_page"), + "total_count": obj.get("total_count") + }) return _obj + + diff --git a/cdp/client/models/create_address_request.py b/cdp/client/models/create_address_request.py index 024733a..f9da470 100644 --- a/cdp/client/models/create_address_request.py +++ b/cdp/client/models/create_address_request.py @@ -1,38 +1,35 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set from typing_extensions import Self - class CreateAddressRequest(BaseModel): - """CreateAddressRequest""" - - public_key: StrictStr | None = Field( - default=None, description="The public key from which the address will be derived." - ) - attestation: StrictStr | None = Field( - default=None, - description="An attestation signed by the private key that is associated with the wallet. The attestation will be a hex-encoded signature of a json payload with fields `wallet_id` and `public_key`, signed by the private key associated with the public_key set in the request.", - ) - address_index: StrictInt | None = Field( - default=None, description="The index of the address within the wallet." - ) - __properties: ClassVar[list[str]] = ["public_key", "attestation", "address_index"] + """ + CreateAddressRequest + """ # noqa: E501 + public_key: Optional[StrictStr] = Field(default=None, description="The public key from which the address will be derived.") + attestation: Optional[StrictStr] = Field(default=None, description="An attestation signed by the private key that is associated with the wallet. The attestation will be a hex-encoded signature of a json payload with fields `wallet_id` and `public_key`, signed by the private key associated with the public_key set in the request.") + address_index: Optional[StrictInt] = Field(default=None, description="The index of the address within the wallet.") + __properties: ClassVar[List[str]] = ["public_key", "attestation", "address_index"] model_config = ConfigDict( populate_by_name=True, @@ -40,6 +37,7 @@ class CreateAddressRequest(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -50,11 +48,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of CreateAddressRequest from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -64,7 +62,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -74,7 +73,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of CreateAddressRequest from a dict""" if obj is None: return None @@ -82,11 +81,11 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "public_key": obj.get("public_key"), - "attestation": obj.get("attestation"), - "address_index": obj.get("address_index"), - } - ) + _obj = cls.model_validate({ + "public_key": obj.get("public_key"), + "attestation": obj.get("attestation"), + "address_index": obj.get("address_index") + }) return _obj + + diff --git a/cdp/client/models/create_contract_invocation_request.py b/cdp/client/models/create_contract_invocation_request.py index a9ec15b..4265c5a 100644 --- a/cdp/client/models/create_contract_invocation_request.py +++ b/cdp/client/models/create_contract_invocation_request.py @@ -1,38 +1,37 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set from typing_extensions import Self - class CreateContractInvocationRequest(BaseModel): - """CreateContractInvocationRequest""" - + """ + CreateContractInvocationRequest + """ # noqa: E501 contract_address: StrictStr = Field(description="The address of the contract to invoke.") method: StrictStr = Field(description="The method to invoke on the contract.") - args: StrictStr = Field( - description="The JSON-encoded arguments to pass to the contract method. The keys should be the argument names and the values should be the argument values." - ) - abi: StrictStr | None = Field(default=None, description="The JSON-encoded ABI of the contract.") - amount: StrictStr | None = Field( - default=None, - description="The amount in atomic units of the native asset to send to the contract for a payable method", - ) - __properties: ClassVar[list[str]] = ["contract_address", "method", "args", "abi", "amount"] + args: StrictStr = Field(description="The JSON-encoded arguments to pass to the contract method. The keys should be the argument names and the values should be the argument values.") + abi: Optional[StrictStr] = Field(default=None, description="The JSON-encoded ABI of the contract.") + amount: Optional[StrictStr] = Field(default=None, description="The amount in atomic units of the native asset to send to the contract for a payable method") + __properties: ClassVar[List[str]] = ["contract_address", "method", "args", "abi", "amount"] model_config = ConfigDict( populate_by_name=True, @@ -40,6 +39,7 @@ class CreateContractInvocationRequest(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -50,11 +50,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of CreateContractInvocationRequest from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -64,7 +64,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -74,7 +75,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of CreateContractInvocationRequest from a dict""" if obj is None: return None @@ -82,13 +83,13 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "contract_address": obj.get("contract_address"), - "method": obj.get("method"), - "args": obj.get("args"), - "abi": obj.get("abi"), - "amount": obj.get("amount"), - } - ) + _obj = cls.model_validate({ + "contract_address": obj.get("contract_address"), + "method": obj.get("method"), + "args": obj.get("args"), + "abi": obj.get("abi"), + "amount": obj.get("amount") + }) return _obj + + diff --git a/cdp/client/models/create_payload_signature_request.py b/cdp/client/models/create_payload_signature_request.py index fa717bb..21ae68c 100644 --- a/cdp/client/models/create_payload_signature_request.py +++ b/cdp/client/models/create_payload_signature_request.py @@ -1,30 +1,34 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set from typing_extensions import Self - class CreatePayloadSignatureRequest(BaseModel): - """CreatePayloadSignatureRequest""" - + """ + CreatePayloadSignatureRequest + """ # noqa: E501 unsigned_payload: StrictStr = Field(description="The unsigned payload.") - signature: StrictStr | None = Field(default=None, description="The signature of the payload.") - __properties: ClassVar[list[str]] = ["unsigned_payload", "signature"] + signature: Optional[StrictStr] = Field(default=None, description="The signature of the payload.") + __properties: ClassVar[List[str]] = ["unsigned_payload", "signature"] model_config = ConfigDict( populate_by_name=True, @@ -32,6 +36,7 @@ class CreatePayloadSignatureRequest(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -42,11 +47,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of CreatePayloadSignatureRequest from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -56,7 +61,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -66,7 +72,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of CreatePayloadSignatureRequest from a dict""" if obj is None: return None @@ -74,7 +80,10 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - {"unsigned_payload": obj.get("unsigned_payload"), "signature": obj.get("signature")} - ) + _obj = cls.model_validate({ + "unsigned_payload": obj.get("unsigned_payload"), + "signature": obj.get("signature") + }) return _obj + + diff --git a/cdp/client/models/create_server_signer_request.py b/cdp/client/models/create_server_signer_request.py index 20c6dd5..d50dac7 100644 --- a/cdp/client/models/create_server_signer_request.py +++ b/cdp/client/models/create_server_signer_request.py @@ -1,35 +1,35 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set from typing_extensions import Self - class CreateServerSignerRequest(BaseModel): - """CreateServerSignerRequest""" - - server_signer_id: StrictStr | None = Field( - default=None, description="The ID of the server signer for the 1 of 1 server signer." - ) - enrollment_data: StrictStr = Field( - description="The enrollment data of the server signer. This will be the base64 encoded server-signer-id for the 1 of 1 server signer." - ) + """ + CreateServerSignerRequest + """ # noqa: E501 + server_signer_id: Optional[StrictStr] = Field(default=None, description="The ID of the server signer for the 1 of 1 server signer.") + enrollment_data: StrictStr = Field(description="The enrollment data of the server signer. This will be the base64 encoded server-signer-id for the 1 of 1 server signer.") is_mpc: StrictBool = Field(description="Whether the Server-Signer uses MPC.") - __properties: ClassVar[list[str]] = ["server_signer_id", "enrollment_data", "is_mpc"] + __properties: ClassVar[List[str]] = ["server_signer_id", "enrollment_data", "is_mpc"] model_config = ConfigDict( populate_by_name=True, @@ -37,6 +37,7 @@ class CreateServerSignerRequest(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -47,11 +48,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of CreateServerSignerRequest from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -61,7 +62,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -71,7 +73,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of CreateServerSignerRequest from a dict""" if obj is None: return None @@ -79,11 +81,11 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "server_signer_id": obj.get("server_signer_id"), - "enrollment_data": obj.get("enrollment_data"), - "is_mpc": obj.get("is_mpc"), - } - ) + _obj = cls.model_validate({ + "server_signer_id": obj.get("server_signer_id"), + "enrollment_data": obj.get("enrollment_data"), + "is_mpc": obj.get("is_mpc") + }) return _obj + + diff --git a/cdp/client/models/create_smart_contract_request.py b/cdp/client/models/create_smart_contract_request.py index 7edf0b5..6bb98e4 100644 --- a/cdp/client/models/create_smart_contract_request.py +++ b/cdp/client/models/create_smart_contract_request.py @@ -1,33 +1,36 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.smart_contract_options import SmartContractOptions from cdp.client.models.smart_contract_type import SmartContractType - +from typing import Optional, Set +from typing_extensions import Self class CreateSmartContractRequest(BaseModel): - """CreateSmartContractRequest""" - + """ + CreateSmartContractRequest + """ # noqa: E501 type: SmartContractType options: SmartContractOptions - __properties: ClassVar[list[str]] = ["type", "options"] + __properties: ClassVar[List[str]] = ["type", "options"] model_config = ConfigDict( populate_by_name=True, @@ -35,6 +38,7 @@ class CreateSmartContractRequest(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -45,11 +49,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of CreateSmartContractRequest from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -59,7 +63,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -68,11 +73,11 @@ def to_dict(self) -> dict[str, Any]: ) # override the default output from pydantic by calling `to_dict()` of options if self.options: - _dict["options"] = self.options.to_dict() + _dict['options'] = self.options.to_dict() return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of CreateSmartContractRequest from a dict""" if obj is None: return None @@ -80,12 +85,10 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "type": obj.get("type"), - "options": SmartContractOptions.from_dict(obj["options"]) - if obj.get("options") is not None - else None, - } - ) + _obj = cls.model_validate({ + "type": obj.get("type"), + "options": SmartContractOptions.from_dict(obj["options"]) if obj.get("options") is not None else None + }) return _obj + + diff --git a/cdp/client/models/create_staking_operation_request.py b/cdp/client/models/create_staking_operation_request.py index febb434..677206b 100644 --- a/cdp/client/models/create_staking_operation_request.py +++ b/cdp/client/models/create_staking_operation_request.py @@ -1,32 +1,36 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set from typing_extensions import Self - class CreateStakingOperationRequest(BaseModel): - """CreateStakingOperationRequest""" - + """ + CreateStakingOperationRequest + """ # noqa: E501 network_id: StrictStr = Field(description="The ID of the blockchain network.") asset_id: StrictStr = Field(description="The ID of the asset being staked.") action: StrictStr = Field(description="The type of staking operation.") - options: dict[str, StrictStr] - __properties: ClassVar[list[str]] = ["network_id", "asset_id", "action", "options"] + options: Dict[str, StrictStr] + __properties: ClassVar[List[str]] = ["network_id", "asset_id", "action", "options"] model_config = ConfigDict( populate_by_name=True, @@ -34,6 +38,7 @@ class CreateStakingOperationRequest(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -44,11 +49,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of CreateStakingOperationRequest from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -58,7 +63,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -68,7 +74,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of CreateStakingOperationRequest from a dict""" if obj is None: return None @@ -76,12 +82,12 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "network_id": obj.get("network_id"), - "asset_id": obj.get("asset_id"), - "action": obj.get("action"), - "options": obj.get("options"), - } - ) + _obj = cls.model_validate({ + "network_id": obj.get("network_id"), + "asset_id": obj.get("asset_id"), + "action": obj.get("action"), + "options": obj.get("options") + }) return _obj + + diff --git a/cdp/client/models/create_trade_request.py b/cdp/client/models/create_trade_request.py index 10c602b..3089020 100644 --- a/cdp/client/models/create_trade_request.py +++ b/cdp/client/models/create_trade_request.py @@ -1,31 +1,35 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set from typing_extensions import Self - class CreateTradeRequest(BaseModel): - """CreateTradeRequest""" - + """ + CreateTradeRequest + """ # noqa: E501 amount: StrictStr = Field(description="The amount to trade") from_asset_id: StrictStr = Field(description="The ID of the asset to trade") to_asset_id: StrictStr = Field(description="The ID of the asset to receive from the trade") - __properties: ClassVar[list[str]] = ["amount", "from_asset_id", "to_asset_id"] + __properties: ClassVar[List[str]] = ["amount", "from_asset_id", "to_asset_id"] model_config = ConfigDict( populate_by_name=True, @@ -33,6 +37,7 @@ class CreateTradeRequest(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -43,11 +48,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of CreateTradeRequest from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -57,7 +62,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -67,7 +73,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of CreateTradeRequest from a dict""" if obj is None: return None @@ -75,11 +81,11 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "amount": obj.get("amount"), - "from_asset_id": obj.get("from_asset_id"), - "to_asset_id": obj.get("to_asset_id"), - } - ) + _obj = cls.model_validate({ + "amount": obj.get("amount"), + "from_asset_id": obj.get("from_asset_id"), + "to_asset_id": obj.get("to_asset_id") + }) return _obj + + diff --git a/cdp/client/models/create_transfer_request.py b/cdp/client/models/create_transfer_request.py index f943498..a180aa5 100644 --- a/cdp/client/models/create_transfer_request.py +++ b/cdp/client/models/create_transfer_request.py @@ -1,43 +1,37 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set from typing_extensions import Self - class CreateTransferRequest(BaseModel): - """CreateTransferRequest""" - + """ + CreateTransferRequest + """ # noqa: E501 amount: StrictStr = Field(description="The amount to transfer") network_id: StrictStr = Field(description="The ID of the blockchain network") asset_id: StrictStr = Field(description="The ID of the asset to transfer") - destination: StrictStr = Field( - description="The destination address, which can be a 0x address, Basename, or ENS name" - ) - gasless: StrictBool | None = Field( - default=None, description="Whether the transfer uses sponsored gas" - ) - __properties: ClassVar[list[str]] = [ - "amount", - "network_id", - "asset_id", - "destination", - "gasless", - ] + destination: StrictStr = Field(description="The destination address, which can be a 0x address, Basename, or ENS name") + gasless: Optional[StrictBool] = Field(default=None, description="Whether the transfer uses sponsored gas") + __properties: ClassVar[List[str]] = ["amount", "network_id", "asset_id", "destination", "gasless"] model_config = ConfigDict( populate_by_name=True, @@ -45,6 +39,7 @@ class CreateTransferRequest(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -55,11 +50,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of CreateTransferRequest from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -69,7 +64,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -79,7 +75,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of CreateTransferRequest from a dict""" if obj is None: return None @@ -87,13 +83,13 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "amount": obj.get("amount"), - "network_id": obj.get("network_id"), - "asset_id": obj.get("asset_id"), - "destination": obj.get("destination"), - "gasless": obj.get("gasless"), - } - ) + _obj = cls.model_validate({ + "amount": obj.get("amount"), + "network_id": obj.get("network_id"), + "asset_id": obj.get("asset_id"), + "destination": obj.get("destination"), + "gasless": obj.get("gasless") + }) return _obj + + diff --git a/cdp/client/models/create_wallet_request.py b/cdp/client/models/create_wallet_request.py index 12d784b..cff8e88 100644 --- a/cdp/client/models/create_wallet_request.py +++ b/cdp/client/models/create_wallet_request.py @@ -1,31 +1,34 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.create_wallet_request_wallet import CreateWalletRequestWallet - +from typing import Optional, Set +from typing_extensions import Self class CreateWalletRequest(BaseModel): - """CreateWalletRequest""" - + """ + CreateWalletRequest + """ # noqa: E501 wallet: CreateWalletRequestWallet - __properties: ClassVar[list[str]] = ["wallet"] + __properties: ClassVar[List[str]] = ["wallet"] model_config = ConfigDict( populate_by_name=True, @@ -33,6 +36,7 @@ class CreateWalletRequest(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -43,11 +47,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of CreateWalletRequest from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -57,7 +61,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -66,11 +71,11 @@ def to_dict(self) -> dict[str, Any]: ) # override the default output from pydantic by calling `to_dict()` of wallet if self.wallet: - _dict["wallet"] = self.wallet.to_dict() + _dict['wallet'] = self.wallet.to_dict() return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of CreateWalletRequest from a dict""" if obj is None: return None @@ -78,11 +83,9 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "wallet": CreateWalletRequestWallet.from_dict(obj["wallet"]) - if obj.get("wallet") is not None - else None - } - ) + _obj = cls.model_validate({ + "wallet": CreateWalletRequestWallet.from_dict(obj["wallet"]) if obj.get("wallet") is not None else None + }) return _obj + + diff --git a/cdp/client/models/create_wallet_request_wallet.py b/cdp/client/models/create_wallet_request_wallet.py index 931d52b..88c5fce 100644 --- a/cdp/client/models/create_wallet_request_wallet.py +++ b/cdp/client/models/create_wallet_request_wallet.py @@ -1,33 +1,34 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set from typing_extensions import Self - class CreateWalletRequestWallet(BaseModel): - """Parameters for configuring a wallet""" - + """ + Parameters for configuring a wallet + """ # noqa: E501 network_id: StrictStr = Field(description="The ID of the blockchain network") - use_server_signer: StrictBool | None = Field( - default=None, - description="Whether the wallet should use the project's server signer or if the addresses in the wallets will belong to a private key the developer manages. Defaults to false.", - ) - __properties: ClassVar[list[str]] = ["network_id", "use_server_signer"] + use_server_signer: Optional[StrictBool] = Field(default=None, description="Whether the wallet should use the project's server signer or if the addresses in the wallets will belong to a private key the developer manages. Defaults to false.") + __properties: ClassVar[List[str]] = ["network_id", "use_server_signer"] model_config = ConfigDict( populate_by_name=True, @@ -35,6 +36,7 @@ class CreateWalletRequestWallet(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -45,11 +47,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of CreateWalletRequestWallet from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -59,7 +61,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -69,7 +72,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of CreateWalletRequestWallet from a dict""" if obj is None: return None @@ -77,7 +80,10 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - {"network_id": obj.get("network_id"), "use_server_signer": obj.get("use_server_signer")} - ) + _obj = cls.model_validate({ + "network_id": obj.get("network_id"), + "use_server_signer": obj.get("use_server_signer") + }) return _obj + + diff --git a/cdp/client/models/create_wallet_webhook_request.py b/cdp/client/models/create_wallet_webhook_request.py new file mode 100644 index 0000000..76996e6 --- /dev/null +++ b/cdp/client/models/create_wallet_webhook_request.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class CreateWalletWebhookRequest(BaseModel): + """ + CreateWalletWebhookRequest + """ # noqa: E501 + notification_uri: StrictStr = Field(description="The URL to which the notifications will be sent.") + signature_header: Optional[StrictStr] = Field(default=None, description="The custom header to be used for x-webhook-signature header on callbacks, so developers can verify the requests are coming from Coinbase.") + __properties: ClassVar[List[str]] = ["notification_uri", "signature_header"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CreateWalletWebhookRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CreateWalletWebhookRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "notification_uri": obj.get("notification_uri"), + "signature_header": obj.get("signature_header") + }) + return _obj + + diff --git a/cdp/client/models/create_webhook_request.py b/cdp/client/models/create_webhook_request.py index 24228be..7125ef7 100644 --- a/cdp/client/models/create_webhook_request.py +++ b/cdp/client/models/create_webhook_request.py @@ -1,53 +1,41 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List, Optional from cdp.client.models.webhook_event_filter import WebhookEventFilter from cdp.client.models.webhook_event_type import WebhookEventType from cdp.client.models.webhook_event_type_filter import WebhookEventTypeFilter - +from typing import Optional, Set +from typing_extensions import Self class CreateWebhookRequest(BaseModel): - """CreateWebhookRequest""" - + """ + CreateWebhookRequest + """ # noqa: E501 network_id: StrictStr = Field(description="The ID of the blockchain network") event_type: WebhookEventType - event_type_filter: WebhookEventTypeFilter | None = None - event_filters: list[WebhookEventFilter] | None = Field( - default=None, - description="Webhook will monitor all events that matches any one of the event filters.", - ) - notification_uri: StrictStr = Field( - description="The URL to which the notifications will be sent" - ) - signature_header: StrictStr | None = Field( - default=None, - description="The custom header to be used for x-webhook-signature header on callbacks, so developers can verify the requests are coming from Coinbase.", - ) - __properties: ClassVar[list[str]] = [ - "network_id", - "event_type", - "event_type_filter", - "event_filters", - "notification_uri", - "signature_header", - ] + event_type_filter: Optional[WebhookEventTypeFilter] = None + event_filters: Optional[List[WebhookEventFilter]] = Field(default=None, description="Webhook will monitor all events that matches any one of the event filters.") + notification_uri: StrictStr = Field(description="The URL to which the notifications will be sent") + signature_header: Optional[StrictStr] = Field(default=None, description="The custom header to be used for x-webhook-signature header on callbacks, so developers can verify the requests are coming from Coinbase.") + __properties: ClassVar[List[str]] = ["network_id", "event_type", "event_type_filter", "event_filters", "notification_uri", "signature_header"] model_config = ConfigDict( populate_by_name=True, @@ -55,6 +43,7 @@ class CreateWebhookRequest(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -65,11 +54,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of CreateWebhookRequest from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -79,7 +68,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -88,18 +78,18 @@ def to_dict(self) -> dict[str, Any]: ) # override the default output from pydantic by calling `to_dict()` of event_type_filter if self.event_type_filter: - _dict["event_type_filter"] = self.event_type_filter.to_dict() + _dict['event_type_filter'] = self.event_type_filter.to_dict() # override the default output from pydantic by calling `to_dict()` of each item in event_filters (list) _items = [] if self.event_filters: for _item_event_filters in self.event_filters: if _item_event_filters: _items.append(_item_event_filters.to_dict()) - _dict["event_filters"] = _items + _dict['event_filters'] = _items return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of CreateWebhookRequest from a dict""" if obj is None: return None @@ -107,20 +97,14 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "network_id": obj.get("network_id"), - "event_type": obj.get("event_type"), - "event_type_filter": WebhookEventTypeFilter.from_dict(obj["event_type_filter"]) - if obj.get("event_type_filter") is not None - else None, - "event_filters": [ - WebhookEventFilter.from_dict(_item) for _item in obj["event_filters"] - ] - if obj.get("event_filters") is not None - else None, - "notification_uri": obj.get("notification_uri"), - "signature_header": obj.get("signature_header"), - } - ) + _obj = cls.model_validate({ + "network_id": obj.get("network_id"), + "event_type": obj.get("event_type"), + "event_type_filter": WebhookEventTypeFilter.from_dict(obj["event_type_filter"]) if obj.get("event_type_filter") is not None else None, + "event_filters": [WebhookEventFilter.from_dict(_item) for _item in obj["event_filters"]] if obj.get("event_filters") is not None else None, + "notification_uri": obj.get("notification_uri"), + "signature_header": obj.get("signature_header") + }) return _obj + + diff --git a/cdp/client/models/deploy_smart_contract_request.py b/cdp/client/models/deploy_smart_contract_request.py index 37aa2cf..cdf37a4 100644 --- a/cdp/client/models/deploy_smart_contract_request.py +++ b/cdp/client/models/deploy_smart_contract_request.py @@ -1,31 +1,33 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set from typing_extensions import Self - class DeploySmartContractRequest(BaseModel): - """DeploySmartContractRequest""" - - signed_payload: StrictStr = Field( - description="The hex-encoded signed payload of the contract deployment transaction." - ) - __properties: ClassVar[list[str]] = ["signed_payload"] + """ + DeploySmartContractRequest + """ # noqa: E501 + signed_payload: StrictStr = Field(description="The hex-encoded signed payload of the contract deployment transaction.") + __properties: ClassVar[List[str]] = ["signed_payload"] model_config = ConfigDict( populate_by_name=True, @@ -33,6 +35,7 @@ class DeploySmartContractRequest(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -43,11 +46,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of DeploySmartContractRequest from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -57,7 +60,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -67,7 +71,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of DeploySmartContractRequest from a dict""" if obj is None: return None @@ -75,5 +79,9 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({"signed_payload": obj.get("signed_payload")}) + _obj = cls.model_validate({ + "signed_payload": obj.get("signed_payload") + }) return _obj + + diff --git a/cdp/client/models/erc20_transfer_event.py b/cdp/client/models/erc20_transfer_event.py index 4a48eb9..403febd 100644 --- a/cdp/client/models/erc20_transfer_event.py +++ b/cdp/client/models/erc20_transfer_event.py @@ -1,95 +1,46 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from datetime import datetime -from typing import Any, ClassVar +import json +from datetime import datetime from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set from typing_extensions import Self - class ERC20TransferEvent(BaseModel): - """Represents an event triggered by an ERC-20 token transfer on the blockchain. Contains information about the transaction, block, and involved addresses.""" - - webhook_id: StrictStr | None = Field( - default=None, - description="Unique identifier for the webhook that triggered this event.", - alias="webhookId", - ) - event_type: StrictStr | None = Field( - default=None, - description="Type of event, in this case, an ERC-20 token transfer.", - alias="eventType", - ) - network: StrictStr | None = Field( - default=None, description="Blockchain network where the event occurred." - ) - block_hash: StrictStr | None = Field( - default=None, description="Hash of the block containing the transaction.", alias="blockHash" - ) - block_number: StrictInt | None = Field( - default=None, - description="Number of the block containing the transaction.", - alias="blockNumber", - ) - block_time: datetime | None = Field( - default=None, description="Timestamp when the block was mined.", alias="blockTime" - ) - transaction_hash: StrictStr | None = Field( - default=None, - description="Hash of the transaction that triggered the event.", - alias="transactionHash", - ) - transaction_index: StrictInt | None = Field( - default=None, - description="Position of the transaction within the block.", - alias="transactionIndex", - ) - log_index: StrictInt | None = Field( - default=None, - description="Position of the event log within the transaction.", - alias="logIndex", - ) - contract_address: StrictStr | None = Field( - default=None, description="Address of the ERC-20 token contract.", alias="contractAddress" - ) - var_from: StrictStr | None = Field( - default=None, description="Address of the sender in the token transfer.", alias="from" - ) - to: StrictStr | None = Field( - default=None, description="Address of the recipient in the token transfer." - ) - value: StrictStr | None = Field( - default=None, - description="Amount of tokens transferred, typically in the smallest unit (e.g., wei for Ethereum).", - ) - __properties: ClassVar[list[str]] = [ - "webhookId", - "eventType", - "network", - "blockHash", - "blockNumber", - "blockTime", - "transactionHash", - "transactionIndex", - "logIndex", - "contractAddress", - "from", - "to", - "value", - ] + """ + Represents an event triggered by an ERC-20 token transfer on the blockchain. Contains information about the transaction, block, and involved addresses. + """ # noqa: E501 + webhook_id: Optional[StrictStr] = Field(default=None, description="Unique identifier for the webhook that triggered this event.", alias="webhookId") + event_type: Optional[StrictStr] = Field(default=None, description="Type of event, in this case, an ERC-20 token transfer.", alias="eventType") + network: Optional[StrictStr] = Field(default=None, description="Blockchain network where the event occurred.") + block_hash: Optional[StrictStr] = Field(default=None, description="Hash of the block containing the transaction.", alias="blockHash") + block_number: Optional[StrictInt] = Field(default=None, description="Number of the block containing the transaction.", alias="blockNumber") + block_time: Optional[datetime] = Field(default=None, description="Timestamp when the block was mined.", alias="blockTime") + transaction_hash: Optional[StrictStr] = Field(default=None, description="Hash of the transaction that triggered the event.", alias="transactionHash") + transaction_index: Optional[StrictInt] = Field(default=None, description="Position of the transaction within the block.", alias="transactionIndex") + log_index: Optional[StrictInt] = Field(default=None, description="Position of the event log within the transaction.", alias="logIndex") + contract_address: Optional[StrictStr] = Field(default=None, description="Address of the ERC-20 token contract.", alias="contractAddress") + var_from: Optional[StrictStr] = Field(default=None, description="Address of the sender in the token transfer.", alias="from") + to: Optional[StrictStr] = Field(default=None, description="Address of the recipient in the token transfer.") + value: Optional[StrictStr] = Field(default=None, description="Amount of tokens transferred, typically in the smallest unit (e.g., wei for Ethereum).") + __properties: ClassVar[List[str]] = ["webhookId", "eventType", "network", "blockHash", "blockNumber", "blockTime", "transactionHash", "transactionIndex", "logIndex", "contractAddress", "from", "to", "value"] model_config = ConfigDict( populate_by_name=True, @@ -97,6 +48,7 @@ class ERC20TransferEvent(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -107,11 +59,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ERC20TransferEvent from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -121,7 +73,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -131,7 +84,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ERC20TransferEvent from a dict""" if obj is None: return None @@ -139,21 +92,21 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "webhookId": obj.get("webhookId"), - "eventType": obj.get("eventType"), - "network": obj.get("network"), - "blockHash": obj.get("blockHash"), - "blockNumber": obj.get("blockNumber"), - "blockTime": obj.get("blockTime"), - "transactionHash": obj.get("transactionHash"), - "transactionIndex": obj.get("transactionIndex"), - "logIndex": obj.get("logIndex"), - "contractAddress": obj.get("contractAddress"), - "from": obj.get("from"), - "to": obj.get("to"), - "value": obj.get("value"), - } - ) + _obj = cls.model_validate({ + "webhookId": obj.get("webhookId"), + "eventType": obj.get("eventType"), + "network": obj.get("network"), + "blockHash": obj.get("blockHash"), + "blockNumber": obj.get("blockNumber"), + "blockTime": obj.get("blockTime"), + "transactionHash": obj.get("transactionHash"), + "transactionIndex": obj.get("transactionIndex"), + "logIndex": obj.get("logIndex"), + "contractAddress": obj.get("contractAddress"), + "from": obj.get("from"), + "to": obj.get("to"), + "value": obj.get("value") + }) return _obj + + diff --git a/cdp/client/models/erc721_transfer_event.py b/cdp/client/models/erc721_transfer_event.py index 3273027..b3a8d14 100644 --- a/cdp/client/models/erc721_transfer_event.py +++ b/cdp/client/models/erc721_transfer_event.py @@ -1,94 +1,46 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from datetime import datetime -from typing import Any, ClassVar +import json +from datetime import datetime from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set from typing_extensions import Self - class ERC721TransferEvent(BaseModel): - """Represents an event triggered by an ERC-721 token transfer on the blockchain. Contains information about the transaction, block, and involved addresses.""" - - webhook_id: StrictStr | None = Field( - default=None, - description="Unique identifier for the webhook that triggered this event.", - alias="webhookId", - ) - event_type: StrictStr | None = Field( - default=None, - description="Type of event, in this case, an ERC-721 token transfer.", - alias="eventType", - ) - network: StrictStr | None = Field( - default=None, description="Blockchain network where the event occurred." - ) - block_hash: StrictStr | None = Field( - default=None, description="Hash of the block containing the transaction.", alias="blockHash" - ) - block_number: StrictInt | None = Field( - default=None, - description="Number of the block containing the transaction.", - alias="blockNumber", - ) - block_time: datetime | None = Field( - default=None, description="Timestamp when the block was mined.", alias="blockTime" - ) - transaction_hash: StrictStr | None = Field( - default=None, - description="Hash of the transaction that triggered the event.", - alias="transactionHash", - ) - transaction_index: StrictInt | None = Field( - default=None, - description="Position of the transaction within the block.", - alias="transactionIndex", - ) - log_index: StrictInt | None = Field( - default=None, - description="Position of the event log within the transaction.", - alias="logIndex", - ) - contract_address: StrictStr | None = Field( - default=None, description="Address of the ERC-721 token contract.", alias="contractAddress" - ) - var_from: StrictStr | None = Field( - default=None, description="Address of the sender in the token transfer.", alias="from" - ) - to: StrictStr | None = Field( - default=None, description="Address of the recipient in the token transfer." - ) - token_id: StrictStr | None = Field( - default=None, description="Unique identifier of the NFT being transferred.", alias="tokenId" - ) - __properties: ClassVar[list[str]] = [ - "webhookId", - "eventType", - "network", - "blockHash", - "blockNumber", - "blockTime", - "transactionHash", - "transactionIndex", - "logIndex", - "contractAddress", - "from", - "to", - "tokenId", - ] + """ + Represents an event triggered by an ERC-721 token transfer on the blockchain. Contains information about the transaction, block, and involved addresses. + """ # noqa: E501 + webhook_id: Optional[StrictStr] = Field(default=None, description="Unique identifier for the webhook that triggered this event.", alias="webhookId") + event_type: Optional[StrictStr] = Field(default=None, description="Type of event, in this case, an ERC-721 token transfer.", alias="eventType") + network: Optional[StrictStr] = Field(default=None, description="Blockchain network where the event occurred.") + block_hash: Optional[StrictStr] = Field(default=None, description="Hash of the block containing the transaction.", alias="blockHash") + block_number: Optional[StrictInt] = Field(default=None, description="Number of the block containing the transaction.", alias="blockNumber") + block_time: Optional[datetime] = Field(default=None, description="Timestamp when the block was mined.", alias="blockTime") + transaction_hash: Optional[StrictStr] = Field(default=None, description="Hash of the transaction that triggered the event.", alias="transactionHash") + transaction_index: Optional[StrictInt] = Field(default=None, description="Position of the transaction within the block.", alias="transactionIndex") + log_index: Optional[StrictInt] = Field(default=None, description="Position of the event log within the transaction.", alias="logIndex") + contract_address: Optional[StrictStr] = Field(default=None, description="Address of the ERC-721 token contract.", alias="contractAddress") + var_from: Optional[StrictStr] = Field(default=None, description="Address of the sender in the token transfer.", alias="from") + to: Optional[StrictStr] = Field(default=None, description="Address of the recipient in the token transfer.") + token_id: Optional[StrictStr] = Field(default=None, description="Unique identifier of the NFT being transferred.", alias="tokenId") + __properties: ClassVar[List[str]] = ["webhookId", "eventType", "network", "blockHash", "blockNumber", "blockTime", "transactionHash", "transactionIndex", "logIndex", "contractAddress", "from", "to", "tokenId"] model_config = ConfigDict( populate_by_name=True, @@ -96,6 +48,7 @@ class ERC721TransferEvent(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -106,11 +59,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ERC721TransferEvent from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -120,7 +73,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -130,7 +84,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ERC721TransferEvent from a dict""" if obj is None: return None @@ -138,21 +92,21 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "webhookId": obj.get("webhookId"), - "eventType": obj.get("eventType"), - "network": obj.get("network"), - "blockHash": obj.get("blockHash"), - "blockNumber": obj.get("blockNumber"), - "blockTime": obj.get("blockTime"), - "transactionHash": obj.get("transactionHash"), - "transactionIndex": obj.get("transactionIndex"), - "logIndex": obj.get("logIndex"), - "contractAddress": obj.get("contractAddress"), - "from": obj.get("from"), - "to": obj.get("to"), - "tokenId": obj.get("tokenId"), - } - ) + _obj = cls.model_validate({ + "webhookId": obj.get("webhookId"), + "eventType": obj.get("eventType"), + "network": obj.get("network"), + "blockHash": obj.get("blockHash"), + "blockNumber": obj.get("blockNumber"), + "blockTime": obj.get("blockTime"), + "transactionHash": obj.get("transactionHash"), + "transactionIndex": obj.get("transactionIndex"), + "logIndex": obj.get("logIndex"), + "contractAddress": obj.get("contractAddress"), + "from": obj.get("from"), + "to": obj.get("to"), + "tokenId": obj.get("tokenId") + }) return _obj + + diff --git a/cdp/client/models/error.py b/cdp/client/models/error.py index 19c3c9c..6d47e8a 100644 --- a/cdp/client/models/error.py +++ b/cdp/client/models/error.py @@ -1,38 +1,36 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Annotated, Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated +from typing import Optional, Set from typing_extensions import Self - class Error(BaseModel): - """An error response from the Coinbase Developer Platform API""" - - code: Annotated[str, Field(strict=True, max_length=5000)] = Field( - description="A short string representing the reported error. Can be use to handle errors programmatically." - ) - message: Annotated[str, Field(strict=True, max_length=5000)] = Field( - description="A human-readable message providing more details about the error." - ) - correlation_id: StrictStr | None = Field( - default=None, - description="A unique identifier for the request that generated the error. This can be used to help debug issues with the API.", - ) - __properties: ClassVar[list[str]] = ["code", "message", "correlation_id"] + """ + An error response from the Coinbase Developer Platform API + """ # noqa: E501 + code: Annotated[str, Field(strict=True, max_length=5000)] = Field(description="A short string representing the reported error. Can be use to handle errors programmatically.") + message: Annotated[str, Field(strict=True, max_length=5000)] = Field(description="A human-readable message providing more details about the error.") + correlation_id: Optional[StrictStr] = Field(default=None, description="A unique identifier for the request that generated the error. This can be used to help debug issues with the API.") + __properties: ClassVar[List[str]] = ["code", "message", "correlation_id"] model_config = ConfigDict( populate_by_name=True, @@ -40,6 +38,7 @@ class Error(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -50,11 +49,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Error from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -64,7 +63,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -74,7 +74,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Error from a dict""" if obj is None: return None @@ -82,11 +82,11 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "code": obj.get("code"), - "message": obj.get("message"), - "correlation_id": obj.get("correlation_id"), - } - ) + _obj = cls.model_validate({ + "code": obj.get("code"), + "message": obj.get("message"), + "correlation_id": obj.get("correlation_id") + }) return _obj + + diff --git a/cdp/client/models/ethereum_transaction.py b/cdp/client/models/ethereum_transaction.py index 9167e45..c81e8f8 100644 --- a/cdp/client/models/ethereum_transaction.py +++ b/cdp/client/models/ethereum_transaction.py @@ -1,99 +1,52 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from datetime import datetime -from typing import Any, ClassVar +import json +from datetime import datetime from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List, Optional from cdp.client.models.ethereum_transaction_access_list import EthereumTransactionAccessList from cdp.client.models.ethereum_transaction_flattened_trace import EthereumTransactionFlattenedTrace - +from typing import Optional, Set +from typing_extensions import Self class EthereumTransaction(BaseModel): - """EthereumTransaction""" - + """ + EthereumTransaction + """ # noqa: E501 var_from: StrictStr = Field(description="The onchain address of the sender.", alias="from") - gas: StrictInt | None = Field( - default=None, description="The amount of gas spent in the transaction." - ) - gas_price: StrictInt | None = Field( - default=None, - description="The price per gas spent in the transaction in atomic units of the native asset.", - ) - hash: StrictStr | None = Field( - default=None, - description="The hash of the transaction as a hexadecimal string, prefixed with 0x.", - ) - input: StrictStr | None = Field(default=None, description="The input data of the transaction.") - nonce: StrictInt | None = Field( - default=None, description="The nonce of the transaction in the source address." - ) + gas: Optional[StrictInt] = Field(default=None, description="The amount of gas spent in the transaction.") + gas_price: Optional[StrictInt] = Field(default=None, description="The price per gas spent in the transaction in atomic units of the native asset.") + hash: Optional[StrictStr] = Field(default=None, description="The hash of the transaction as a hexadecimal string, prefixed with 0x.") + input: Optional[StrictStr] = Field(default=None, description="The input data of the transaction.") + nonce: Optional[StrictInt] = Field(default=None, description="The nonce of the transaction in the source address.") to: StrictStr = Field(description="The onchain address of the receiver.") - index: StrictInt | None = Field( - default=None, description="The index of the transaction in the block." - ) - value: StrictStr | None = Field( - default=None, - description="The value of the transaction in atomic units of the native asset.", - ) - type: StrictInt | None = Field( - default=None, - description="The EIP-2718 transaction type. See https://eips.ethereum.org/EIPS/eip-2718 for more details.", - ) - max_fee_per_gas: StrictInt | None = Field( - default=None, - description="The max fee per gas as defined in EIP-1559. https://eips.ethereum.org/EIPS/eip-1559 for more details.", - ) - max_priority_fee_per_gas: StrictInt | None = Field( - default=None, - description="The max priority fee per gas as defined in EIP-1559. https://eips.ethereum.org/EIPS/eip-1559 for more details.", - ) - priority_fee_per_gas: StrictInt | None = Field( - default=None, - description="The confirmed priority fee per gas as defined in EIP-1559. https://eips.ethereum.org/EIPS/eip-1559 for more details.", - ) - transaction_access_list: EthereumTransactionAccessList | None = None - flattened_traces: list[EthereumTransactionFlattenedTrace] | None = None - block_timestamp: datetime | None = Field( - default=None, description="The timestamp of the block in which the event was emitted" - ) - mint: StrictStr | None = Field( - default=None, - description="This is for handling optimism rollup specific EIP-2718 transaction type field.", - ) - __properties: ClassVar[list[str]] = [ - "from", - "gas", - "gas_price", - "hash", - "input", - "nonce", - "to", - "index", - "value", - "type", - "max_fee_per_gas", - "max_priority_fee_per_gas", - "priority_fee_per_gas", - "transaction_access_list", - "flattened_traces", - "block_timestamp", - "mint", - ] + index: Optional[StrictInt] = Field(default=None, description="The index of the transaction in the block.") + value: Optional[StrictStr] = Field(default=None, description="The value of the transaction in atomic units of the native asset.") + type: Optional[StrictInt] = Field(default=None, description="The EIP-2718 transaction type. See https://eips.ethereum.org/EIPS/eip-2718 for more details.") + max_fee_per_gas: Optional[StrictInt] = Field(default=None, description="The max fee per gas as defined in EIP-1559. https://eips.ethereum.org/EIPS/eip-1559 for more details.") + max_priority_fee_per_gas: Optional[StrictInt] = Field(default=None, description="The max priority fee per gas as defined in EIP-1559. https://eips.ethereum.org/EIPS/eip-1559 for more details.") + priority_fee_per_gas: Optional[StrictInt] = Field(default=None, description="The confirmed priority fee per gas as defined in EIP-1559. https://eips.ethereum.org/EIPS/eip-1559 for more details.") + transaction_access_list: Optional[EthereumTransactionAccessList] = None + flattened_traces: Optional[List[EthereumTransactionFlattenedTrace]] = None + block_timestamp: Optional[datetime] = Field(default=None, description="The timestamp of the block in which the event was emitted") + mint: Optional[StrictStr] = Field(default=None, description="This is for handling optimism rollup specific EIP-2718 transaction type field.") + __properties: ClassVar[List[str]] = ["from", "gas", "gas_price", "hash", "input", "nonce", "to", "index", "value", "type", "max_fee_per_gas", "max_priority_fee_per_gas", "priority_fee_per_gas", "transaction_access_list", "flattened_traces", "block_timestamp", "mint"] model_config = ConfigDict( populate_by_name=True, @@ -101,6 +54,7 @@ class EthereumTransaction(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -111,11 +65,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of EthereumTransaction from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -125,7 +79,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -134,18 +89,18 @@ def to_dict(self) -> dict[str, Any]: ) # override the default output from pydantic by calling `to_dict()` of transaction_access_list if self.transaction_access_list: - _dict["transaction_access_list"] = self.transaction_access_list.to_dict() + _dict['transaction_access_list'] = self.transaction_access_list.to_dict() # override the default output from pydantic by calling `to_dict()` of each item in flattened_traces (list) _items = [] if self.flattened_traces: for _item_flattened_traces in self.flattened_traces: if _item_flattened_traces: _items.append(_item_flattened_traces.to_dict()) - _dict["flattened_traces"] = _items + _dict['flattened_traces'] = _items return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of EthereumTransaction from a dict""" if obj is None: return None @@ -153,34 +108,25 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "from": obj.get("from"), - "gas": obj.get("gas"), - "gas_price": obj.get("gas_price"), - "hash": obj.get("hash"), - "input": obj.get("input"), - "nonce": obj.get("nonce"), - "to": obj.get("to"), - "index": obj.get("index"), - "value": obj.get("value"), - "type": obj.get("type"), - "max_fee_per_gas": obj.get("max_fee_per_gas"), - "max_priority_fee_per_gas": obj.get("max_priority_fee_per_gas"), - "priority_fee_per_gas": obj.get("priority_fee_per_gas"), - "transaction_access_list": EthereumTransactionAccessList.from_dict( - obj["transaction_access_list"] - ) - if obj.get("transaction_access_list") is not None - else None, - "flattened_traces": [ - EthereumTransactionFlattenedTrace.from_dict(_item) - for _item in obj["flattened_traces"] - ] - if obj.get("flattened_traces") is not None - else None, - "block_timestamp": obj.get("block_timestamp"), - "mint": obj.get("mint"), - } - ) + _obj = cls.model_validate({ + "from": obj.get("from"), + "gas": obj.get("gas"), + "gas_price": obj.get("gas_price"), + "hash": obj.get("hash"), + "input": obj.get("input"), + "nonce": obj.get("nonce"), + "to": obj.get("to"), + "index": obj.get("index"), + "value": obj.get("value"), + "type": obj.get("type"), + "max_fee_per_gas": obj.get("max_fee_per_gas"), + "max_priority_fee_per_gas": obj.get("max_priority_fee_per_gas"), + "priority_fee_per_gas": obj.get("priority_fee_per_gas"), + "transaction_access_list": EthereumTransactionAccessList.from_dict(obj["transaction_access_list"]) if obj.get("transaction_access_list") is not None else None, + "flattened_traces": [EthereumTransactionFlattenedTrace.from_dict(_item) for _item in obj["flattened_traces"]] if obj.get("flattened_traces") is not None else None, + "block_timestamp": obj.get("block_timestamp"), + "mint": obj.get("mint") + }) return _obj + + diff --git a/cdp/client/models/ethereum_transaction_access.py b/cdp/client/models/ethereum_transaction_access.py index 203781a..2b9afab 100644 --- a/cdp/client/models/ethereum_transaction_access.py +++ b/cdp/client/models/ethereum_transaction_access.py @@ -1,30 +1,34 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set from typing_extensions import Self - class EthereumTransactionAccess(BaseModel): - """EthereumTransactionAccess""" - - address: StrictStr | None = None - storage_keys: list[StrictStr] | None = None - __properties: ClassVar[list[str]] = ["address", "storage_keys"] + """ + EthereumTransactionAccess + """ # noqa: E501 + address: Optional[StrictStr] = None + storage_keys: Optional[List[StrictStr]] = None + __properties: ClassVar[List[str]] = ["address", "storage_keys"] model_config = ConfigDict( populate_by_name=True, @@ -32,6 +36,7 @@ class EthereumTransactionAccess(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -42,11 +47,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of EthereumTransactionAccess from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -56,7 +61,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -66,7 +72,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of EthereumTransactionAccess from a dict""" if obj is None: return None @@ -74,7 +80,10 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - {"address": obj.get("address"), "storage_keys": obj.get("storage_keys")} - ) + _obj = cls.model_validate({ + "address": obj.get("address"), + "storage_keys": obj.get("storage_keys") + }) return _obj + + diff --git a/cdp/client/models/ethereum_transaction_access_list.py b/cdp/client/models/ethereum_transaction_access_list.py index e643de8..46a176b 100644 --- a/cdp/client/models/ethereum_transaction_access_list.py +++ b/cdp/client/models/ethereum_transaction_access_list.py @@ -1,31 +1,34 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List, Optional from cdp.client.models.ethereum_transaction_access import EthereumTransactionAccess - +from typing import Optional, Set +from typing_extensions import Self class EthereumTransactionAccessList(BaseModel): - """EthereumTransactionAccessList""" - - access_list: list[EthereumTransactionAccess] | None = None - __properties: ClassVar[list[str]] = ["access_list"] + """ + EthereumTransactionAccessList + """ # noqa: E501 + access_list: Optional[List[EthereumTransactionAccess]] = None + __properties: ClassVar[List[str]] = ["access_list"] model_config = ConfigDict( populate_by_name=True, @@ -33,6 +36,7 @@ class EthereumTransactionAccessList(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -43,11 +47,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of EthereumTransactionAccessList from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -57,7 +61,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -70,11 +75,11 @@ def to_dict(self) -> dict[str, Any]: for _item_access_list in self.access_list: if _item_access_list: _items.append(_item_access_list.to_dict()) - _dict["access_list"] = _items + _dict['access_list'] = _items return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of EthereumTransactionAccessList from a dict""" if obj is None: return None @@ -82,13 +87,9 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "access_list": [ - EthereumTransactionAccess.from_dict(_item) for _item in obj["access_list"] - ] - if obj.get("access_list") is not None - else None - } - ) + _obj = cls.model_validate({ + "access_list": [EthereumTransactionAccess.from_dict(_item) for _item in obj["access_list"]] if obj.get("access_list") is not None else None + }) return _obj + + diff --git a/cdp/client/models/ethereum_transaction_flattened_trace.py b/cdp/client/models/ethereum_transaction_flattened_trace.py index fb7c8fe..0d1b9a5 100644 --- a/cdp/client/models/ethereum_transaction_flattened_trace.py +++ b/cdp/client/models/ethereum_transaction_flattened_trace.py @@ -1,67 +1,51 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set from typing_extensions import Self - class EthereumTransactionFlattenedTrace(BaseModel): - """EthereumTransactionFlattenedTrace""" - - error: StrictStr | None = None - type: StrictStr | None = None - var_from: StrictStr | None = Field(default=None, alias="from") - to: StrictStr | None = None - value: StrictStr | None = None - gas: StrictInt | None = None - gas_used: StrictInt | None = None - input: StrictStr | None = None - output: StrictStr | None = None - sub_traces: StrictInt | None = None - trace_address: list[StrictInt] | None = None - trace_type: StrictStr | None = None - call_type: StrictStr | None = None - trace_id: StrictStr | None = None - status: StrictInt | None = None - block_hash: StrictStr | None = None - block_number: StrictInt | None = None - transaction_hash: StrictStr | None = None - transaction_index: StrictInt | None = None - __properties: ClassVar[list[str]] = [ - "error", - "type", - "from", - "to", - "value", - "gas", - "gas_used", - "input", - "output", - "sub_traces", - "trace_address", - "trace_type", - "call_type", - "trace_id", - "status", - "block_hash", - "block_number", - "transaction_hash", - "transaction_index", - ] + """ + EthereumTransactionFlattenedTrace + """ # noqa: E501 + error: Optional[StrictStr] = None + type: Optional[StrictStr] = None + var_from: Optional[StrictStr] = Field(default=None, alias="from") + to: Optional[StrictStr] = None + value: Optional[StrictStr] = None + gas: Optional[StrictInt] = None + gas_used: Optional[StrictInt] = None + input: Optional[StrictStr] = None + output: Optional[StrictStr] = None + sub_traces: Optional[StrictInt] = None + trace_address: Optional[List[StrictInt]] = None + trace_type: Optional[StrictStr] = None + call_type: Optional[StrictStr] = None + trace_id: Optional[StrictStr] = None + status: Optional[StrictInt] = None + block_hash: Optional[StrictStr] = None + block_number: Optional[StrictInt] = None + transaction_hash: Optional[StrictStr] = None + transaction_index: Optional[StrictInt] = None + __properties: ClassVar[List[str]] = ["error", "type", "from", "to", "value", "gas", "gas_used", "input", "output", "sub_traces", "trace_address", "trace_type", "call_type", "trace_id", "status", "block_hash", "block_number", "transaction_hash", "transaction_index"] model_config = ConfigDict( populate_by_name=True, @@ -69,6 +53,7 @@ class EthereumTransactionFlattenedTrace(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -79,11 +64,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of EthereumTransactionFlattenedTrace from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -93,7 +78,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -103,7 +89,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of EthereumTransactionFlattenedTrace from a dict""" if obj is None: return None @@ -111,27 +97,27 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "error": obj.get("error"), - "type": obj.get("type"), - "from": obj.get("from"), - "to": obj.get("to"), - "value": obj.get("value"), - "gas": obj.get("gas"), - "gas_used": obj.get("gas_used"), - "input": obj.get("input"), - "output": obj.get("output"), - "sub_traces": obj.get("sub_traces"), - "trace_address": obj.get("trace_address"), - "trace_type": obj.get("trace_type"), - "call_type": obj.get("call_type"), - "trace_id": obj.get("trace_id"), - "status": obj.get("status"), - "block_hash": obj.get("block_hash"), - "block_number": obj.get("block_number"), - "transaction_hash": obj.get("transaction_hash"), - "transaction_index": obj.get("transaction_index"), - } - ) + _obj = cls.model_validate({ + "error": obj.get("error"), + "type": obj.get("type"), + "from": obj.get("from"), + "to": obj.get("to"), + "value": obj.get("value"), + "gas": obj.get("gas"), + "gas_used": obj.get("gas_used"), + "input": obj.get("input"), + "output": obj.get("output"), + "sub_traces": obj.get("sub_traces"), + "trace_address": obj.get("trace_address"), + "trace_type": obj.get("trace_type"), + "call_type": obj.get("call_type"), + "trace_id": obj.get("trace_id"), + "status": obj.get("status"), + "block_hash": obj.get("block_hash"), + "block_number": obj.get("block_number"), + "transaction_hash": obj.get("transaction_hash"), + "transaction_index": obj.get("transaction_index") + }) return _obj + + diff --git a/cdp/client/models/ethereum_validator_metadata.py b/cdp/client/models/ethereum_validator_metadata.py index bd4a238..43d72ec 100644 --- a/cdp/client/models/ethereum_validator_metadata.py +++ b/cdp/client/models/ethereum_validator_metadata.py @@ -1,57 +1,42 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.balance import Balance - +from typing import Optional, Set +from typing_extensions import Self class EthereumValidatorMetadata(BaseModel): - """An Ethereum validator.""" - + """ + An Ethereum validator. + """ # noqa: E501 index: StrictStr = Field(description="The index of the validator in the validator set.") public_key: StrictStr = Field(description="The public key of the validator.") - withdrawal_address: StrictStr = Field( - description="The address to which the validator's rewards are sent." - ) + withdrawal_address: StrictStr = Field(description="The address to which the validator's rewards are sent.") slashed: StrictBool = Field(description="Whether the validator has been slashed.") - activation_epoch: StrictStr = Field( - description="The epoch at which the validator was activated.", alias="activationEpoch" - ) - exit_epoch: StrictStr = Field( - description="The epoch at which the validator exited.", alias="exitEpoch" - ) - withdrawable_epoch: StrictStr = Field( - description="The epoch at which the validator can withdraw.", alias="withdrawableEpoch" - ) + activation_epoch: StrictStr = Field(description="The epoch at which the validator was activated.", alias="activationEpoch") + exit_epoch: StrictStr = Field(description="The epoch at which the validator exited.", alias="exitEpoch") + withdrawable_epoch: StrictStr = Field(description="The epoch at which the validator can withdraw.", alias="withdrawableEpoch") balance: Balance effective_balance: Balance - __properties: ClassVar[list[str]] = [ - "index", - "public_key", - "withdrawal_address", - "slashed", - "activationEpoch", - "exitEpoch", - "withdrawableEpoch", - "balance", - "effective_balance", - ] + __properties: ClassVar[List[str]] = ["index", "public_key", "withdrawal_address", "slashed", "activationEpoch", "exitEpoch", "withdrawableEpoch", "balance", "effective_balance"] model_config = ConfigDict( populate_by_name=True, @@ -59,6 +44,7 @@ class EthereumValidatorMetadata(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -69,11 +55,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of EthereumValidatorMetadata from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -83,7 +69,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -92,14 +79,14 @@ def to_dict(self) -> dict[str, Any]: ) # override the default output from pydantic by calling `to_dict()` of balance if self.balance: - _dict["balance"] = self.balance.to_dict() + _dict['balance'] = self.balance.to_dict() # override the default output from pydantic by calling `to_dict()` of effective_balance if self.effective_balance: - _dict["effective_balance"] = self.effective_balance.to_dict() + _dict['effective_balance'] = self.effective_balance.to_dict() return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of EthereumValidatorMetadata from a dict""" if obj is None: return None @@ -107,21 +94,17 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "index": obj.get("index"), - "public_key": obj.get("public_key"), - "withdrawal_address": obj.get("withdrawal_address"), - "slashed": obj.get("slashed"), - "activationEpoch": obj.get("activationEpoch"), - "exitEpoch": obj.get("exitEpoch"), - "withdrawableEpoch": obj.get("withdrawableEpoch"), - "balance": Balance.from_dict(obj["balance"]) - if obj.get("balance") is not None - else None, - "effective_balance": Balance.from_dict(obj["effective_balance"]) - if obj.get("effective_balance") is not None - else None, - } - ) + _obj = cls.model_validate({ + "index": obj.get("index"), + "public_key": obj.get("public_key"), + "withdrawal_address": obj.get("withdrawal_address"), + "slashed": obj.get("slashed"), + "activationEpoch": obj.get("activationEpoch"), + "exitEpoch": obj.get("exitEpoch"), + "withdrawableEpoch": obj.get("withdrawableEpoch"), + "balance": Balance.from_dict(obj["balance"]) if obj.get("balance") is not None else None, + "effective_balance": Balance.from_dict(obj["effective_balance"]) if obj.get("effective_balance") is not None else None + }) return _obj + + diff --git a/cdp/client/models/faucet_transaction.py b/cdp/client/models/faucet_transaction.py index 1f83dd4..cfad1a9 100644 --- a/cdp/client/models/faucet_transaction.py +++ b/cdp/client/models/faucet_transaction.py @@ -1,34 +1,34 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set from typing_extensions import Self - class FaucetTransaction(BaseModel): - """The faucet transaction""" - - transaction_hash: StrictStr = Field( - description="The transaction hash of the transaction the faucet created." - ) - transaction_link: StrictStr = Field( - description="Link to the transaction on the blockchain explorer." - ) - __properties: ClassVar[list[str]] = ["transaction_hash", "transaction_link"] + """ + The faucet transaction + """ # noqa: E501 + transaction_hash: StrictStr = Field(description="The transaction hash of the transaction the faucet created.") + transaction_link: StrictStr = Field(description="Link to the transaction on the blockchain explorer.") + __properties: ClassVar[List[str]] = ["transaction_hash", "transaction_link"] model_config = ConfigDict( populate_by_name=True, @@ -36,6 +36,7 @@ class FaucetTransaction(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -46,11 +47,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of FaucetTransaction from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -60,7 +61,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -70,7 +72,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of FaucetTransaction from a dict""" if obj is None: return None @@ -78,10 +80,10 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "transaction_hash": obj.get("transaction_hash"), - "transaction_link": obj.get("transaction_link"), - } - ) + _obj = cls.model_validate({ + "transaction_hash": obj.get("transaction_hash"), + "transaction_link": obj.get("transaction_link") + }) return _obj + + diff --git a/cdp/client/models/feature_set.py b/cdp/client/models/feature_set.py index 38b5593..0c159a1 100644 --- a/cdp/client/models/feature_set.py +++ b/cdp/client/models/feature_set.py @@ -1,41 +1,38 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set from typing_extensions import Self - class FeatureSet(BaseModel): - """FeatureSet""" - + """ + FeatureSet + """ # noqa: E501 faucet: StrictBool = Field(description="Whether the network supports a faucet") server_signer: StrictBool = Field(description="Whether the network supports Server-Signers") transfer: StrictBool = Field(description="Whether the network supports transfers") trade: StrictBool = Field(description="Whether the network supports trading") stake: StrictBool = Field(description="Whether the network supports staking") gasless_send: StrictBool = Field(description="Whether the network supports gasless sends") - __properties: ClassVar[list[str]] = [ - "faucet", - "server_signer", - "transfer", - "trade", - "stake", - "gasless_send", - ] + __properties: ClassVar[List[str]] = ["faucet", "server_signer", "transfer", "trade", "stake", "gasless_send"] model_config = ConfigDict( populate_by_name=True, @@ -43,6 +40,7 @@ class FeatureSet(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -53,11 +51,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of FeatureSet from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -67,7 +65,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -77,7 +76,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of FeatureSet from a dict""" if obj is None: return None @@ -85,14 +84,14 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "faucet": obj.get("faucet"), - "server_signer": obj.get("server_signer"), - "transfer": obj.get("transfer"), - "trade": obj.get("trade"), - "stake": obj.get("stake"), - "gasless_send": obj.get("gasless_send"), - } - ) + _obj = cls.model_validate({ + "faucet": obj.get("faucet"), + "server_signer": obj.get("server_signer"), + "transfer": obj.get("transfer"), + "trade": obj.get("trade"), + "stake": obj.get("stake"), + "gasless_send": obj.get("gasless_send") + }) return _obj + + diff --git a/cdp/client/models/fetch_historical_staking_balances200_response.py b/cdp/client/models/fetch_historical_staking_balances200_response.py index 0bcb86a..8fef137 100644 --- a/cdp/client/models/fetch_historical_staking_balances200_response.py +++ b/cdp/client/models/fetch_historical_staking_balances200_response.py @@ -1,35 +1,36 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.staking_balance import StakingBalance - +from typing import Optional, Set +from typing_extensions import Self class FetchHistoricalStakingBalances200Response(BaseModel): - """ """ - - data: list[StakingBalance] - has_more: StrictBool = Field( - description="True if this list has another page of items after this one that can be fetched." - ) + """ + + """ # noqa: E501 + data: List[StakingBalance] + has_more: StrictBool = Field(description="True if this list has another page of items after this one that can be fetched.") next_page: StrictStr = Field(description="The page token to be used to fetch the next page.") - __properties: ClassVar[list[str]] = ["data", "has_more", "next_page"] + __properties: ClassVar[List[str]] = ["data", "has_more", "next_page"] model_config = ConfigDict( populate_by_name=True, @@ -37,6 +38,7 @@ class FetchHistoricalStakingBalances200Response(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -47,11 +49,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of FetchHistoricalStakingBalances200Response from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -61,7 +63,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -74,11 +77,11 @@ def to_dict(self) -> dict[str, Any]: for _item_data in self.data: if _item_data: _items.append(_item_data.to_dict()) - _dict["data"] = _items + _dict['data'] = _items return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of FetchHistoricalStakingBalances200Response from a dict""" if obj is None: return None @@ -86,13 +89,11 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "data": [StakingBalance.from_dict(_item) for _item in obj["data"]] - if obj.get("data") is not None - else None, - "has_more": obj.get("has_more"), - "next_page": obj.get("next_page"), - } - ) + _obj = cls.model_validate({ + "data": [StakingBalance.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None, + "has_more": obj.get("has_more"), + "next_page": obj.get("next_page") + }) return _obj + + diff --git a/cdp/client/models/fetch_staking_rewards200_response.py b/cdp/client/models/fetch_staking_rewards200_response.py index a395b5f..53feb0c 100644 --- a/cdp/client/models/fetch_staking_rewards200_response.py +++ b/cdp/client/models/fetch_staking_rewards200_response.py @@ -1,35 +1,36 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.staking_reward import StakingReward - +from typing import Optional, Set +from typing_extensions import Self class FetchStakingRewards200Response(BaseModel): - """ """ - - data: list[StakingReward] - has_more: StrictBool = Field( - description="True if this list has another page of items after this one that can be fetched." - ) + """ + + """ # noqa: E501 + data: List[StakingReward] + has_more: StrictBool = Field(description="True if this list has another page of items after this one that can be fetched.") next_page: StrictStr = Field(description="The page token to be used to fetch the next page.") - __properties: ClassVar[list[str]] = ["data", "has_more", "next_page"] + __properties: ClassVar[List[str]] = ["data", "has_more", "next_page"] model_config = ConfigDict( populate_by_name=True, @@ -37,6 +38,7 @@ class FetchStakingRewards200Response(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -47,11 +49,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of FetchStakingRewards200Response from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -61,7 +63,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -74,11 +77,11 @@ def to_dict(self) -> dict[str, Any]: for _item_data in self.data: if _item_data: _items.append(_item_data.to_dict()) - _dict["data"] = _items + _dict['data'] = _items return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of FetchStakingRewards200Response from a dict""" if obj is None: return None @@ -86,13 +89,11 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "data": [StakingReward.from_dict(_item) for _item in obj["data"]] - if obj.get("data") is not None - else None, - "has_more": obj.get("has_more"), - "next_page": obj.get("next_page"), - } - ) + _obj = cls.model_validate({ + "data": [StakingReward.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None, + "has_more": obj.get("has_more"), + "next_page": obj.get("next_page") + }) return _obj + + diff --git a/cdp/client/models/fetch_staking_rewards_request.py b/cdp/client/models/fetch_staking_rewards_request.py index e8738e3..04b47a7 100644 --- a/cdp/client/models/fetch_staking_rewards_request.py +++ b/cdp/client/models/fetch_staking_rewards_request.py @@ -1,48 +1,40 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from datetime import datetime -from typing import Any, ClassVar +import json +from datetime import datetime from pydantic import BaseModel, ConfigDict, Field, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.staking_reward_format import StakingRewardFormat - +from typing import Optional, Set +from typing_extensions import Self class FetchStakingRewardsRequest(BaseModel): - """FetchStakingRewardsRequest""" - + """ + FetchStakingRewardsRequest + """ # noqa: E501 network_id: StrictStr = Field(description="The ID of the blockchain network") - asset_id: StrictStr = Field( - description="The ID of the asset for which the staking rewards are being fetched" - ) - address_ids: list[StrictStr] = Field( - description="The onchain addresses for which the staking rewards are being fetched" - ) + asset_id: StrictStr = Field(description="The ID of the asset for which the staking rewards are being fetched") + address_ids: List[StrictStr] = Field(description="The onchain addresses for which the staking rewards are being fetched") start_time: datetime = Field(description="The start time of this reward period") end_time: datetime = Field(description="The end time of this reward period") format: StakingRewardFormat - __properties: ClassVar[list[str]] = [ - "network_id", - "asset_id", - "address_ids", - "start_time", - "end_time", - "format", - ] + __properties: ClassVar[List[str]] = ["network_id", "asset_id", "address_ids", "start_time", "end_time", "format"] model_config = ConfigDict( populate_by_name=True, @@ -50,6 +42,7 @@ class FetchStakingRewardsRequest(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -60,11 +53,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of FetchStakingRewardsRequest from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -74,7 +67,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -84,7 +78,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of FetchStakingRewardsRequest from a dict""" if obj is None: return None @@ -92,16 +86,14 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "network_id": obj.get("network_id"), - "asset_id": obj.get("asset_id"), - "address_ids": obj.get("address_ids"), - "start_time": obj.get("start_time"), - "end_time": obj.get("end_time"), - "format": obj.get("format") - if obj.get("format") is not None - else StakingRewardFormat.USD, - } - ) + _obj = cls.model_validate({ + "network_id": obj.get("network_id"), + "asset_id": obj.get("asset_id"), + "address_ids": obj.get("address_ids"), + "start_time": obj.get("start_time"), + "end_time": obj.get("end_time"), + "format": obj.get("format") if obj.get("format") is not None else StakingRewardFormat.USD + }) return _obj + + diff --git a/cdp/client/models/get_staking_context_request.py b/cdp/client/models/get_staking_context_request.py index aeaf0bd..c2918e6 100644 --- a/cdp/client/models/get_staking_context_request.py +++ b/cdp/client/models/get_staking_context_request.py @@ -1,34 +1,36 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set from typing_extensions import Self - class GetStakingContextRequest(BaseModel): - """GetStakingContextRequest""" - + """ + GetStakingContextRequest + """ # noqa: E501 network_id: StrictStr = Field(description="The ID of the blockchain network") asset_id: StrictStr = Field(description="The ID of the asset being staked") - address_id: StrictStr = Field( - description="The onchain address for which the staking context is being fetched" - ) - options: dict[str, StrictStr] - __properties: ClassVar[list[str]] = ["network_id", "asset_id", "address_id", "options"] + address_id: StrictStr = Field(description="The onchain address for which the staking context is being fetched") + options: Dict[str, StrictStr] + __properties: ClassVar[List[str]] = ["network_id", "asset_id", "address_id", "options"] model_config = ConfigDict( populate_by_name=True, @@ -36,6 +38,7 @@ class GetStakingContextRequest(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -46,11 +49,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of GetStakingContextRequest from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -60,7 +63,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -70,7 +74,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of GetStakingContextRequest from a dict""" if obj is None: return None @@ -78,12 +82,12 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "network_id": obj.get("network_id"), - "asset_id": obj.get("asset_id"), - "address_id": obj.get("address_id"), - "options": obj.get("options"), - } - ) + _obj = cls.model_validate({ + "network_id": obj.get("network_id"), + "asset_id": obj.get("asset_id"), + "address_id": obj.get("address_id"), + "options": obj.get("options") + }) return _obj + + diff --git a/cdp/client/models/historical_balance.py b/cdp/client/models/historical_balance.py index f15c35c..48c43f5 100644 --- a/cdp/client/models/historical_balance.py +++ b/cdp/client/models/historical_balance.py @@ -1,38 +1,37 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.asset import Asset - +from typing import Optional, Set +from typing_extensions import Self class HistoricalBalance(BaseModel): - """The balance of an asset onchain at a particular block""" - + """ + The balance of an asset onchain at a particular block + """ # noqa: E501 amount: StrictStr = Field(description="The amount in the atomic units of the asset") - block_hash: StrictStr = Field( - description="The hash of the block at which the balance was recorded" - ) - block_height: StrictStr = Field( - description="The block height at which the balance was recorded" - ) + block_hash: StrictStr = Field(description="The hash of the block at which the balance was recorded") + block_height: StrictStr = Field(description="The block height at which the balance was recorded") asset: Asset - __properties: ClassVar[list[str]] = ["amount", "block_hash", "block_height", "asset"] + __properties: ClassVar[List[str]] = ["amount", "block_hash", "block_height", "asset"] model_config = ConfigDict( populate_by_name=True, @@ -40,6 +39,7 @@ class HistoricalBalance(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -50,11 +50,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of HistoricalBalance from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -64,7 +64,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -73,11 +74,11 @@ def to_dict(self) -> dict[str, Any]: ) # override the default output from pydantic by calling `to_dict()` of asset if self.asset: - _dict["asset"] = self.asset.to_dict() + _dict['asset'] = self.asset.to_dict() return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of HistoricalBalance from a dict""" if obj is None: return None @@ -85,12 +86,12 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "amount": obj.get("amount"), - "block_hash": obj.get("block_hash"), - "block_height": obj.get("block_height"), - "asset": Asset.from_dict(obj["asset"]) if obj.get("asset") is not None else None, - } - ) + _obj = cls.model_validate({ + "amount": obj.get("amount"), + "block_hash": obj.get("block_hash"), + "block_height": obj.get("block_height"), + "asset": Asset.from_dict(obj["asset"]) if obj.get("asset") is not None else None + }) return _obj + + diff --git a/cdp/client/models/multi_token_contract_options.py b/cdp/client/models/multi_token_contract_options.py new file mode 100644 index 0000000..de9dff7 --- /dev/null +++ b/cdp/client/models/multi_token_contract_options.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class MultiTokenContractOptions(BaseModel): + """ + Options for multi-token contract creation + """ # noqa: E501 + uri: StrictStr = Field(description="The URI for all token metadata") + __properties: ClassVar[List[str]] = ["uri"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of MultiTokenContractOptions from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of MultiTokenContractOptions from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "uri": obj.get("uri") + }) + return _obj + + diff --git a/cdp/client/models/network.py b/cdp/client/models/network.py index 550bab9..5b5e4d4 100644 --- a/cdp/client/models/network.py +++ b/cdp/client/models/network.py @@ -1,31 +1,34 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr, field_validator -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List, Optional from cdp.client.models.asset import Asset from cdp.client.models.feature_set import FeatureSet from cdp.client.models.network_identifier import NetworkIdentifier - +from typing import Optional, Set +from typing_extensions import Self class Network(BaseModel): - """Network""" - + """ + Network + """ # noqa: E501 id: NetworkIdentifier display_name: StrictStr = Field(description="The human-readable name of the blockchain network") chain_id: StrictInt = Field(description="The chain ID of the blockchain network") @@ -33,24 +36,13 @@ class Network(BaseModel): is_testnet: StrictBool = Field(description="Whether the network is a testnet or not") native_asset: Asset feature_set: FeatureSet - address_path_prefix: StrictStr | None = Field( - default=None, description="The BIP44 path prefix for the network" - ) - __properties: ClassVar[list[str]] = [ - "id", - "display_name", - "chain_id", - "protocol_family", - "is_testnet", - "native_asset", - "feature_set", - "address_path_prefix", - ] - - @field_validator("protocol_family") + address_path_prefix: Optional[StrictStr] = Field(default=None, description="The BIP44 path prefix for the network") + __properties: ClassVar[List[str]] = ["id", "display_name", "chain_id", "protocol_family", "is_testnet", "native_asset", "feature_set", "address_path_prefix"] + + @field_validator('protocol_family') def protocol_family_validate_enum(cls, value): """Validates the enum""" - if value not in set(["evm", "solana"]): + if value not in set(['evm', 'solana']): raise ValueError("must be one of enum values ('evm', 'solana')") return value @@ -60,6 +52,7 @@ def protocol_family_validate_enum(cls, value): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -70,11 +63,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Network from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -84,7 +77,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -93,14 +87,14 @@ def to_dict(self) -> dict[str, Any]: ) # override the default output from pydantic by calling `to_dict()` of native_asset if self.native_asset: - _dict["native_asset"] = self.native_asset.to_dict() + _dict['native_asset'] = self.native_asset.to_dict() # override the default output from pydantic by calling `to_dict()` of feature_set if self.feature_set: - _dict["feature_set"] = self.feature_set.to_dict() + _dict['feature_set'] = self.feature_set.to_dict() return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Network from a dict""" if obj is None: return None @@ -108,20 +102,16 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "id": obj.get("id"), - "display_name": obj.get("display_name"), - "chain_id": obj.get("chain_id"), - "protocol_family": obj.get("protocol_family"), - "is_testnet": obj.get("is_testnet"), - "native_asset": Asset.from_dict(obj["native_asset"]) - if obj.get("native_asset") is not None - else None, - "feature_set": FeatureSet.from_dict(obj["feature_set"]) - if obj.get("feature_set") is not None - else None, - "address_path_prefix": obj.get("address_path_prefix"), - } - ) + _obj = cls.model_validate({ + "id": obj.get("id"), + "display_name": obj.get("display_name"), + "chain_id": obj.get("chain_id"), + "protocol_family": obj.get("protocol_family"), + "is_testnet": obj.get("is_testnet"), + "native_asset": Asset.from_dict(obj["native_asset"]) if obj.get("native_asset") is not None else None, + "feature_set": FeatureSet.from_dict(obj["feature_set"]) if obj.get("feature_set") is not None else None, + "address_path_prefix": obj.get("address_path_prefix") + }) return _obj + + diff --git a/cdp/client/models/network_identifier.py b/cdp/client/models/network_identifier.py index 51b106e..7d3a547 100644 --- a/cdp/client/models/network_identifier.py +++ b/cdp/client/models/network_identifier.py @@ -1,37 +1,43 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import json from enum import Enum - from typing_extensions import Self class NetworkIdentifier(str, Enum): - """The ID of the blockchain network. This is unique across all networks, and takes the form of `-`.""" + """ + The ID of the blockchain network. This is unique across all networks, and takes the form of `-`. + """ """ allowed enum values """ - BASE_MINUS_SEPOLIA = "base-sepolia" - BASE_MINUS_MAINNET = "base-mainnet" - ETHEREUM_MINUS_HOLESKY = "ethereum-holesky" - ETHEREUM_MINUS_MAINNET = "ethereum-mainnet" - POLYGON_MINUS_MAINNET = "polygon-mainnet" - SOLANA_MINUS_DEVNET = "solana-devnet" - SOLANA_MINUS_MAINNET = "solana-mainnet" - ARBITRUM_MINUS_MAINNET = "arbitrum-mainnet" + BASE_MINUS_SEPOLIA = 'base-sepolia' + BASE_MINUS_MAINNET = 'base-mainnet' + ETHEREUM_MINUS_HOLESKY = 'ethereum-holesky' + ETHEREUM_MINUS_MAINNET = 'ethereum-mainnet' + POLYGON_MINUS_MAINNET = 'polygon-mainnet' + SOLANA_MINUS_DEVNET = 'solana-devnet' + SOLANA_MINUS_MAINNET = 'solana-mainnet' + ARBITRUM_MINUS_MAINNET = 'arbitrum-mainnet' @classmethod def from_json(cls, json_str: str) -> Self: """Create an instance of NetworkIdentifier from a JSON string""" return cls(json.loads(json_str)) + + diff --git a/cdp/client/models/nft_contract_options.py b/cdp/client/models/nft_contract_options.py index 38f0252..7f1e350 100644 --- a/cdp/client/models/nft_contract_options.py +++ b/cdp/client/models/nft_contract_options.py @@ -1,30 +1,35 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set from typing_extensions import Self - class NFTContractOptions(BaseModel): - """Options for NFT contract creation""" - + """ + Options for NFT contract creation + """ # noqa: E501 name: StrictStr = Field(description="The name of the NFT") symbol: StrictStr = Field(description="The symbol of the NFT") - __properties: ClassVar[list[str]] = ["name", "symbol"] + base_uri: StrictStr = Field(description="The base URI for the NFT metadata") + __properties: ClassVar[List[str]] = ["name", "symbol", "base_uri"] model_config = ConfigDict( populate_by_name=True, @@ -32,6 +37,7 @@ class NFTContractOptions(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -42,11 +48,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of NFTContractOptions from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -56,7 +62,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -66,7 +73,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of NFTContractOptions from a dict""" if obj is None: return None @@ -74,5 +81,11 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({"name": obj.get("name"), "symbol": obj.get("symbol")}) + _obj = cls.model_validate({ + "name": obj.get("name"), + "symbol": obj.get("symbol"), + "base_uri": obj.get("base_uri") + }) return _obj + + diff --git a/cdp/client/models/payload_signature.py b/cdp/client/models/payload_signature.py index 34764b5..a1c9880 100644 --- a/cdp/client/models/payload_signature.py +++ b/cdp/client/models/payload_signature.py @@ -1,48 +1,43 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set from typing_extensions import Self - class PayloadSignature(BaseModel): - """A payload signed by an address.""" - + """ + A payload signed by an address. + """ # noqa: E501 payload_signature_id: StrictStr = Field(description="The ID of the payload signature.") wallet_id: StrictStr = Field(description="The ID of the wallet that owns the address.") address_id: StrictStr = Field(description="The onchain address of the signer.") - unsigned_payload: StrictStr = Field( - description="The unsigned payload. This is the payload that needs to be signed by the signer address." - ) - signature: StrictStr | None = Field(default=None, description="The signature of the payload.") + unsigned_payload: StrictStr = Field(description="The unsigned payload. This is the payload that needs to be signed by the signer address.") + signature: Optional[StrictStr] = Field(default=None, description="The signature of the payload.") status: StrictStr = Field(description="The status of the payload signature.") - __properties: ClassVar[list[str]] = [ - "payload_signature_id", - "wallet_id", - "address_id", - "unsigned_payload", - "signature", - "status", - ] - - @field_validator("status") + __properties: ClassVar[List[str]] = ["payload_signature_id", "wallet_id", "address_id", "unsigned_payload", "signature", "status"] + + @field_validator('status') def status_validate_enum(cls, value): """Validates the enum""" - if value not in set(["pending", "signed", "failed"]): + if value not in set(['pending', 'signed', 'failed']): raise ValueError("must be one of enum values ('pending', 'signed', 'failed')") return value @@ -52,6 +47,7 @@ def status_validate_enum(cls, value): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -62,11 +58,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of PayloadSignature from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -76,7 +72,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -86,7 +83,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of PayloadSignature from a dict""" if obj is None: return None @@ -94,14 +91,14 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "payload_signature_id": obj.get("payload_signature_id"), - "wallet_id": obj.get("wallet_id"), - "address_id": obj.get("address_id"), - "unsigned_payload": obj.get("unsigned_payload"), - "signature": obj.get("signature"), - "status": obj.get("status"), - } - ) + _obj = cls.model_validate({ + "payload_signature_id": obj.get("payload_signature_id"), + "wallet_id": obj.get("wallet_id"), + "address_id": obj.get("address_id"), + "unsigned_payload": obj.get("unsigned_payload"), + "signature": obj.get("signature"), + "status": obj.get("status") + }) return _obj + + diff --git a/cdp/client/models/payload_signature_list.py b/cdp/client/models/payload_signature_list.py index 260cdaa..e9a50d1 100644 --- a/cdp/client/models/payload_signature_list.py +++ b/cdp/client/models/payload_signature_list.py @@ -1,38 +1,37 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.payload_signature import PayloadSignature - +from typing import Optional, Set +from typing_extensions import Self class PayloadSignatureList(BaseModel): - """ """ - - data: list[PayloadSignature] - has_more: StrictBool = Field( - description="True if this list has another page of items after this one that can be fetched." - ) + """ + + """ # noqa: E501 + data: List[PayloadSignature] + has_more: StrictBool = Field(description="True if this list has another page of items after this one that can be fetched.") next_page: StrictStr = Field(description="The page token to be used to fetch the next page.") - total_count: StrictInt = Field( - description="The total number of payload signatures for the address." - ) - __properties: ClassVar[list[str]] = ["data", "has_more", "next_page", "total_count"] + total_count: StrictInt = Field(description="The total number of payload signatures for the address.") + __properties: ClassVar[List[str]] = ["data", "has_more", "next_page", "total_count"] model_config = ConfigDict( populate_by_name=True, @@ -40,6 +39,7 @@ class PayloadSignatureList(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -50,11 +50,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of PayloadSignatureList from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -64,7 +64,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -77,11 +78,11 @@ def to_dict(self) -> dict[str, Any]: for _item_data in self.data: if _item_data: _items.append(_item_data.to_dict()) - _dict["data"] = _items + _dict['data'] = _items return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of PayloadSignatureList from a dict""" if obj is None: return None @@ -89,14 +90,12 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "data": [PayloadSignature.from_dict(_item) for _item in obj["data"]] - if obj.get("data") is not None - else None, - "has_more": obj.get("has_more"), - "next_page": obj.get("next_page"), - "total_count": obj.get("total_count"), - } - ) + _obj = cls.model_validate({ + "data": [PayloadSignature.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None, + "has_more": obj.get("has_more"), + "next_page": obj.get("next_page"), + "total_count": obj.get("total_count") + }) return _obj + + diff --git a/cdp/client/models/seed_creation_event.py b/cdp/client/models/seed_creation_event.py index cf79f64..6b47e39 100644 --- a/cdp/client/models/seed_creation_event.py +++ b/cdp/client/models/seed_creation_event.py @@ -1,32 +1,34 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set from typing_extensions import Self - class SeedCreationEvent(BaseModel): - """An event representing a seed creation.""" - - wallet_id: StrictStr = Field( - description="The ID of the wallet that the server-signer should create the seed for" - ) + """ + An event representing a seed creation. + """ # noqa: E501 + wallet_id: StrictStr = Field(description="The ID of the wallet that the server-signer should create the seed for") wallet_user_id: StrictStr = Field(description="The ID of the user that the wallet belongs to") - __properties: ClassVar[list[str]] = ["wallet_id", "wallet_user_id"] + __properties: ClassVar[List[str]] = ["wallet_id", "wallet_user_id"] model_config = ConfigDict( populate_by_name=True, @@ -34,6 +36,7 @@ class SeedCreationEvent(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -44,11 +47,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of SeedCreationEvent from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -58,7 +61,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -68,7 +72,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of SeedCreationEvent from a dict""" if obj is None: return None @@ -76,7 +80,10 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - {"wallet_id": obj.get("wallet_id"), "wallet_user_id": obj.get("wallet_user_id")} - ) + _obj = cls.model_validate({ + "wallet_id": obj.get("wallet_id"), + "wallet_user_id": obj.get("wallet_user_id") + }) return _obj + + diff --git a/cdp/client/models/seed_creation_event_result.py b/cdp/client/models/seed_creation_event_result.py index 497a8e0..1939bd6 100644 --- a/cdp/client/models/seed_creation_event_result.py +++ b/cdp/client/models/seed_creation_event_result.py @@ -1,41 +1,36 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set from typing_extensions import Self - class SeedCreationEventResult(BaseModel): - """The result to a SeedCreationEvent.""" - + """ + The result to a SeedCreationEvent. + """ # noqa: E501 wallet_id: StrictStr = Field(description="The ID of the wallet that the seed was created for") wallet_user_id: StrictStr = Field(description="The ID of the user that the wallet belongs to") - extended_public_key: StrictStr = Field( - description="The extended public key for the first master key derived from seed." - ) - seed_id: StrictStr = Field( - description="The ID of the seed in Server-Signer used to generate the extended public key." - ) - __properties: ClassVar[list[str]] = [ - "wallet_id", - "wallet_user_id", - "extended_public_key", - "seed_id", - ] + extended_public_key: StrictStr = Field(description="The extended public key for the first master key derived from seed.") + seed_id: StrictStr = Field(description="The ID of the seed in Server-Signer used to generate the extended public key.") + __properties: ClassVar[List[str]] = ["wallet_id", "wallet_user_id", "extended_public_key", "seed_id"] model_config = ConfigDict( populate_by_name=True, @@ -43,6 +38,7 @@ class SeedCreationEventResult(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -53,11 +49,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of SeedCreationEventResult from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -67,7 +63,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -77,7 +74,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of SeedCreationEventResult from a dict""" if obj is None: return None @@ -85,12 +82,12 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "wallet_id": obj.get("wallet_id"), - "wallet_user_id": obj.get("wallet_user_id"), - "extended_public_key": obj.get("extended_public_key"), - "seed_id": obj.get("seed_id"), - } - ) + _obj = cls.model_validate({ + "wallet_id": obj.get("wallet_id"), + "wallet_user_id": obj.get("wallet_user_id"), + "extended_public_key": obj.get("extended_public_key"), + "seed_id": obj.get("seed_id") + }) return _obj + + diff --git a/cdp/client/models/server_signer.py b/cdp/client/models/server_signer.py index bbdcbb8..ef9ce70 100644 --- a/cdp/client/models/server_signer.py +++ b/cdp/client/models/server_signer.py @@ -1,33 +1,35 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set from typing_extensions import Self - class ServerSigner(BaseModel): - """A Server-Signer assigned to sign transactions in a wallet.""" - + """ + A Server-Signer assigned to sign transactions in a wallet. + """ # noqa: E501 server_signer_id: StrictStr = Field(description="The ID of the server-signer") - wallets: list[StrictStr] | None = Field( - default=None, description="The IDs of the wallets that the server-signer can sign for" - ) + wallets: Optional[List[StrictStr]] = Field(default=None, description="The IDs of the wallets that the server-signer can sign for") is_mpc: StrictBool = Field(description="Whether the Server-Signer uses MPC.") - __properties: ClassVar[list[str]] = ["server_signer_id", "wallets", "is_mpc"] + __properties: ClassVar[List[str]] = ["server_signer_id", "wallets", "is_mpc"] model_config = ConfigDict( populate_by_name=True, @@ -35,6 +37,7 @@ class ServerSigner(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -45,11 +48,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ServerSigner from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -59,7 +62,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -69,7 +73,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ServerSigner from a dict""" if obj is None: return None @@ -77,11 +81,11 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "server_signer_id": obj.get("server_signer_id"), - "wallets": obj.get("wallets"), - "is_mpc": obj.get("is_mpc"), - } - ) + _obj = cls.model_validate({ + "server_signer_id": obj.get("server_signer_id"), + "wallets": obj.get("wallets"), + "is_mpc": obj.get("is_mpc") + }) return _obj + + diff --git a/cdp/client/models/server_signer_event.py b/cdp/client/models/server_signer_event.py index cedd991..a347b27 100644 --- a/cdp/client/models/server_signer_event.py +++ b/cdp/client/models/server_signer_event.py @@ -1,34 +1,35 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.server_signer_event_event import ServerSignerEventEvent - +from typing import Optional, Set +from typing_extensions import Self class ServerSignerEvent(BaseModel): - """An event that is waiting to be processed by a Server-Signer.""" - - server_signer_id: StrictStr = Field( - description="The ID of the server-signer that the event is for" - ) + """ + An event that is waiting to be processed by a Server-Signer. + """ # noqa: E501 + server_signer_id: StrictStr = Field(description="The ID of the server-signer that the event is for") event: ServerSignerEventEvent - __properties: ClassVar[list[str]] = ["server_signer_id", "event"] + __properties: ClassVar[List[str]] = ["server_signer_id", "event"] model_config = ConfigDict( populate_by_name=True, @@ -36,6 +37,7 @@ class ServerSignerEvent(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -46,11 +48,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ServerSignerEvent from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -60,7 +62,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -69,11 +72,11 @@ def to_dict(self) -> dict[str, Any]: ) # override the default output from pydantic by calling `to_dict()` of event if self.event: - _dict["event"] = self.event.to_dict() + _dict['event'] = self.event.to_dict() return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ServerSignerEvent from a dict""" if obj is None: return None @@ -81,12 +84,10 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "server_signer_id": obj.get("server_signer_id"), - "event": ServerSignerEventEvent.from_dict(obj["event"]) - if obj.get("event") is not None - else None, - } - ) + _obj = cls.model_validate({ + "server_signer_id": obj.get("server_signer_id"), + "event": ServerSignerEventEvent.from_dict(obj["event"]) if obj.get("event") is not None else None + }) return _obj + + diff --git a/cdp/client/models/server_signer_event_event.py b/cdp/client/models/server_signer_event_event.py index 9f22102..17908e0 100644 --- a/cdp/client/models/server_signer_event_event.py +++ b/cdp/client/models/server_signer_event_event.py @@ -1,58 +1,58 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import json import pprint -from typing import Any - -from pydantic import BaseModel, ConfigDict, ValidationError, field_validator -from typing_extensions import Self - +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional from cdp.client.models.seed_creation_event import SeedCreationEvent from cdp.client.models.signature_creation_event import SignatureCreationEvent +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self SERVERSIGNEREVENTEVENT_ONE_OF_SCHEMAS = ["SeedCreationEvent", "SignatureCreationEvent"] - class ServerSignerEventEvent(BaseModel): - """ServerSignerEventEvent""" - + """ + ServerSignerEventEvent + """ # data type: SeedCreationEvent - oneof_schema_1_validator: SeedCreationEvent | None = None + oneof_schema_1_validator: Optional[SeedCreationEvent] = None # data type: SignatureCreationEvent - oneof_schema_2_validator: SignatureCreationEvent | None = None - actual_instance: SeedCreationEvent | SignatureCreationEvent | None = None - one_of_schemas: set[str] = {"SeedCreationEvent", "SignatureCreationEvent"} + oneof_schema_2_validator: Optional[SignatureCreationEvent] = None + actual_instance: Optional[Union[SeedCreationEvent, SignatureCreationEvent]] = None + one_of_schemas: Set[str] = { "SeedCreationEvent", "SignatureCreationEvent" } model_config = ConfigDict( validate_assignment=True, protected_namespaces=(), ) + def __init__(self, *args, **kwargs) -> None: if args: if len(args) > 1: - raise ValueError( - "If a position argument is used, only 1 is allowed to set `actual_instance`" - ) + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") if kwargs: - raise ValueError( - "If a position argument is used, keyword arguments cannot be used." - ) + raise ValueError("If a position argument is used, keyword arguments cannot be used.") super().__init__(actual_instance=args[0]) else: super().__init__(**kwargs) - @field_validator("actual_instance") + @field_validator('actual_instance') def actual_instance_must_validate_oneof(cls, v): instance = ServerSignerEventEvent.model_construct() error_messages = [] @@ -69,21 +69,15 @@ def actual_instance_must_validate_oneof(cls, v): match += 1 if match > 1: # more than 1 match - raise ValueError( - "Multiple matches found when setting `actual_instance` in ServerSignerEventEvent with oneOf schemas: SeedCreationEvent, SignatureCreationEvent. Details: " - + ", ".join(error_messages) - ) + raise ValueError("Multiple matches found when setting `actual_instance` in ServerSignerEventEvent with oneOf schemas: SeedCreationEvent, SignatureCreationEvent. Details: " + ", ".join(error_messages)) elif match == 0: # no match - raise ValueError( - "No match found when setting `actual_instance` in ServerSignerEventEvent with oneOf schemas: SeedCreationEvent, SignatureCreationEvent. Details: " - + ", ".join(error_messages) - ) + raise ValueError("No match found when setting `actual_instance` in ServerSignerEventEvent with oneOf schemas: SeedCreationEvent, SignatureCreationEvent. Details: " + ", ".join(error_messages)) else: return v @classmethod - def from_dict(cls, obj: str | dict[str, Any]) -> Self: + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: return cls.from_json(json.dumps(obj)) @classmethod @@ -108,16 +102,10 @@ def from_json(cls, json_str: str) -> Self: if match > 1: # more than 1 match - raise ValueError( - "Multiple matches found when deserializing the JSON string into ServerSignerEventEvent with oneOf schemas: SeedCreationEvent, SignatureCreationEvent. Details: " - + ", ".join(error_messages) - ) + raise ValueError("Multiple matches found when deserializing the JSON string into ServerSignerEventEvent with oneOf schemas: SeedCreationEvent, SignatureCreationEvent. Details: " + ", ".join(error_messages)) elif match == 0: # no match - raise ValueError( - "No match found when deserializing the JSON string into ServerSignerEventEvent with oneOf schemas: SeedCreationEvent, SignatureCreationEvent. Details: " - + ", ".join(error_messages) - ) + raise ValueError("No match found when deserializing the JSON string into ServerSignerEventEvent with oneOf schemas: SeedCreationEvent, SignatureCreationEvent. Details: " + ", ".join(error_messages)) else: return instance @@ -131,7 +119,7 @@ def to_json(self) -> str: else: return json.dumps(self.actual_instance) - def to_dict(self) -> dict[str, Any] | SeedCreationEvent | SignatureCreationEvent | None: + def to_dict(self) -> Optional[Union[Dict[str, Any], SeedCreationEvent, SignatureCreationEvent]]: """Returns the dict representation of the actual instance""" if self.actual_instance is None: return None @@ -145,3 +133,5 @@ def to_dict(self) -> dict[str, Any] | SeedCreationEvent | SignatureCreationEvent def to_str(self) -> str: """Returns the string representation of the actual instance""" return pprint.pformat(self.model_dump()) + + diff --git a/cdp/client/models/server_signer_event_list.py b/cdp/client/models/server_signer_event_list.py index e076686..b963b3f 100644 --- a/cdp/client/models/server_signer_event_list.py +++ b/cdp/client/models/server_signer_event_list.py @@ -1,36 +1,37 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.server_signer_event import ServerSignerEvent - +from typing import Optional, Set +from typing_extensions import Self class ServerSignerEventList(BaseModel): - """ """ - - data: list[ServerSignerEvent] - has_more: StrictBool = Field( - description="True if this list has another page of items after this one that can be fetched." - ) + """ + + """ # noqa: E501 + data: List[ServerSignerEvent] + has_more: StrictBool = Field(description="True if this list has another page of items after this one that can be fetched.") next_page: StrictStr = Field(description="The page token to be used to fetch the next page.") total_count: StrictInt = Field(description="The total number of events for the server signer.") - __properties: ClassVar[list[str]] = ["data", "has_more", "next_page", "total_count"] + __properties: ClassVar[List[str]] = ["data", "has_more", "next_page", "total_count"] model_config = ConfigDict( populate_by_name=True, @@ -38,6 +39,7 @@ class ServerSignerEventList(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -48,11 +50,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ServerSignerEventList from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -62,7 +64,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -75,11 +78,11 @@ def to_dict(self) -> dict[str, Any]: for _item_data in self.data: if _item_data: _items.append(_item_data.to_dict()) - _dict["data"] = _items + _dict['data'] = _items return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ServerSignerEventList from a dict""" if obj is None: return None @@ -87,14 +90,12 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "data": [ServerSignerEvent.from_dict(_item) for _item in obj["data"]] - if obj.get("data") is not None - else None, - "has_more": obj.get("has_more"), - "next_page": obj.get("next_page"), - "total_count": obj.get("total_count"), - } - ) + _obj = cls.model_validate({ + "data": [ServerSignerEvent.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None, + "has_more": obj.get("has_more"), + "next_page": obj.get("next_page"), + "total_count": obj.get("total_count") + }) return _obj + + diff --git a/cdp/client/models/server_signer_list.py b/cdp/client/models/server_signer_list.py index aa53db2..cccd8fc 100644 --- a/cdp/client/models/server_signer_list.py +++ b/cdp/client/models/server_signer_list.py @@ -1,38 +1,37 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.server_signer import ServerSigner - +from typing import Optional, Set +from typing_extensions import Self class ServerSignerList(BaseModel): - """ """ - - data: list[ServerSigner] - has_more: StrictBool = Field( - description="True if this list has another page of items after this one that can be fetched." - ) + """ + + """ # noqa: E501 + data: List[ServerSigner] + has_more: StrictBool = Field(description="True if this list has another page of items after this one that can be fetched.") next_page: StrictStr = Field(description="The page token to be used to fetch the next page.") - total_count: StrictInt = Field( - description="The total number of server-signers for the project." - ) - __properties: ClassVar[list[str]] = ["data", "has_more", "next_page", "total_count"] + total_count: StrictInt = Field(description="The total number of server-signers for the project.") + __properties: ClassVar[List[str]] = ["data", "has_more", "next_page", "total_count"] model_config = ConfigDict( populate_by_name=True, @@ -40,6 +39,7 @@ class ServerSignerList(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -50,11 +50,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ServerSignerList from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -64,7 +64,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -77,11 +78,11 @@ def to_dict(self) -> dict[str, Any]: for _item_data in self.data: if _item_data: _items.append(_item_data.to_dict()) - _dict["data"] = _items + _dict['data'] = _items return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ServerSignerList from a dict""" if obj is None: return None @@ -89,14 +90,12 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "data": [ServerSigner.from_dict(_item) for _item in obj["data"]] - if obj.get("data") is not None - else None, - "has_more": obj.get("has_more"), - "next_page": obj.get("next_page"), - "total_count": obj.get("total_count"), - } - ) + _obj = cls.model_validate({ + "data": [ServerSigner.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None, + "has_more": obj.get("has_more"), + "next_page": obj.get("next_page"), + "total_count": obj.get("total_count") + }) return _obj + + diff --git a/cdp/client/models/signature_creation_event.py b/cdp/client/models/signature_creation_event.py index afeb0ac..af1aecc 100644 --- a/cdp/client/models/signature_creation_event.py +++ b/cdp/client/models/signature_creation_event.py @@ -1,53 +1,41 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.transaction_type import TransactionType - +from typing import Optional, Set +from typing_extensions import Self class SignatureCreationEvent(BaseModel): - """An event representing a signature creation.""" - - seed_id: StrictStr = Field( - description="The ID of the seed that the server-signer should create the signature for" - ) + """ + An event representing a signature creation. + """ # noqa: E501 + seed_id: StrictStr = Field(description="The ID of the seed that the server-signer should create the signature for") wallet_id: StrictStr = Field(description="The ID of the wallet the signature is for") wallet_user_id: StrictStr = Field(description="The ID of the user that the wallet belongs to") address_id: StrictStr = Field(description="The ID of the address the transfer belongs to") - address_index: StrictInt = Field( - description="The index of the address that the server-signer should sign with" - ) + address_index: StrictInt = Field(description="The index of the address that the server-signer should sign with") signing_payload: StrictStr = Field(description="The payload that the server-signer should sign") transaction_type: TransactionType - transaction_id: StrictStr = Field( - description="The ID of the transaction that the server-signer should sign" - ) - __properties: ClassVar[list[str]] = [ - "seed_id", - "wallet_id", - "wallet_user_id", - "address_id", - "address_index", - "signing_payload", - "transaction_type", - "transaction_id", - ] + transaction_id: StrictStr = Field(description="The ID of the transaction that the server-signer should sign") + __properties: ClassVar[List[str]] = ["seed_id", "wallet_id", "wallet_user_id", "address_id", "address_index", "signing_payload", "transaction_type", "transaction_id"] model_config = ConfigDict( populate_by_name=True, @@ -55,6 +43,7 @@ class SignatureCreationEvent(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -65,11 +54,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of SignatureCreationEvent from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -79,7 +68,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -89,7 +79,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of SignatureCreationEvent from a dict""" if obj is None: return None @@ -97,16 +87,16 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "seed_id": obj.get("seed_id"), - "wallet_id": obj.get("wallet_id"), - "wallet_user_id": obj.get("wallet_user_id"), - "address_id": obj.get("address_id"), - "address_index": obj.get("address_index"), - "signing_payload": obj.get("signing_payload"), - "transaction_type": obj.get("transaction_type"), - "transaction_id": obj.get("transaction_id"), - } - ) + _obj = cls.model_validate({ + "seed_id": obj.get("seed_id"), + "wallet_id": obj.get("wallet_id"), + "wallet_user_id": obj.get("wallet_user_id"), + "address_id": obj.get("address_id"), + "address_index": obj.get("address_index"), + "signing_payload": obj.get("signing_payload"), + "transaction_type": obj.get("transaction_type"), + "transaction_id": obj.get("transaction_id") + }) return _obj + + diff --git a/cdp/client/models/signature_creation_event_result.py b/cdp/client/models/signature_creation_event_result.py index ccd3678..2059017 100644 --- a/cdp/client/models/signature_creation_event_result.py +++ b/cdp/client/models/signature_creation_event_result.py @@ -1,45 +1,39 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.transaction_type import TransactionType - +from typing import Optional, Set +from typing_extensions import Self class SignatureCreationEventResult(BaseModel): - """The result to a SignatureCreationEvent.""" - + """ + The result to a SignatureCreationEvent. + """ # noqa: E501 wallet_id: StrictStr = Field(description="The ID of the wallet that the event was created for.") wallet_user_id: StrictStr = Field(description="The ID of the user that the wallet belongs to") address_id: StrictStr = Field(description="The ID of the address the transfer belongs to") transaction_type: TransactionType - transaction_id: StrictStr = Field( - description="The ID of the transaction that the Server-Signer has signed for" - ) + transaction_id: StrictStr = Field(description="The ID of the transaction that the Server-Signer has signed for") signature: StrictStr = Field(description="The signature created by the server-signer.") - __properties: ClassVar[list[str]] = [ - "wallet_id", - "wallet_user_id", - "address_id", - "transaction_type", - "transaction_id", - "signature", - ] + __properties: ClassVar[List[str]] = ["wallet_id", "wallet_user_id", "address_id", "transaction_type", "transaction_id", "signature"] model_config = ConfigDict( populate_by_name=True, @@ -47,6 +41,7 @@ class SignatureCreationEventResult(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -57,11 +52,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of SignatureCreationEventResult from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -71,7 +66,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -81,7 +77,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of SignatureCreationEventResult from a dict""" if obj is None: return None @@ -89,14 +85,14 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "wallet_id": obj.get("wallet_id"), - "wallet_user_id": obj.get("wallet_user_id"), - "address_id": obj.get("address_id"), - "transaction_type": obj.get("transaction_type"), - "transaction_id": obj.get("transaction_id"), - "signature": obj.get("signature"), - } - ) + _obj = cls.model_validate({ + "wallet_id": obj.get("wallet_id"), + "wallet_user_id": obj.get("wallet_user_id"), + "address_id": obj.get("address_id"), + "transaction_type": obj.get("transaction_type"), + "transaction_id": obj.get("transaction_id"), + "signature": obj.get("signature") + }) return _obj + + diff --git a/cdp/client/models/signed_voluntary_exit_message_metadata.py b/cdp/client/models/signed_voluntary_exit_message_metadata.py index d0e9f43..69b0c4b 100644 --- a/cdp/client/models/signed_voluntary_exit_message_metadata.py +++ b/cdp/client/models/signed_voluntary_exit_message_metadata.py @@ -1,35 +1,35 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set from typing_extensions import Self - class SignedVoluntaryExitMessageMetadata(BaseModel): - """Signed voluntary exit message metadata to be provided to beacon chain to exit a validator.""" - - validator_pub_key: StrictStr = Field( - description="The public key of the validator associated with the exit message." - ) + """ + Signed voluntary exit message metadata to be provided to beacon chain to exit a validator. + """ # noqa: E501 + validator_pub_key: StrictStr = Field(description="The public key of the validator associated with the exit message.") fork: StrictStr = Field(description="The current fork version of the Ethereum beacon chain.") - signed_voluntary_exit: StrictStr = Field( - description="A base64 encoded version of a json string representing a voluntary exit message." - ) - __properties: ClassVar[list[str]] = ["validator_pub_key", "fork", "signed_voluntary_exit"] + signed_voluntary_exit: StrictStr = Field(description="A base64 encoded version of a json string representing a voluntary exit message.") + __properties: ClassVar[List[str]] = ["validator_pub_key", "fork", "signed_voluntary_exit"] model_config = ConfigDict( populate_by_name=True, @@ -37,6 +37,7 @@ class SignedVoluntaryExitMessageMetadata(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -47,11 +48,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of SignedVoluntaryExitMessageMetadata from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -61,7 +62,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -71,7 +73,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of SignedVoluntaryExitMessageMetadata from a dict""" if obj is None: return None @@ -79,11 +81,11 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "validator_pub_key": obj.get("validator_pub_key"), - "fork": obj.get("fork"), - "signed_voluntary_exit": obj.get("signed_voluntary_exit"), - } - ) + _obj = cls.model_validate({ + "validator_pub_key": obj.get("validator_pub_key"), + "fork": obj.get("fork"), + "signed_voluntary_exit": obj.get("signed_voluntary_exit") + }) return _obj + + diff --git a/cdp/client/models/smart_contract.py b/cdp/client/models/smart_contract.py index cf0bbd4..884ca0c 100644 --- a/cdp/client/models/smart_contract.py +++ b/cdp/client/models/smart_contract.py @@ -1,55 +1,44 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.smart_contract_options import SmartContractOptions from cdp.client.models.smart_contract_type import SmartContractType from cdp.client.models.transaction import Transaction - +from typing import Optional, Set +from typing_extensions import Self class SmartContract(BaseModel): - """Represents a smart contract on the blockchain""" - + """ + Represents a smart contract on the blockchain + """ # noqa: E501 smart_contract_id: StrictStr = Field(description="The unique identifier of the smart contract") network_id: StrictStr = Field(description="The name of the blockchain network") - wallet_id: StrictStr = Field( - description="The ID of the wallet that deployed the smart contract" - ) + wallet_id: StrictStr = Field(description="The ID of the wallet that deployed the smart contract") contract_address: StrictStr = Field(description="The EVM address of the smart contract") - deployer_address: StrictStr = Field( - description="The EVM address of the account that deployed the smart contract" - ) + deployer_address: StrictStr = Field(description="The EVM address of the account that deployed the smart contract") type: SmartContractType options: SmartContractOptions abi: StrictStr = Field(description="The JSON-encoded ABI of the contract") transaction: Transaction - __properties: ClassVar[list[str]] = [ - "smart_contract_id", - "network_id", - "wallet_id", - "contract_address", - "deployer_address", - "type", - "options", - "abi", - "transaction", - ] + __properties: ClassVar[List[str]] = ["smart_contract_id", "network_id", "wallet_id", "contract_address", "deployer_address", "type", "options", "abi", "transaction"] model_config = ConfigDict( populate_by_name=True, @@ -57,6 +46,7 @@ class SmartContract(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -67,11 +57,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of SmartContract from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -81,7 +71,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -90,14 +81,14 @@ def to_dict(self) -> dict[str, Any]: ) # override the default output from pydantic by calling `to_dict()` of options if self.options: - _dict["options"] = self.options.to_dict() + _dict['options'] = self.options.to_dict() # override the default output from pydantic by calling `to_dict()` of transaction if self.transaction: - _dict["transaction"] = self.transaction.to_dict() + _dict['transaction'] = self.transaction.to_dict() return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of SmartContract from a dict""" if obj is None: return None @@ -105,21 +96,17 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "smart_contract_id": obj.get("smart_contract_id"), - "network_id": obj.get("network_id"), - "wallet_id": obj.get("wallet_id"), - "contract_address": obj.get("contract_address"), - "deployer_address": obj.get("deployer_address"), - "type": obj.get("type"), - "options": SmartContractOptions.from_dict(obj["options"]) - if obj.get("options") is not None - else None, - "abi": obj.get("abi"), - "transaction": Transaction.from_dict(obj["transaction"]) - if obj.get("transaction") is not None - else None, - } - ) + _obj = cls.model_validate({ + "smart_contract_id": obj.get("smart_contract_id"), + "network_id": obj.get("network_id"), + "wallet_id": obj.get("wallet_id"), + "contract_address": obj.get("contract_address"), + "deployer_address": obj.get("deployer_address"), + "type": obj.get("type"), + "options": SmartContractOptions.from_dict(obj["options"]) if obj.get("options") is not None else None, + "abi": obj.get("abi"), + "transaction": Transaction.from_dict(obj["transaction"]) if obj.get("transaction") is not None else None + }) return _obj + + diff --git a/cdp/client/models/smart_contract_list.py b/cdp/client/models/smart_contract_list.py index 7e42b71..d99869e 100644 --- a/cdp/client/models/smart_contract_list.py +++ b/cdp/client/models/smart_contract_list.py @@ -1,35 +1,36 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.smart_contract import SmartContract - +from typing import Optional, Set +from typing_extensions import Self class SmartContractList(BaseModel): - """SmartContractList""" - - data: list[SmartContract] - has_more: StrictBool = Field( - description="True if this list has another page of items after this one that can be fetched." - ) + """ + SmartContractList + """ # noqa: E501 + data: List[SmartContract] + has_more: StrictBool = Field(description="True if this list has another page of items after this one that can be fetched.") next_page: StrictStr = Field(description="The page token to be used to fetch the next page.") - __properties: ClassVar[list[str]] = ["data", "has_more", "next_page"] + __properties: ClassVar[List[str]] = ["data", "has_more", "next_page"] model_config = ConfigDict( populate_by_name=True, @@ -37,6 +38,7 @@ class SmartContractList(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -47,11 +49,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of SmartContractList from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -61,7 +63,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -74,11 +77,11 @@ def to_dict(self) -> dict[str, Any]: for _item_data in self.data: if _item_data: _items.append(_item_data.to_dict()) - _dict["data"] = _items + _dict['data'] = _items return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of SmartContractList from a dict""" if obj is None: return None @@ -86,13 +89,11 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "data": [SmartContract.from_dict(_item) for _item in obj["data"]] - if obj.get("data") is not None - else None, - "has_more": obj.get("has_more"), - "next_page": obj.get("next_page"), - } - ) + _obj = cls.model_validate({ + "data": [SmartContract.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None, + "has_more": obj.get("has_more"), + "next_page": obj.get("next_page") + }) return _obj + + diff --git a/cdp/client/models/smart_contract_options.py b/cdp/client/models/smart_contract_options.py index 6da1d8e..caff948 100644 --- a/cdp/client/models/smart_contract_options.py +++ b/cdp/client/models/smart_contract_options.py @@ -1,58 +1,61 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import json import pprint -from typing import Any - -from pydantic import BaseModel, ConfigDict, ValidationError, field_validator -from typing_extensions import Self - +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from cdp.client.models.multi_token_contract_options import MultiTokenContractOptions from cdp.client.models.nft_contract_options import NFTContractOptions from cdp.client.models.token_contract_options import TokenContractOptions +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self -SMARTCONTRACTOPTIONS_ONE_OF_SCHEMAS = ["NFTContractOptions", "TokenContractOptions"] - +SMARTCONTRACTOPTIONS_ONE_OF_SCHEMAS = ["MultiTokenContractOptions", "NFTContractOptions", "TokenContractOptions"] class SmartContractOptions(BaseModel): - """Options for smart contract creation""" - + """ + Options for smart contract creation + """ # data type: TokenContractOptions - oneof_schema_1_validator: TokenContractOptions | None = None + oneof_schema_1_validator: Optional[TokenContractOptions] = None # data type: NFTContractOptions - oneof_schema_2_validator: NFTContractOptions | None = None - actual_instance: NFTContractOptions | TokenContractOptions | None = None - one_of_schemas: set[str] = {"NFTContractOptions", "TokenContractOptions"} + oneof_schema_2_validator: Optional[NFTContractOptions] = None + # data type: MultiTokenContractOptions + oneof_schema_3_validator: Optional[MultiTokenContractOptions] = None + actual_instance: Optional[Union[MultiTokenContractOptions, NFTContractOptions, TokenContractOptions]] = None + one_of_schemas: Set[str] = { "MultiTokenContractOptions", "NFTContractOptions", "TokenContractOptions" } model_config = ConfigDict( validate_assignment=True, protected_namespaces=(), ) + def __init__(self, *args, **kwargs) -> None: if args: if len(args) > 1: - raise ValueError( - "If a position argument is used, only 1 is allowed to set `actual_instance`" - ) + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") if kwargs: - raise ValueError( - "If a position argument is used, keyword arguments cannot be used." - ) + raise ValueError("If a position argument is used, keyword arguments cannot be used.") super().__init__(actual_instance=args[0]) else: super().__init__(**kwargs) - @field_validator("actual_instance") + @field_validator('actual_instance') def actual_instance_must_validate_oneof(cls, v): instance = SmartContractOptions.model_construct() error_messages = [] @@ -67,23 +70,22 @@ def actual_instance_must_validate_oneof(cls, v): error_messages.append(f"Error! Input type `{type(v)}` is not `NFTContractOptions`") else: match += 1 + # validate data type: MultiTokenContractOptions + if not isinstance(v, MultiTokenContractOptions): + error_messages.append(f"Error! Input type `{type(v)}` is not `MultiTokenContractOptions`") + else: + match += 1 if match > 1: # more than 1 match - raise ValueError( - "Multiple matches found when setting `actual_instance` in SmartContractOptions with oneOf schemas: NFTContractOptions, TokenContractOptions. Details: " - + ", ".join(error_messages) - ) + raise ValueError("Multiple matches found when setting `actual_instance` in SmartContractOptions with oneOf schemas: MultiTokenContractOptions, NFTContractOptions, TokenContractOptions. Details: " + ", ".join(error_messages)) elif match == 0: # no match - raise ValueError( - "No match found when setting `actual_instance` in SmartContractOptions with oneOf schemas: NFTContractOptions, TokenContractOptions. Details: " - + ", ".join(error_messages) - ) + raise ValueError("No match found when setting `actual_instance` in SmartContractOptions with oneOf schemas: MultiTokenContractOptions, NFTContractOptions, TokenContractOptions. Details: " + ", ".join(error_messages)) else: return v @classmethod - def from_dict(cls, obj: str | dict[str, Any]) -> Self: + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: return cls.from_json(json.dumps(obj)) @classmethod @@ -105,19 +107,19 @@ def from_json(cls, json_str: str) -> Self: match += 1 except (ValidationError, ValueError) as e: error_messages.append(str(e)) + # deserialize data into MultiTokenContractOptions + try: + instance.actual_instance = MultiTokenContractOptions.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) if match > 1: # more than 1 match - raise ValueError( - "Multiple matches found when deserializing the JSON string into SmartContractOptions with oneOf schemas: NFTContractOptions, TokenContractOptions. Details: " - + ", ".join(error_messages) - ) + raise ValueError("Multiple matches found when deserializing the JSON string into SmartContractOptions with oneOf schemas: MultiTokenContractOptions, NFTContractOptions, TokenContractOptions. Details: " + ", ".join(error_messages)) elif match == 0: # no match - raise ValueError( - "No match found when deserializing the JSON string into SmartContractOptions with oneOf schemas: NFTContractOptions, TokenContractOptions. Details: " - + ", ".join(error_messages) - ) + raise ValueError("No match found when deserializing the JSON string into SmartContractOptions with oneOf schemas: MultiTokenContractOptions, NFTContractOptions, TokenContractOptions. Details: " + ", ".join(error_messages)) else: return instance @@ -131,7 +133,7 @@ def to_json(self) -> str: else: return json.dumps(self.actual_instance) - def to_dict(self) -> dict[str, Any] | NFTContractOptions | TokenContractOptions | None: + def to_dict(self) -> Optional[Union[Dict[str, Any], MultiTokenContractOptions, NFTContractOptions, TokenContractOptions]]: """Returns the dict representation of the actual instance""" if self.actual_instance is None: return None @@ -145,3 +147,5 @@ def to_dict(self) -> dict[str, Any] | NFTContractOptions | TokenContractOptions def to_str(self) -> str: """Returns the string representation of the actual instance""" return pprint.pformat(self.model_dump()) + + diff --git a/cdp/client/models/smart_contract_type.py b/cdp/client/models/smart_contract_type.py index 7a815e3..7399f69 100644 --- a/cdp/client/models/smart_contract_type.py +++ b/cdp/client/models/smart_contract_type.py @@ -1,31 +1,38 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import json from enum import Enum - from typing_extensions import Self class SmartContractType(str, Enum): - """The type of the smart contract""" + """ + The type of the smart contract. + """ """ allowed enum values """ - ERC20 = "erc20" - ERC721 = "erc721" + ERC20 = 'erc20' + ERC721 = 'erc721' + ERC1155 = 'erc1155' @classmethod def from_json(cls, json_str: str) -> Self: """Create an instance of SmartContractType from a JSON string""" return cls(json.loads(json_str)) + + diff --git a/cdp/client/models/sponsored_send.py b/cdp/client/models/sponsored_send.py index adc397d..64af14a 100644 --- a/cdp/client/models/sponsored_send.py +++ b/cdp/client/models/sponsored_send.py @@ -1,60 +1,45 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set from typing_extensions import Self - class SponsoredSend(BaseModel): - """An onchain sponsored gasless send.""" - + """ + An onchain sponsored gasless send. + """ # noqa: E501 to_address_id: StrictStr = Field(description="The onchain address of the recipient") raw_typed_data: StrictStr = Field(description="The raw typed data for the sponsored send") - typed_data_hash: StrictStr = Field( - description="The typed data hash for the sponsored send. This is the typed data hash that needs to be signed by the sender." - ) - signature: StrictStr | None = Field( - default=None, description="The signed hash of the sponsored send typed data." - ) - transaction_hash: StrictStr | None = Field( - default=None, description="The hash of the onchain sponsored send transaction" - ) - transaction_link: StrictStr | None = Field( - default=None, - description="The link to view the transaction on a block explorer. This is optional and may not be present for all transactions.", - ) + typed_data_hash: StrictStr = Field(description="The typed data hash for the sponsored send. This is the typed data hash that needs to be signed by the sender.") + signature: Optional[StrictStr] = Field(default=None, description="The signed hash of the sponsored send typed data.") + transaction_hash: Optional[StrictStr] = Field(default=None, description="The hash of the onchain sponsored send transaction") + transaction_link: Optional[StrictStr] = Field(default=None, description="The link to view the transaction on a block explorer. This is optional and may not be present for all transactions.") status: StrictStr = Field(description="The status of the sponsored send") - __properties: ClassVar[list[str]] = [ - "to_address_id", - "raw_typed_data", - "typed_data_hash", - "signature", - "transaction_hash", - "transaction_link", - "status", - ] - - @field_validator("status") + __properties: ClassVar[List[str]] = ["to_address_id", "raw_typed_data", "typed_data_hash", "signature", "transaction_hash", "transaction_link", "status"] + + @field_validator('status') def status_validate_enum(cls, value): """Validates the enum""" - if value not in set(["pending", "signed", "submitted", "complete", "failed"]): - raise ValueError( - "must be one of enum values ('pending', 'signed', 'submitted', 'complete', 'failed')" - ) + if value not in set(['pending', 'signed', 'submitted', 'complete', 'failed']): + raise ValueError("must be one of enum values ('pending', 'signed', 'submitted', 'complete', 'failed')") return value model_config = ConfigDict( @@ -63,6 +48,7 @@ def status_validate_enum(cls, value): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -73,11 +59,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of SponsoredSend from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -87,7 +73,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -97,7 +84,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of SponsoredSend from a dict""" if obj is None: return None @@ -105,15 +92,15 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "to_address_id": obj.get("to_address_id"), - "raw_typed_data": obj.get("raw_typed_data"), - "typed_data_hash": obj.get("typed_data_hash"), - "signature": obj.get("signature"), - "transaction_hash": obj.get("transaction_hash"), - "transaction_link": obj.get("transaction_link"), - "status": obj.get("status"), - } - ) + _obj = cls.model_validate({ + "to_address_id": obj.get("to_address_id"), + "raw_typed_data": obj.get("raw_typed_data"), + "typed_data_hash": obj.get("typed_data_hash"), + "signature": obj.get("signature"), + "transaction_hash": obj.get("transaction_hash"), + "transaction_link": obj.get("transaction_link"), + "status": obj.get("status") + }) return _obj + + diff --git a/cdp/client/models/staking_balance.py b/cdp/client/models/staking_balance.py index d763dce..25556bc 100644 --- a/cdp/client/models/staking_balance.py +++ b/cdp/client/models/staking_balance.py @@ -1,46 +1,39 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from datetime import datetime -from typing import Any, ClassVar +import json +from datetime import datetime from pydantic import BaseModel, ConfigDict, Field, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.balance import Balance - +from typing import Optional, Set +from typing_extensions import Self class StakingBalance(BaseModel): - """The staking balances for an address.""" - - address: StrictStr = Field( - description="The onchain address for which the staking balances are being fetched." - ) - var_date: datetime = Field( - description="The timestamp of the staking balance in UTC.", alias="date" - ) + """ + The staking balances for an address. + """ # noqa: E501 + address: StrictStr = Field(description="The onchain address for which the staking balances are being fetched.") + var_date: datetime = Field(description="The timestamp of the staking balance in UTC.", alias="date") bonded_stake: Balance unbonded_balance: Balance participant_type: StrictStr = Field(description="The type of staking participation.") - __properties: ClassVar[list[str]] = [ - "address", - "date", - "bonded_stake", - "unbonded_balance", - "participant_type", - ] + __properties: ClassVar[List[str]] = ["address", "date", "bonded_stake", "unbonded_balance", "participant_type"] model_config = ConfigDict( populate_by_name=True, @@ -48,6 +41,7 @@ class StakingBalance(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -58,11 +52,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of StakingBalance from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -72,7 +66,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -81,14 +76,14 @@ def to_dict(self) -> dict[str, Any]: ) # override the default output from pydantic by calling `to_dict()` of bonded_stake if self.bonded_stake: - _dict["bonded_stake"] = self.bonded_stake.to_dict() + _dict['bonded_stake'] = self.bonded_stake.to_dict() # override the default output from pydantic by calling `to_dict()` of unbonded_balance if self.unbonded_balance: - _dict["unbonded_balance"] = self.unbonded_balance.to_dict() + _dict['unbonded_balance'] = self.unbonded_balance.to_dict() return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of StakingBalance from a dict""" if obj is None: return None @@ -96,17 +91,13 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "address": obj.get("address"), - "date": obj.get("date"), - "bonded_stake": Balance.from_dict(obj["bonded_stake"]) - if obj.get("bonded_stake") is not None - else None, - "unbonded_balance": Balance.from_dict(obj["unbonded_balance"]) - if obj.get("unbonded_balance") is not None - else None, - "participant_type": obj.get("participant_type"), - } - ) + _obj = cls.model_validate({ + "address": obj.get("address"), + "date": obj.get("date"), + "bonded_stake": Balance.from_dict(obj["bonded_stake"]) if obj.get("bonded_stake") is not None else None, + "unbonded_balance": Balance.from_dict(obj["unbonded_balance"]) if obj.get("unbonded_balance") is not None else None, + "participant_type": obj.get("participant_type") + }) return _obj + + diff --git a/cdp/client/models/staking_context.py b/cdp/client/models/staking_context.py index e7ccd9b..8fca6b5 100644 --- a/cdp/client/models/staking_context.py +++ b/cdp/client/models/staking_context.py @@ -1,31 +1,34 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.staking_context_context import StakingContextContext - +from typing import Optional, Set +from typing_extensions import Self class StakingContext(BaseModel): - """Context needed to perform a staking operation""" - + """ + Context needed to perform a staking operation + """ # noqa: E501 context: StakingContextContext - __properties: ClassVar[list[str]] = ["context"] + __properties: ClassVar[List[str]] = ["context"] model_config = ConfigDict( populate_by_name=True, @@ -33,6 +36,7 @@ class StakingContext(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -43,11 +47,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of StakingContext from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -57,7 +61,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -66,11 +71,11 @@ def to_dict(self) -> dict[str, Any]: ) # override the default output from pydantic by calling `to_dict()` of context if self.context: - _dict["context"] = self.context.to_dict() + _dict['context'] = self.context.to_dict() return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of StakingContext from a dict""" if obj is None: return None @@ -78,11 +83,9 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "context": StakingContextContext.from_dict(obj["context"]) - if obj.get("context") is not None - else None - } - ) + _obj = cls.model_validate({ + "context": StakingContextContext.from_dict(obj["context"]) if obj.get("context") is not None else None + }) return _obj + + diff --git a/cdp/client/models/staking_context_context.py b/cdp/client/models/staking_context_context.py index 07d1f34..239cd8b 100644 --- a/cdp/client/models/staking_context_context.py +++ b/cdp/client/models/staking_context_context.py @@ -1,37 +1,36 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.balance import Balance - +from typing import Optional, Set +from typing_extensions import Self class StakingContextContext(BaseModel): - """StakingContextContext""" - + """ + StakingContextContext + """ # noqa: E501 stakeable_balance: Balance unstakeable_balance: Balance claimable_balance: Balance - __properties: ClassVar[list[str]] = [ - "stakeable_balance", - "unstakeable_balance", - "claimable_balance", - ] + __properties: ClassVar[List[str]] = ["stakeable_balance", "unstakeable_balance", "claimable_balance"] model_config = ConfigDict( populate_by_name=True, @@ -39,6 +38,7 @@ class StakingContextContext(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -49,11 +49,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of StakingContextContext from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -63,7 +63,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -72,17 +73,17 @@ def to_dict(self) -> dict[str, Any]: ) # override the default output from pydantic by calling `to_dict()` of stakeable_balance if self.stakeable_balance: - _dict["stakeable_balance"] = self.stakeable_balance.to_dict() + _dict['stakeable_balance'] = self.stakeable_balance.to_dict() # override the default output from pydantic by calling `to_dict()` of unstakeable_balance if self.unstakeable_balance: - _dict["unstakeable_balance"] = self.unstakeable_balance.to_dict() + _dict['unstakeable_balance'] = self.unstakeable_balance.to_dict() # override the default output from pydantic by calling `to_dict()` of claimable_balance if self.claimable_balance: - _dict["claimable_balance"] = self.claimable_balance.to_dict() + _dict['claimable_balance'] = self.claimable_balance.to_dict() return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of StakingContextContext from a dict""" if obj is None: return None @@ -90,17 +91,11 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "stakeable_balance": Balance.from_dict(obj["stakeable_balance"]) - if obj.get("stakeable_balance") is not None - else None, - "unstakeable_balance": Balance.from_dict(obj["unstakeable_balance"]) - if obj.get("unstakeable_balance") is not None - else None, - "claimable_balance": Balance.from_dict(obj["claimable_balance"]) - if obj.get("claimable_balance") is not None - else None, - } - ) + _obj = cls.model_validate({ + "stakeable_balance": Balance.from_dict(obj["stakeable_balance"]) if obj.get("stakeable_balance") is not None else None, + "unstakeable_balance": Balance.from_dict(obj["unstakeable_balance"]) if obj.get("unstakeable_balance") is not None else None, + "claimable_balance": Balance.from_dict(obj["claimable_balance"]) if obj.get("claimable_balance") is not None else None + }) return _obj + + diff --git a/cdp/client/models/staking_operation.py b/cdp/client/models/staking_operation.py index 675c1c3..da71bec 100644 --- a/cdp/client/models/staking_operation.py +++ b/cdp/client/models/staking_operation.py @@ -1,60 +1,47 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List, Optional from cdp.client.models.staking_operation_metadata import StakingOperationMetadata from cdp.client.models.transaction import Transaction - +from typing import Optional, Set +from typing_extensions import Self class StakingOperation(BaseModel): - """A list of onchain transactions to help realize a staking action.""" - + """ + A list of onchain transactions to help realize a staking action. + """ # noqa: E501 id: StrictStr = Field(description="The unique ID of the staking operation.") - wallet_id: StrictStr | None = Field( - default=None, description="The ID of the wallet that owns the address." - ) + wallet_id: Optional[StrictStr] = Field(default=None, description="The ID of the wallet that owns the address.") network_id: StrictStr = Field(description="The ID of the blockchain network.") - address_id: StrictStr = Field( - description="The onchain address orchestrating the staking operation." - ) + address_id: StrictStr = Field(description="The onchain address orchestrating the staking operation.") status: StrictStr = Field(description="The status of the staking operation.") - transactions: list[Transaction] = Field( - description="The transaction(s) that will execute the staking operation onchain." - ) - metadata: StakingOperationMetadata | None = None - __properties: ClassVar[list[str]] = [ - "id", - "wallet_id", - "network_id", - "address_id", - "status", - "transactions", - "metadata", - ] - - @field_validator("status") + transactions: List[Transaction] = Field(description="The transaction(s) that will execute the staking operation onchain.") + metadata: Optional[StakingOperationMetadata] = None + __properties: ClassVar[List[str]] = ["id", "wallet_id", "network_id", "address_id", "status", "transactions", "metadata"] + + @field_validator('status') def status_validate_enum(cls, value): """Validates the enum""" - if value not in set(["initialized", "complete", "failed", "unspecified"]): - raise ValueError( - "must be one of enum values ('initialized', 'complete', 'failed', 'unspecified')" - ) + if value not in set(['initialized', 'complete', 'failed', 'unspecified']): + raise ValueError("must be one of enum values ('initialized', 'complete', 'failed', 'unspecified')") return value model_config = ConfigDict( @@ -63,6 +50,7 @@ def status_validate_enum(cls, value): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -73,11 +61,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of StakingOperation from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -87,7 +75,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -100,14 +89,14 @@ def to_dict(self) -> dict[str, Any]: for _item_transactions in self.transactions: if _item_transactions: _items.append(_item_transactions.to_dict()) - _dict["transactions"] = _items + _dict['transactions'] = _items # override the default output from pydantic by calling `to_dict()` of metadata if self.metadata: - _dict["metadata"] = self.metadata.to_dict() + _dict['metadata'] = self.metadata.to_dict() return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of StakingOperation from a dict""" if obj is None: return None @@ -115,19 +104,15 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "id": obj.get("id"), - "wallet_id": obj.get("wallet_id"), - "network_id": obj.get("network_id"), - "address_id": obj.get("address_id"), - "status": obj.get("status"), - "transactions": [Transaction.from_dict(_item) for _item in obj["transactions"]] - if obj.get("transactions") is not None - else None, - "metadata": StakingOperationMetadata.from_dict(obj["metadata"]) - if obj.get("metadata") is not None - else None, - } - ) + _obj = cls.model_validate({ + "id": obj.get("id"), + "wallet_id": obj.get("wallet_id"), + "network_id": obj.get("network_id"), + "address_id": obj.get("address_id"), + "status": obj.get("status"), + "transactions": [Transaction.from_dict(_item) for _item in obj["transactions"]] if obj.get("transactions") is not None else None, + "metadata": StakingOperationMetadata.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None + }) return _obj + + diff --git a/cdp/client/models/staking_operation_metadata.py b/cdp/client/models/staking_operation_metadata.py index ce17613..c694574 100644 --- a/cdp/client/models/staking_operation_metadata.py +++ b/cdp/client/models/staking_operation_metadata.py @@ -1,59 +1,55 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 -from __future__ import annotations +from __future__ import annotations import json import pprint -from typing import Any - -from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator -from typing_extensions import Self - -from cdp.client.models.signed_voluntary_exit_message_metadata import ( - SignedVoluntaryExitMessageMetadata, -) +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from cdp.client.models.signed_voluntary_exit_message_metadata import SignedVoluntaryExitMessageMetadata +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self STAKINGOPERATIONMETADATA_ONE_OF_SCHEMAS = ["List[SignedVoluntaryExitMessageMetadata]"] - class StakingOperationMetadata(BaseModel): - """StakingOperationMetadata""" - + """ + StakingOperationMetadata + """ # data type: List[SignedVoluntaryExitMessageMetadata] - oneof_schema_1_validator: list[SignedVoluntaryExitMessageMetadata] | None = Field( - default=None, description="Additional metadata needed to power native eth unstaking." - ) - actual_instance: list[SignedVoluntaryExitMessageMetadata] | None = None - one_of_schemas: set[str] = {"List[SignedVoluntaryExitMessageMetadata]"} + oneof_schema_1_validator: Optional[List[SignedVoluntaryExitMessageMetadata]] = Field(default=None, description="Additional metadata needed to power native eth unstaking.") + actual_instance: Optional[Union[List[SignedVoluntaryExitMessageMetadata]]] = None + one_of_schemas: Set[str] = { "List[SignedVoluntaryExitMessageMetadata]" } model_config = ConfigDict( validate_assignment=True, protected_namespaces=(), ) + def __init__(self, *args, **kwargs) -> None: if args: if len(args) > 1: - raise ValueError( - "If a position argument is used, only 1 is allowed to set `actual_instance`" - ) + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") if kwargs: - raise ValueError( - "If a position argument is used, keyword arguments cannot be used." - ) + raise ValueError("If a position argument is used, keyword arguments cannot be used.") super().__init__(actual_instance=args[0]) else: super().__init__(**kwargs) - @field_validator("actual_instance") + @field_validator('actual_instance') def actual_instance_must_validate_oneof(cls, v): instance = StakingOperationMetadata.model_construct() error_messages = [] @@ -66,21 +62,15 @@ def actual_instance_must_validate_oneof(cls, v): error_messages.append(str(e)) if match > 1: # more than 1 match - raise ValueError( - "Multiple matches found when setting `actual_instance` in StakingOperationMetadata with oneOf schemas: List[SignedVoluntaryExitMessageMetadata]. Details: " - + ", ".join(error_messages) - ) + raise ValueError("Multiple matches found when setting `actual_instance` in StakingOperationMetadata with oneOf schemas: List[SignedVoluntaryExitMessageMetadata]. Details: " + ", ".join(error_messages)) elif match == 0: # no match - raise ValueError( - "No match found when setting `actual_instance` in StakingOperationMetadata with oneOf schemas: List[SignedVoluntaryExitMessageMetadata]. Details: " - + ", ".join(error_messages) - ) + raise ValueError("No match found when setting `actual_instance` in StakingOperationMetadata with oneOf schemas: List[SignedVoluntaryExitMessageMetadata]. Details: " + ", ".join(error_messages)) else: return v @classmethod - def from_dict(cls, obj: str | dict[str, Any]) -> Self: + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: return cls.from_json(json.dumps(obj)) @classmethod @@ -102,16 +92,10 @@ def from_json(cls, json_str: str) -> Self: if match > 1: # more than 1 match - raise ValueError( - "Multiple matches found when deserializing the JSON string into StakingOperationMetadata with oneOf schemas: List[SignedVoluntaryExitMessageMetadata]. Details: " - + ", ".join(error_messages) - ) + raise ValueError("Multiple matches found when deserializing the JSON string into StakingOperationMetadata with oneOf schemas: List[SignedVoluntaryExitMessageMetadata]. Details: " + ", ".join(error_messages)) elif match == 0: # no match - raise ValueError( - "No match found when deserializing the JSON string into StakingOperationMetadata with oneOf schemas: List[SignedVoluntaryExitMessageMetadata]. Details: " - + ", ".join(error_messages) - ) + raise ValueError("No match found when deserializing the JSON string into StakingOperationMetadata with oneOf schemas: List[SignedVoluntaryExitMessageMetadata]. Details: " + ", ".join(error_messages)) else: return instance @@ -125,7 +109,7 @@ def to_json(self) -> str: else: return json.dumps(self.actual_instance) - def to_dict(self) -> dict[str, Any] | list[SignedVoluntaryExitMessageMetadata] | None: + def to_dict(self) -> Optional[Union[Dict[str, Any], List[SignedVoluntaryExitMessageMetadata]]]: """Returns the dict representation of the actual instance""" if self.actual_instance is None: return None @@ -139,3 +123,5 @@ def to_dict(self) -> dict[str, Any] | list[SignedVoluntaryExitMessageMetadata] | def to_str(self) -> str: """Returns the string representation of the actual instance""" return pprint.pformat(self.model_dump()) + + diff --git a/cdp/client/models/staking_reward.py b/cdp/client/models/staking_reward.py index 90ae5eb..0dd6649 100644 --- a/cdp/client/models/staking_reward.py +++ b/cdp/client/models/staking_reward.py @@ -1,54 +1,46 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from datetime import datetime -from typing import Any, ClassVar +import json +from datetime import datetime from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.staking_reward_format import StakingRewardFormat from cdp.client.models.staking_reward_usd_value import StakingRewardUSDValue - +from typing import Optional, Set +from typing_extensions import Self class StakingReward(BaseModel): - """The staking rewards for an address.""" - - address_id: StrictStr = Field( - description="The onchain address for which the staking rewards are being fetched." - ) + """ + The staking rewards for an address. + """ # noqa: E501 + address_id: StrictStr = Field(description="The onchain address for which the staking rewards are being fetched.") var_date: datetime = Field(description="The timestamp of the reward in UTC.", alias="date") - amount: StrictStr = Field( - description='The reward amount in requested "format". Default is USD.' - ) + amount: StrictStr = Field(description="The reward amount in requested \"format\". Default is USD.") state: StrictStr = Field(description="The state of the reward.") format: StakingRewardFormat usd_value: StakingRewardUSDValue - __properties: ClassVar[list[str]] = [ - "address_id", - "date", - "amount", - "state", - "format", - "usd_value", - ] - - @field_validator("state") + __properties: ClassVar[List[str]] = ["address_id", "date", "amount", "state", "format", "usd_value"] + + @field_validator('state') def state_validate_enum(cls, value): """Validates the enum""" - if value not in set(["pending", "distributed"]): + if value not in set(['pending', 'distributed']): raise ValueError("must be one of enum values ('pending', 'distributed')") return value @@ -58,6 +50,7 @@ def state_validate_enum(cls, value): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -68,11 +61,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of StakingReward from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -82,7 +75,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -91,11 +85,11 @@ def to_dict(self) -> dict[str, Any]: ) # override the default output from pydantic by calling `to_dict()` of usd_value if self.usd_value: - _dict["usd_value"] = self.usd_value.to_dict() + _dict['usd_value'] = self.usd_value.to_dict() return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of StakingReward from a dict""" if obj is None: return None @@ -103,18 +97,14 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "address_id": obj.get("address_id"), - "date": obj.get("date"), - "amount": obj.get("amount"), - "state": obj.get("state"), - "format": obj.get("format") - if obj.get("format") is not None - else StakingRewardFormat.USD, - "usd_value": StakingRewardUSDValue.from_dict(obj["usd_value"]) - if obj.get("usd_value") is not None - else None, - } - ) + _obj = cls.model_validate({ + "address_id": obj.get("address_id"), + "date": obj.get("date"), + "amount": obj.get("amount"), + "state": obj.get("state"), + "format": obj.get("format") if obj.get("format") is not None else StakingRewardFormat.USD, + "usd_value": StakingRewardUSDValue.from_dict(obj["usd_value"]) if obj.get("usd_value") is not None else None + }) return _obj + + diff --git a/cdp/client/models/staking_reward_format.py b/cdp/client/models/staking_reward_format.py index e3c5b5a..018c9df 100644 --- a/cdp/client/models/staking_reward_format.py +++ b/cdp/client/models/staking_reward_format.py @@ -1,31 +1,37 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import json from enum import Enum - from typing_extensions import Self class StakingRewardFormat(str, Enum): - """The format in which the rewards are to be fetched i.e native or in equivalent USD""" + """ + The format in which the rewards are to be fetched i.e native or in equivalent USD + """ """ allowed enum values """ - USD = "usd" - NATIVE = "native" + USD = 'usd' + NATIVE = 'native' @classmethod def from_json(cls, json_str: str) -> Self: """Create an instance of StakingRewardFormat from a JSON string""" return cls(json.loads(json_str)) + + diff --git a/cdp/client/models/staking_reward_usd_value.py b/cdp/client/models/staking_reward_usd_value.py index 6000cd4..0ac8f1c 100644 --- a/cdp/client/models/staking_reward_usd_value.py +++ b/cdp/client/models/staking_reward_usd_value.py @@ -1,34 +1,36 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from datetime import datetime -from typing import Any, ClassVar +import json +from datetime import datetime from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set from typing_extensions import Self - class StakingRewardUSDValue(BaseModel): - """The USD value of the reward""" - + """ + The USD value of the reward + """ # noqa: E501 amount: StrictStr = Field(description="The value of the reward in USD") - conversion_price: StrictStr = Field( - description="The conversion price from native currency to USD" - ) + conversion_price: StrictStr = Field(description="The conversion price from native currency to USD") conversion_time: datetime = Field(description="The time of the conversion in UTC.") - __properties: ClassVar[list[str]] = ["amount", "conversion_price", "conversion_time"] + __properties: ClassVar[List[str]] = ["amount", "conversion_price", "conversion_time"] model_config = ConfigDict( populate_by_name=True, @@ -36,6 +38,7 @@ class StakingRewardUSDValue(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -46,11 +49,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of StakingRewardUSDValue from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -60,7 +63,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -70,7 +74,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of StakingRewardUSDValue from a dict""" if obj is None: return None @@ -78,11 +82,11 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "amount": obj.get("amount"), - "conversion_price": obj.get("conversion_price"), - "conversion_time": obj.get("conversion_time"), - } - ) + _obj = cls.model_validate({ + "amount": obj.get("amount"), + "conversion_price": obj.get("conversion_price"), + "conversion_time": obj.get("conversion_time") + }) return _obj + + diff --git a/cdp/client/models/token_contract_options.py b/cdp/client/models/token_contract_options.py index 309aa36..e1b9676 100644 --- a/cdp/client/models/token_contract_options.py +++ b/cdp/client/models/token_contract_options.py @@ -1,33 +1,35 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set from typing_extensions import Self - class TokenContractOptions(BaseModel): - """Options for token contract creation""" - + """ + Options for token contract creation + """ # noqa: E501 name: StrictStr = Field(description="The name of the token") symbol: StrictStr = Field(description="The symbol of the token") - total_supply: StrictStr = Field( - description="The total supply of the token denominated in the whole amount of the token." - ) - __properties: ClassVar[list[str]] = ["name", "symbol", "total_supply"] + total_supply: StrictStr = Field(description="The total supply of the token denominated in the whole amount of the token.") + __properties: ClassVar[List[str]] = ["name", "symbol", "total_supply"] model_config = ConfigDict( populate_by_name=True, @@ -35,6 +37,7 @@ class TokenContractOptions(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -45,11 +48,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of TokenContractOptions from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -59,7 +62,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -69,7 +73,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of TokenContractOptions from a dict""" if obj is None: return None @@ -77,11 +81,11 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "name": obj.get("name"), - "symbol": obj.get("symbol"), - "total_supply": obj.get("total_supply"), - } - ) + _obj = cls.model_validate({ + "name": obj.get("name"), + "symbol": obj.get("symbol"), + "total_supply": obj.get("total_supply") + }) return _obj + + diff --git a/cdp/client/models/trade.py b/cdp/client/models/trade.py index 946a475..701a787 100644 --- a/cdp/client/models/trade.py +++ b/cdp/client/models/trade.py @@ -1,56 +1,44 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List, Optional from cdp.client.models.asset import Asset from cdp.client.models.transaction import Transaction - +from typing import Optional, Set +from typing_extensions import Self class Trade(BaseModel): - """A trade of an asset to another asset""" - + """ + A trade of an asset to another asset + """ # noqa: E501 network_id: StrictStr = Field(description="The ID of the blockchain network") wallet_id: StrictStr = Field(description="The ID of the wallet that owns the from address") address_id: StrictStr = Field(description="The onchain address of the sender") trade_id: StrictStr = Field(description="The ID of the trade") - from_amount: StrictStr = Field( - description="The amount of the from asset to be traded (in atomic units of the from asset)" - ) + from_amount: StrictStr = Field(description="The amount of the from asset to be traded (in atomic units of the from asset)") from_asset: Asset - to_amount: StrictStr = Field( - description="The amount of the to asset that will be received (in atomic units of the to asset)" - ) + to_amount: StrictStr = Field(description="The amount of the to asset that will be received (in atomic units of the to asset)") to_asset: Asset transaction: Transaction - approve_transaction: Transaction | None = None - __properties: ClassVar[list[str]] = [ - "network_id", - "wallet_id", - "address_id", - "trade_id", - "from_amount", - "from_asset", - "to_amount", - "to_asset", - "transaction", - "approve_transaction", - ] + approve_transaction: Optional[Transaction] = None + __properties: ClassVar[List[str]] = ["network_id", "wallet_id", "address_id", "trade_id", "from_amount", "from_asset", "to_amount", "to_asset", "transaction", "approve_transaction"] model_config = ConfigDict( populate_by_name=True, @@ -58,6 +46,7 @@ class Trade(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -68,11 +57,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Trade from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -82,7 +71,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -91,20 +81,20 @@ def to_dict(self) -> dict[str, Any]: ) # override the default output from pydantic by calling `to_dict()` of from_asset if self.from_asset: - _dict["from_asset"] = self.from_asset.to_dict() + _dict['from_asset'] = self.from_asset.to_dict() # override the default output from pydantic by calling `to_dict()` of to_asset if self.to_asset: - _dict["to_asset"] = self.to_asset.to_dict() + _dict['to_asset'] = self.to_asset.to_dict() # override the default output from pydantic by calling `to_dict()` of transaction if self.transaction: - _dict["transaction"] = self.transaction.to_dict() + _dict['transaction'] = self.transaction.to_dict() # override the default output from pydantic by calling `to_dict()` of approve_transaction if self.approve_transaction: - _dict["approve_transaction"] = self.approve_transaction.to_dict() + _dict['approve_transaction'] = self.approve_transaction.to_dict() return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Trade from a dict""" if obj is None: return None @@ -112,26 +102,18 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "network_id": obj.get("network_id"), - "wallet_id": obj.get("wallet_id"), - "address_id": obj.get("address_id"), - "trade_id": obj.get("trade_id"), - "from_amount": obj.get("from_amount"), - "from_asset": Asset.from_dict(obj["from_asset"]) - if obj.get("from_asset") is not None - else None, - "to_amount": obj.get("to_amount"), - "to_asset": Asset.from_dict(obj["to_asset"]) - if obj.get("to_asset") is not None - else None, - "transaction": Transaction.from_dict(obj["transaction"]) - if obj.get("transaction") is not None - else None, - "approve_transaction": Transaction.from_dict(obj["approve_transaction"]) - if obj.get("approve_transaction") is not None - else None, - } - ) + _obj = cls.model_validate({ + "network_id": obj.get("network_id"), + "wallet_id": obj.get("wallet_id"), + "address_id": obj.get("address_id"), + "trade_id": obj.get("trade_id"), + "from_amount": obj.get("from_amount"), + "from_asset": Asset.from_dict(obj["from_asset"]) if obj.get("from_asset") is not None else None, + "to_amount": obj.get("to_amount"), + "to_asset": Asset.from_dict(obj["to_asset"]) if obj.get("to_asset") is not None else None, + "transaction": Transaction.from_dict(obj["transaction"]) if obj.get("transaction") is not None else None, + "approve_transaction": Transaction.from_dict(obj["approve_transaction"]) if obj.get("approve_transaction") is not None else None + }) return _obj + + diff --git a/cdp/client/models/trade_list.py b/cdp/client/models/trade_list.py index ad699a9..3d4667f 100644 --- a/cdp/client/models/trade_list.py +++ b/cdp/client/models/trade_list.py @@ -1,38 +1,37 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.trade import Trade - +from typing import Optional, Set +from typing_extensions import Self class TradeList(BaseModel): - """ """ - - data: list[Trade] - has_more: StrictBool = Field( - description="True if this list has another page of items after this one that can be fetched." - ) + """ + + """ # noqa: E501 + data: List[Trade] + has_more: StrictBool = Field(description="True if this list has another page of items after this one that can be fetched.") next_page: StrictStr = Field(description="The page token to be used to fetch the next page.") - total_count: StrictInt = Field( - description="The total number of trades for the address in the wallet." - ) - __properties: ClassVar[list[str]] = ["data", "has_more", "next_page", "total_count"] + total_count: StrictInt = Field(description="The total number of trades for the address in the wallet.") + __properties: ClassVar[List[str]] = ["data", "has_more", "next_page", "total_count"] model_config = ConfigDict( populate_by_name=True, @@ -40,6 +39,7 @@ class TradeList(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -50,11 +50,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of TradeList from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -64,7 +64,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -77,11 +78,11 @@ def to_dict(self) -> dict[str, Any]: for _item_data in self.data: if _item_data: _items.append(_item_data.to_dict()) - _dict["data"] = _items + _dict['data'] = _items return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of TradeList from a dict""" if obj is None: return None @@ -89,14 +90,12 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "data": [Trade.from_dict(_item) for _item in obj["data"]] - if obj.get("data") is not None - else None, - "has_more": obj.get("has_more"), - "next_page": obj.get("next_page"), - "total_count": obj.get("total_count"), - } - ) + _obj = cls.model_validate({ + "data": [Trade.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None, + "has_more": obj.get("has_more"), + "next_page": obj.get("next_page"), + "total_count": obj.get("total_count") + }) return _obj + + diff --git a/cdp/client/models/transaction.py b/cdp/client/models/transaction.py index 9bcf60b..594a1ff 100644 --- a/cdp/client/models/transaction.py +++ b/cdp/client/models/transaction.py @@ -1,79 +1,50 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List, Optional from cdp.client.models.transaction_content import TransactionContent - +from typing import Optional, Set +from typing_extensions import Self class Transaction(BaseModel): - """An onchain transaction.""" - + """ + An onchain transaction. + """ # noqa: E501 network_id: StrictStr = Field(description="The ID of the blockchain network.") - block_hash: StrictStr | None = Field( - default=None, description="The hash of the block at which the transaction was recorded." - ) - block_height: StrictStr | None = Field( - default=None, description="The block height at which the transaction was recorded." - ) + block_hash: Optional[StrictStr] = Field(default=None, description="The hash of the block at which the transaction was recorded.") + block_height: Optional[StrictStr] = Field(default=None, description="The block height at which the transaction was recorded.") from_address_id: StrictStr = Field(description="The onchain address of the sender.") - to_address_id: StrictStr | None = Field( - default=None, description="The onchain address of the recipient." - ) - unsigned_payload: StrictStr = Field( - description="The unsigned payload of the transaction. This is the payload that needs to be signed by the sender." - ) - signed_payload: StrictStr | None = Field( - default=None, - description="The signed payload of the transaction. This is the payload that has been signed by the sender.", - ) - transaction_hash: StrictStr | None = Field( - default=None, description="The hash of the transaction." - ) - transaction_link: StrictStr | None = Field( - default=None, - description="The link to view the transaction on a block explorer. This is optional and may not be present for all transactions.", - ) + to_address_id: Optional[StrictStr] = Field(default=None, description="The onchain address of the recipient.") + unsigned_payload: StrictStr = Field(description="The unsigned payload of the transaction. This is the payload that needs to be signed by the sender.") + signed_payload: Optional[StrictStr] = Field(default=None, description="The signed payload of the transaction. This is the payload that has been signed by the sender.") + transaction_hash: Optional[StrictStr] = Field(default=None, description="The hash of the transaction.") + transaction_link: Optional[StrictStr] = Field(default=None, description="The link to view the transaction on a block explorer. This is optional and may not be present for all transactions.") status: StrictStr = Field(description="The status of the transaction.") - content: TransactionContent | None = None - __properties: ClassVar[list[str]] = [ - "network_id", - "block_hash", - "block_height", - "from_address_id", - "to_address_id", - "unsigned_payload", - "signed_payload", - "transaction_hash", - "transaction_link", - "status", - "content", - ] - - @field_validator("status") + content: Optional[TransactionContent] = None + __properties: ClassVar[List[str]] = ["network_id", "block_hash", "block_height", "from_address_id", "to_address_id", "unsigned_payload", "signed_payload", "transaction_hash", "transaction_link", "status", "content"] + + @field_validator('status') def status_validate_enum(cls, value): """Validates the enum""" - if value not in set( - ["pending", "signed", "broadcast", "complete", "failed", "unspecified"] - ): - raise ValueError( - "must be one of enum values ('pending', 'signed', 'broadcast', 'complete', 'failed', 'unspecified')" - ) + if value not in set(['pending', 'signed', 'broadcast', 'complete', 'failed', 'unspecified']): + raise ValueError("must be one of enum values ('pending', 'signed', 'broadcast', 'complete', 'failed', 'unspecified')") return value model_config = ConfigDict( @@ -82,6 +53,7 @@ def status_validate_enum(cls, value): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -92,11 +64,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Transaction from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -106,7 +78,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -115,11 +88,11 @@ def to_dict(self) -> dict[str, Any]: ) # override the default output from pydantic by calling `to_dict()` of content if self.content: - _dict["content"] = self.content.to_dict() + _dict['content'] = self.content.to_dict() return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Transaction from a dict""" if obj is None: return None @@ -127,21 +100,19 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "network_id": obj.get("network_id"), - "block_hash": obj.get("block_hash"), - "block_height": obj.get("block_height"), - "from_address_id": obj.get("from_address_id"), - "to_address_id": obj.get("to_address_id"), - "unsigned_payload": obj.get("unsigned_payload"), - "signed_payload": obj.get("signed_payload"), - "transaction_hash": obj.get("transaction_hash"), - "transaction_link": obj.get("transaction_link"), - "status": obj.get("status"), - "content": TransactionContent.from_dict(obj["content"]) - if obj.get("content") is not None - else None, - } - ) + _obj = cls.model_validate({ + "network_id": obj.get("network_id"), + "block_hash": obj.get("block_hash"), + "block_height": obj.get("block_height"), + "from_address_id": obj.get("from_address_id"), + "to_address_id": obj.get("to_address_id"), + "unsigned_payload": obj.get("unsigned_payload"), + "signed_payload": obj.get("signed_payload"), + "transaction_hash": obj.get("transaction_hash"), + "transaction_link": obj.get("transaction_link"), + "status": obj.get("status"), + "content": TransactionContent.from_dict(obj["content"]) if obj.get("content") is not None else None + }) return _obj + + diff --git a/cdp/client/models/transaction_content.py b/cdp/client/models/transaction_content.py index d4cb21a..32208ab 100644 --- a/cdp/client/models/transaction_content.py +++ b/cdp/client/models/transaction_content.py @@ -1,55 +1,55 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import json import pprint -from typing import Any - -from pydantic import BaseModel, ConfigDict, ValidationError, field_validator -from typing_extensions import Self - +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional from cdp.client.models.ethereum_transaction import EthereumTransaction +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self TRANSACTIONCONTENT_ONE_OF_SCHEMAS = ["EthereumTransaction"] - class TransactionContent(BaseModel): - """TransactionContent""" - + """ + TransactionContent + """ # data type: EthereumTransaction - oneof_schema_1_validator: EthereumTransaction | None = None - actual_instance: EthereumTransaction | None = None - one_of_schemas: set[str] = {"EthereumTransaction"} + oneof_schema_1_validator: Optional[EthereumTransaction] = None + actual_instance: Optional[Union[EthereumTransaction]] = None + one_of_schemas: Set[str] = { "EthereumTransaction" } model_config = ConfigDict( validate_assignment=True, protected_namespaces=(), ) + def __init__(self, *args, **kwargs) -> None: if args: if len(args) > 1: - raise ValueError( - "If a position argument is used, only 1 is allowed to set `actual_instance`" - ) + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") if kwargs: - raise ValueError( - "If a position argument is used, keyword arguments cannot be used." - ) + raise ValueError("If a position argument is used, keyword arguments cannot be used.") super().__init__(actual_instance=args[0]) else: super().__init__(**kwargs) - @field_validator("actual_instance") + @field_validator('actual_instance') def actual_instance_must_validate_oneof(cls, v): instance = TransactionContent.model_construct() error_messages = [] @@ -61,21 +61,15 @@ def actual_instance_must_validate_oneof(cls, v): match += 1 if match > 1: # more than 1 match - raise ValueError( - "Multiple matches found when setting `actual_instance` in TransactionContent with oneOf schemas: EthereumTransaction. Details: " - + ", ".join(error_messages) - ) + raise ValueError("Multiple matches found when setting `actual_instance` in TransactionContent with oneOf schemas: EthereumTransaction. Details: " + ", ".join(error_messages)) elif match == 0: # no match - raise ValueError( - "No match found when setting `actual_instance` in TransactionContent with oneOf schemas: EthereumTransaction. Details: " - + ", ".join(error_messages) - ) + raise ValueError("No match found when setting `actual_instance` in TransactionContent with oneOf schemas: EthereumTransaction. Details: " + ", ".join(error_messages)) else: return v @classmethod - def from_dict(cls, obj: str | dict[str, Any]) -> Self: + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: return cls.from_json(json.dumps(obj)) @classmethod @@ -94,16 +88,10 @@ def from_json(cls, json_str: str) -> Self: if match > 1: # more than 1 match - raise ValueError( - "Multiple matches found when deserializing the JSON string into TransactionContent with oneOf schemas: EthereumTransaction. Details: " - + ", ".join(error_messages) - ) + raise ValueError("Multiple matches found when deserializing the JSON string into TransactionContent with oneOf schemas: EthereumTransaction. Details: " + ", ".join(error_messages)) elif match == 0: # no match - raise ValueError( - "No match found when deserializing the JSON string into TransactionContent with oneOf schemas: EthereumTransaction. Details: " - + ", ".join(error_messages) - ) + raise ValueError("No match found when deserializing the JSON string into TransactionContent with oneOf schemas: EthereumTransaction. Details: " + ", ".join(error_messages)) else: return instance @@ -117,7 +105,7 @@ def to_json(self) -> str: else: return json.dumps(self.actual_instance) - def to_dict(self) -> dict[str, Any] | EthereumTransaction | None: + def to_dict(self) -> Optional[Union[Dict[str, Any], EthereumTransaction]]: """Returns the dict representation of the actual instance""" if self.actual_instance is None: return None @@ -131,3 +119,5 @@ def to_dict(self) -> dict[str, Any] | EthereumTransaction | None: def to_str(self) -> str: """Returns the string representation of the actual instance""" return pprint.pformat(self.model_dump()) + + diff --git a/cdp/client/models/transaction_type.py b/cdp/client/models/transaction_type.py index dca5e24..ea0092e 100644 --- a/cdp/client/models/transaction_type.py +++ b/cdp/client/models/transaction_type.py @@ -1,30 +1,36 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import json from enum import Enum - from typing_extensions import Self class TransactionType(str, Enum): - """TransactionType""" + """ + TransactionType + """ """ allowed enum values """ - TRANSFER = "transfer" + TRANSFER = 'transfer' @classmethod def from_json(cls, json_str: str) -> Self: """Create an instance of TransactionType from a JSON string""" return cls(json.loads(json_str)) + + diff --git a/cdp/client/models/transfer.py b/cdp/client/models/transfer.py index 6f7bcbf..2b6fb1a 100644 --- a/cdp/client/models/transfer.py +++ b/cdp/client/models/transfer.py @@ -1,31 +1,34 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr, field_validator -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List, Optional from cdp.client.models.asset import Asset from cdp.client.models.sponsored_send import SponsoredSend from cdp.client.models.transaction import Transaction - +from typing import Optional, Set +from typing_extensions import Self class Transfer(BaseModel): - """A transfer of an asset from one address to another""" - + """ + A transfer of an asset from one address to another + """ # noqa: E501 network_id: StrictStr = Field(description="The ID of the blockchain network") wallet_id: StrictStr = Field(description="The ID of the wallet that owns the from address") address_id: StrictStr = Field(description="The onchain address of the sender") @@ -34,49 +37,23 @@ class Transfer(BaseModel): asset_id: StrictStr = Field(description="The ID of the asset being transferred") asset: Asset transfer_id: StrictStr = Field(description="The ID of the transfer") - transaction: Transaction | None = None - sponsored_send: SponsoredSend | None = None - unsigned_payload: StrictStr | None = Field( - default=None, - description="The unsigned payload of the transfer. This is the payload that needs to be signed by the sender.", - ) - signed_payload: StrictStr | None = Field( - default=None, - description="The signed payload of the transfer. This is the payload that has been signed by the sender.", - ) - transaction_hash: StrictStr | None = Field( - default=None, description="The hash of the transfer transaction" - ) - status: StrictStr | None = Field(default=None, description="The status of the transfer") + transaction: Optional[Transaction] = None + sponsored_send: Optional[SponsoredSend] = None + unsigned_payload: Optional[StrictStr] = Field(default=None, description="The unsigned payload of the transfer. This is the payload that needs to be signed by the sender.") + signed_payload: Optional[StrictStr] = Field(default=None, description="The signed payload of the transfer. This is the payload that has been signed by the sender.") + transaction_hash: Optional[StrictStr] = Field(default=None, description="The hash of the transfer transaction") + status: Optional[StrictStr] = Field(default=None, description="The status of the transfer") gasless: StrictBool = Field(description="Whether the transfer uses sponsored gas") - __properties: ClassVar[list[str]] = [ - "network_id", - "wallet_id", - "address_id", - "destination", - "amount", - "asset_id", - "asset", - "transfer_id", - "transaction", - "sponsored_send", - "unsigned_payload", - "signed_payload", - "transaction_hash", - "status", - "gasless", - ] - - @field_validator("status") + __properties: ClassVar[List[str]] = ["network_id", "wallet_id", "address_id", "destination", "amount", "asset_id", "asset", "transfer_id", "transaction", "sponsored_send", "unsigned_payload", "signed_payload", "transaction_hash", "status", "gasless"] + + @field_validator('status') def status_validate_enum(cls, value): """Validates the enum""" if value is None: return value - if value not in set(["pending", "broadcast", "complete", "failed"]): - raise ValueError( - "must be one of enum values ('pending', 'broadcast', 'complete', 'failed')" - ) + if value not in set(['pending', 'broadcast', 'complete', 'failed']): + raise ValueError("must be one of enum values ('pending', 'broadcast', 'complete', 'failed')") return value model_config = ConfigDict( @@ -85,6 +62,7 @@ def status_validate_enum(cls, value): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -95,11 +73,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Transfer from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -109,7 +87,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -118,17 +97,17 @@ def to_dict(self) -> dict[str, Any]: ) # override the default output from pydantic by calling `to_dict()` of asset if self.asset: - _dict["asset"] = self.asset.to_dict() + _dict['asset'] = self.asset.to_dict() # override the default output from pydantic by calling `to_dict()` of transaction if self.transaction: - _dict["transaction"] = self.transaction.to_dict() + _dict['transaction'] = self.transaction.to_dict() # override the default output from pydantic by calling `to_dict()` of sponsored_send if self.sponsored_send: - _dict["sponsored_send"] = self.sponsored_send.to_dict() + _dict['sponsored_send'] = self.sponsored_send.to_dict() return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Transfer from a dict""" if obj is None: return None @@ -136,27 +115,23 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "network_id": obj.get("network_id"), - "wallet_id": obj.get("wallet_id"), - "address_id": obj.get("address_id"), - "destination": obj.get("destination"), - "amount": obj.get("amount"), - "asset_id": obj.get("asset_id"), - "asset": Asset.from_dict(obj["asset"]) if obj.get("asset") is not None else None, - "transfer_id": obj.get("transfer_id"), - "transaction": Transaction.from_dict(obj["transaction"]) - if obj.get("transaction") is not None - else None, - "sponsored_send": SponsoredSend.from_dict(obj["sponsored_send"]) - if obj.get("sponsored_send") is not None - else None, - "unsigned_payload": obj.get("unsigned_payload"), - "signed_payload": obj.get("signed_payload"), - "transaction_hash": obj.get("transaction_hash"), - "status": obj.get("status"), - "gasless": obj.get("gasless"), - } - ) + _obj = cls.model_validate({ + "network_id": obj.get("network_id"), + "wallet_id": obj.get("wallet_id"), + "address_id": obj.get("address_id"), + "destination": obj.get("destination"), + "amount": obj.get("amount"), + "asset_id": obj.get("asset_id"), + "asset": Asset.from_dict(obj["asset"]) if obj.get("asset") is not None else None, + "transfer_id": obj.get("transfer_id"), + "transaction": Transaction.from_dict(obj["transaction"]) if obj.get("transaction") is not None else None, + "sponsored_send": SponsoredSend.from_dict(obj["sponsored_send"]) if obj.get("sponsored_send") is not None else None, + "unsigned_payload": obj.get("unsigned_payload"), + "signed_payload": obj.get("signed_payload"), + "transaction_hash": obj.get("transaction_hash"), + "status": obj.get("status"), + "gasless": obj.get("gasless") + }) return _obj + + diff --git a/cdp/client/models/transfer_list.py b/cdp/client/models/transfer_list.py index 99b9332..d202f9e 100644 --- a/cdp/client/models/transfer_list.py +++ b/cdp/client/models/transfer_list.py @@ -1,38 +1,37 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.transfer import Transfer - +from typing import Optional, Set +from typing_extensions import Self class TransferList(BaseModel): - """ """ - - data: list[Transfer] - has_more: StrictBool = Field( - description="True if this list has another page of items after this one that can be fetched." - ) + """ + + """ # noqa: E501 + data: List[Transfer] + has_more: StrictBool = Field(description="True if this list has another page of items after this one that can be fetched.") next_page: StrictStr = Field(description="The page token to be used to fetch the next page.") - total_count: StrictInt = Field( - description="The total number of transfers for the address in the wallet." - ) - __properties: ClassVar[list[str]] = ["data", "has_more", "next_page", "total_count"] + total_count: StrictInt = Field(description="The total number of transfers for the address in the wallet.") + __properties: ClassVar[List[str]] = ["data", "has_more", "next_page", "total_count"] model_config = ConfigDict( populate_by_name=True, @@ -40,6 +39,7 @@ class TransferList(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -50,11 +50,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of TransferList from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -64,7 +64,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -77,11 +78,11 @@ def to_dict(self) -> dict[str, Any]: for _item_data in self.data: if _item_data: _items.append(_item_data.to_dict()) - _dict["data"] = _items + _dict['data'] = _items return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of TransferList from a dict""" if obj is None: return None @@ -89,14 +90,12 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "data": [Transfer.from_dict(_item) for _item in obj["data"]] - if obj.get("data") is not None - else None, - "has_more": obj.get("has_more"), - "next_page": obj.get("next_page"), - "total_count": obj.get("total_count"), - } - ) + _obj = cls.model_validate({ + "data": [Transfer.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None, + "has_more": obj.get("has_more"), + "next_page": obj.get("next_page"), + "total_count": obj.get("total_count") + }) return _obj + + diff --git a/cdp/client/models/update_webhook_request.py b/cdp/client/models/update_webhook_request.py index af0182e..968bb1e 100644 --- a/cdp/client/models/update_webhook_request.py +++ b/cdp/client/models/update_webhook_request.py @@ -1,37 +1,37 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List, Optional from cdp.client.models.webhook_event_filter import WebhookEventFilter from cdp.client.models.webhook_event_type_filter import WebhookEventTypeFilter - +from typing import Optional, Set +from typing_extensions import Self class UpdateWebhookRequest(BaseModel): - """UpdateWebhookRequest""" - - event_type_filter: WebhookEventTypeFilter | None = None - event_filters: list[WebhookEventFilter] | None = Field( - default=None, - description="Webhook will monitor all events that matches any one of the event filters.", - ) + """ + UpdateWebhookRequest + """ # noqa: E501 + event_type_filter: Optional[WebhookEventTypeFilter] = None + event_filters: Optional[List[WebhookEventFilter]] = Field(default=None, description="Webhook will monitor all events that matches any one of the event filters.") notification_uri: StrictStr = Field(description="The Webhook uri that updates to") - __properties: ClassVar[list[str]] = ["event_type_filter", "event_filters", "notification_uri"] + __properties: ClassVar[List[str]] = ["event_type_filter", "event_filters", "notification_uri"] model_config = ConfigDict( populate_by_name=True, @@ -39,6 +39,7 @@ class UpdateWebhookRequest(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -49,11 +50,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of UpdateWebhookRequest from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -63,7 +64,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -72,18 +74,18 @@ def to_dict(self) -> dict[str, Any]: ) # override the default output from pydantic by calling `to_dict()` of event_type_filter if self.event_type_filter: - _dict["event_type_filter"] = self.event_type_filter.to_dict() + _dict['event_type_filter'] = self.event_type_filter.to_dict() # override the default output from pydantic by calling `to_dict()` of each item in event_filters (list) _items = [] if self.event_filters: for _item_event_filters in self.event_filters: if _item_event_filters: _items.append(_item_event_filters.to_dict()) - _dict["event_filters"] = _items + _dict['event_filters'] = _items return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of UpdateWebhookRequest from a dict""" if obj is None: return None @@ -91,17 +93,11 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "event_type_filter": WebhookEventTypeFilter.from_dict(obj["event_type_filter"]) - if obj.get("event_type_filter") is not None - else None, - "event_filters": [ - WebhookEventFilter.from_dict(_item) for _item in obj["event_filters"] - ] - if obj.get("event_filters") is not None - else None, - "notification_uri": obj.get("notification_uri"), - } - ) + _obj = cls.model_validate({ + "event_type_filter": WebhookEventTypeFilter.from_dict(obj["event_type_filter"]) if obj.get("event_type_filter") is not None else None, + "event_filters": [WebhookEventFilter.from_dict(_item) for _item in obj["event_filters"]] if obj.get("event_filters") is not None else None, + "notification_uri": obj.get("notification_uri") + }) return _obj + + diff --git a/cdp/client/models/user.py b/cdp/client/models/user.py index d431c00..1ccb4f1 100644 --- a/cdp/client/models/user.py +++ b/cdp/client/models/user.py @@ -1,30 +1,34 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set from typing_extensions import Self - class User(BaseModel): - """User""" - + """ + User + """ # noqa: E501 id: StrictStr = Field(description="The ID of the user") - display_name: StrictStr | None = None - __properties: ClassVar[list[str]] = ["id", "display_name"] + display_name: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["id", "display_name"] model_config = ConfigDict( populate_by_name=True, @@ -32,6 +36,7 @@ class User(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -42,11 +47,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of User from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -56,7 +61,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -66,7 +72,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of User from a dict""" if obj is None: return None @@ -74,5 +80,10 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate({"id": obj.get("id"), "display_name": obj.get("display_name")}) + _obj = cls.model_validate({ + "id": obj.get("id"), + "display_name": obj.get("display_name") + }) return _obj + + diff --git a/cdp/client/models/validator.py b/cdp/client/models/validator.py index ad123bd..312e9e5 100644 --- a/cdp/client/models/validator.py +++ b/cdp/client/models/validator.py @@ -1,46 +1,39 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List, Optional from cdp.client.models.validator_details import ValidatorDetails from cdp.client.models.validator_status import ValidatorStatus - +from typing import Optional, Set +from typing_extensions import Self class Validator(BaseModel): - """A validator onchain.""" - - validator_id: StrictStr = Field( - description="The publicly identifiable unique id of the validator. This can be the public key for Ethereum validators and maybe an address for some other network." - ) - network_id: StrictStr = Field( - description="The ID of the blockchain network to which the Validator belongs." - ) + """ + A validator onchain. + """ # noqa: E501 + validator_id: StrictStr = Field(description="The publicly identifiable unique id of the validator. This can be the public key for Ethereum validators and maybe an address for some other network.") + network_id: StrictStr = Field(description="The ID of the blockchain network to which the Validator belongs.") asset_id: StrictStr = Field(description="The ID of the asset that the validator helps stake.") status: ValidatorStatus - details: ValidatorDetails | None = None - __properties: ClassVar[list[str]] = [ - "validator_id", - "network_id", - "asset_id", - "status", - "details", - ] + details: Optional[ValidatorDetails] = None + __properties: ClassVar[List[str]] = ["validator_id", "network_id", "asset_id", "status", "details"] model_config = ConfigDict( populate_by_name=True, @@ -48,6 +41,7 @@ class Validator(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -58,11 +52,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Validator from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -72,7 +66,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -81,11 +76,11 @@ def to_dict(self) -> dict[str, Any]: ) # override the default output from pydantic by calling `to_dict()` of details if self.details: - _dict["details"] = self.details.to_dict() + _dict['details'] = self.details.to_dict() return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Validator from a dict""" if obj is None: return None @@ -93,15 +88,13 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "validator_id": obj.get("validator_id"), - "network_id": obj.get("network_id"), - "asset_id": obj.get("asset_id"), - "status": obj.get("status"), - "details": ValidatorDetails.from_dict(obj["details"]) - if obj.get("details") is not None - else None, - } - ) + _obj = cls.model_validate({ + "validator_id": obj.get("validator_id"), + "network_id": obj.get("network_id"), + "asset_id": obj.get("asset_id"), + "status": obj.get("status"), + "details": ValidatorDetails.from_dict(obj["details"]) if obj.get("details") is not None else None + }) return _obj + + diff --git a/cdp/client/models/validator_details.py b/cdp/client/models/validator_details.py index 9b00932..0159b71 100644 --- a/cdp/client/models/validator_details.py +++ b/cdp/client/models/validator_details.py @@ -1,83 +1,75 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import json import pprint -from typing import Any - -from pydantic import BaseModel, ConfigDict, ValidationError, field_validator -from typing_extensions import Self - +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional from cdp.client.models.ethereum_validator_metadata import EthereumValidatorMetadata +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self VALIDATORDETAILS_ONE_OF_SCHEMAS = ["EthereumValidatorMetadata"] - class ValidatorDetails(BaseModel): - """ValidatorDetails""" - + """ + ValidatorDetails + """ # data type: EthereumValidatorMetadata - oneof_schema_1_validator: EthereumValidatorMetadata | None = None - actual_instance: EthereumValidatorMetadata | None = None - one_of_schemas: set[str] = {"EthereumValidatorMetadata"} + oneof_schema_1_validator: Optional[EthereumValidatorMetadata] = None + actual_instance: Optional[Union[EthereumValidatorMetadata]] = None + one_of_schemas: Set[str] = { "EthereumValidatorMetadata" } model_config = ConfigDict( validate_assignment=True, protected_namespaces=(), ) + def __init__(self, *args, **kwargs) -> None: if args: if len(args) > 1: - raise ValueError( - "If a position argument is used, only 1 is allowed to set `actual_instance`" - ) + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") if kwargs: - raise ValueError( - "If a position argument is used, keyword arguments cannot be used." - ) + raise ValueError("If a position argument is used, keyword arguments cannot be used.") super().__init__(actual_instance=args[0]) else: super().__init__(**kwargs) - @field_validator("actual_instance") + @field_validator('actual_instance') def actual_instance_must_validate_oneof(cls, v): instance = ValidatorDetails.model_construct() error_messages = [] match = 0 # validate data type: EthereumValidatorMetadata if not isinstance(v, EthereumValidatorMetadata): - error_messages.append( - f"Error! Input type `{type(v)}` is not `EthereumValidatorMetadata`" - ) + error_messages.append(f"Error! Input type `{type(v)}` is not `EthereumValidatorMetadata`") else: match += 1 if match > 1: # more than 1 match - raise ValueError( - "Multiple matches found when setting `actual_instance` in ValidatorDetails with oneOf schemas: EthereumValidatorMetadata. Details: " - + ", ".join(error_messages) - ) + raise ValueError("Multiple matches found when setting `actual_instance` in ValidatorDetails with oneOf schemas: EthereumValidatorMetadata. Details: " + ", ".join(error_messages)) elif match == 0: # no match - raise ValueError( - "No match found when setting `actual_instance` in ValidatorDetails with oneOf schemas: EthereumValidatorMetadata. Details: " - + ", ".join(error_messages) - ) + raise ValueError("No match found when setting `actual_instance` in ValidatorDetails with oneOf schemas: EthereumValidatorMetadata. Details: " + ", ".join(error_messages)) else: return v @classmethod - def from_dict(cls, obj: str | dict[str, Any]) -> Self: + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: return cls.from_json(json.dumps(obj)) @classmethod @@ -96,16 +88,10 @@ def from_json(cls, json_str: str) -> Self: if match > 1: # more than 1 match - raise ValueError( - "Multiple matches found when deserializing the JSON string into ValidatorDetails with oneOf schemas: EthereumValidatorMetadata. Details: " - + ", ".join(error_messages) - ) + raise ValueError("Multiple matches found when deserializing the JSON string into ValidatorDetails with oneOf schemas: EthereumValidatorMetadata. Details: " + ", ".join(error_messages)) elif match == 0: # no match - raise ValueError( - "No match found when deserializing the JSON string into ValidatorDetails with oneOf schemas: EthereumValidatorMetadata. Details: " - + ", ".join(error_messages) - ) + raise ValueError("No match found when deserializing the JSON string into ValidatorDetails with oneOf schemas: EthereumValidatorMetadata. Details: " + ", ".join(error_messages)) else: return instance @@ -119,7 +105,7 @@ def to_json(self) -> str: else: return json.dumps(self.actual_instance) - def to_dict(self) -> dict[str, Any] | EthereumValidatorMetadata | None: + def to_dict(self) -> Optional[Union[Dict[str, Any], EthereumValidatorMetadata]]: """Returns the dict representation of the actual instance""" if self.actual_instance is None: return None @@ -133,3 +119,5 @@ def to_dict(self) -> dict[str, Any] | EthereumValidatorMetadata | None: def to_str(self) -> str: """Returns the string representation of the actual instance""" return pprint.pformat(self.model_dump()) + + diff --git a/cdp/client/models/validator_list.py b/cdp/client/models/validator_list.py index 7f72c37..41903bc 100644 --- a/cdp/client/models/validator_list.py +++ b/cdp/client/models/validator_list.py @@ -1,35 +1,36 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.validator import Validator - +from typing import Optional, Set +from typing_extensions import Self class ValidatorList(BaseModel): - """ """ - - data: list[Validator] - has_more: StrictBool = Field( - description="True if this list has another page of items after this one that can be fetched." - ) + """ + + """ # noqa: E501 + data: List[Validator] + has_more: StrictBool = Field(description="True if this list has another page of items after this one that can be fetched.") next_page: StrictStr = Field(description="The page token to be used to fetch the next page.") - __properties: ClassVar[list[str]] = ["data", "has_more", "next_page"] + __properties: ClassVar[List[str]] = ["data", "has_more", "next_page"] model_config = ConfigDict( populate_by_name=True, @@ -37,6 +38,7 @@ class ValidatorList(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -47,11 +49,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ValidatorList from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -61,7 +63,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -74,11 +77,11 @@ def to_dict(self) -> dict[str, Any]: for _item_data in self.data: if _item_data: _items.append(_item_data.to_dict()) - _dict["data"] = _items + _dict['data'] = _items return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ValidatorList from a dict""" if obj is None: return None @@ -86,13 +89,11 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "data": [Validator.from_dict(_item) for _item in obj["data"]] - if obj.get("data") is not None - else None, - "has_more": obj.get("has_more"), - "next_page": obj.get("next_page"), - } - ) + _obj = cls.model_validate({ + "data": [Validator.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None, + "has_more": obj.get("has_more"), + "next_page": obj.get("next_page") + }) return _obj + + diff --git a/cdp/client/models/validator_status.py b/cdp/client/models/validator_status.py index b37435f..7fb324a 100644 --- a/cdp/client/models/validator_status.py +++ b/cdp/client/models/validator_status.py @@ -1,42 +1,48 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import json from enum import Enum - from typing_extensions import Self class ValidatorStatus(str, Enum): - """The status of the validator.""" + """ + The status of the validator. + """ """ allowed enum values """ - UNKNOWN = "unknown" - PROVISIONING = "provisioning" - PROVISIONED = "provisioned" - DEPOSITED = "deposited" - PENDING_ACTIVATION = "pending_activation" - ACTIVE = "active" - EXITING = "exiting" - EXITED = "exited" - WITHDRAWAL_AVAILABLE = "withdrawal_available" - WITHDRAWAL_COMPLETE = "withdrawal_complete" - ACTIVE_SLASHED = "active_slashed" - EXITED_SLASHED = "exited_slashed" - REAPED = "reaped" + UNKNOWN = 'unknown' + PROVISIONING = 'provisioning' + PROVISIONED = 'provisioned' + DEPOSITED = 'deposited' + PENDING_ACTIVATION = 'pending_activation' + ACTIVE = 'active' + EXITING = 'exiting' + EXITED = 'exited' + WITHDRAWAL_AVAILABLE = 'withdrawal_available' + WITHDRAWAL_COMPLETE = 'withdrawal_complete' + ACTIVE_SLASHED = 'active_slashed' + EXITED_SLASHED = 'exited_slashed' + REAPED = 'reaped' @classmethod def from_json(cls, json_str: str) -> Self: """Create an instance of ValidatorStatus from a JSON string""" return cls(json.loads(json_str)) + + diff --git a/cdp/client/models/wallet.py b/cdp/client/models/wallet.py index 626d05d..2952845 100644 --- a/cdp/client/models/wallet.py +++ b/cdp/client/models/wallet.py @@ -1,52 +1,47 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List, Optional from cdp.client.models.address import Address from cdp.client.models.feature_set import FeatureSet - +from typing import Optional, Set +from typing_extensions import Self class Wallet(BaseModel): - """Wallet""" - + """ + Wallet + """ # noqa: E501 id: StrictStr = Field(description="The server-assigned ID for the wallet.") network_id: StrictStr = Field(description="The ID of the blockchain network") - default_address: Address | None = None + default_address: Optional[Address] = None feature_set: FeatureSet - server_signer_status: StrictStr | None = Field( - default=None, description="The status of the Server-Signer for the wallet if present." - ) - __properties: ClassVar[list[str]] = [ - "id", - "network_id", - "default_address", - "feature_set", - "server_signer_status", - ] - - @field_validator("server_signer_status") + server_signer_status: Optional[StrictStr] = Field(default=None, description="The status of the Server-Signer for the wallet if present.") + __properties: ClassVar[List[str]] = ["id", "network_id", "default_address", "feature_set", "server_signer_status"] + + @field_validator('server_signer_status') def server_signer_status_validate_enum(cls, value): """Validates the enum""" if value is None: return value - if value not in set(["pending_seed_creation", "active_seed"]): + if value not in set(['pending_seed_creation', 'active_seed']): raise ValueError("must be one of enum values ('pending_seed_creation', 'active_seed')") return value @@ -56,6 +51,7 @@ def server_signer_status_validate_enum(cls, value): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -66,11 +62,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Wallet from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -80,7 +76,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -89,14 +86,14 @@ def to_dict(self) -> dict[str, Any]: ) # override the default output from pydantic by calling `to_dict()` of default_address if self.default_address: - _dict["default_address"] = self.default_address.to_dict() + _dict['default_address'] = self.default_address.to_dict() # override the default output from pydantic by calling `to_dict()` of feature_set if self.feature_set: - _dict["feature_set"] = self.feature_set.to_dict() + _dict['feature_set'] = self.feature_set.to_dict() return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Wallet from a dict""" if obj is None: return None @@ -104,17 +101,13 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "id": obj.get("id"), - "network_id": obj.get("network_id"), - "default_address": Address.from_dict(obj["default_address"]) - if obj.get("default_address") is not None - else None, - "feature_set": FeatureSet.from_dict(obj["feature_set"]) - if obj.get("feature_set") is not None - else None, - "server_signer_status": obj.get("server_signer_status"), - } - ) + _obj = cls.model_validate({ + "id": obj.get("id"), + "network_id": obj.get("network_id"), + "default_address": Address.from_dict(obj["default_address"]) if obj.get("default_address") is not None else None, + "feature_set": FeatureSet.from_dict(obj["feature_set"]) if obj.get("feature_set") is not None else None, + "server_signer_status": obj.get("server_signer_status") + }) return _obj + + diff --git a/cdp/client/models/wallet_list.py b/cdp/client/models/wallet_list.py index eea2d56..6fe9466 100644 --- a/cdp/client/models/wallet_list.py +++ b/cdp/client/models/wallet_list.py @@ -1,36 +1,37 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List from cdp.client.models.wallet import Wallet - +from typing import Optional, Set +from typing_extensions import Self class WalletList(BaseModel): - """Paginated list of wallets""" - - data: list[Wallet] - has_more: StrictBool = Field( - description="True if this list has another page of items after this one that can be fetched." - ) + """ + Paginated list of wallets + """ # noqa: E501 + data: List[Wallet] + has_more: StrictBool = Field(description="True if this list has another page of items after this one that can be fetched.") next_page: StrictStr = Field(description="The page token to be used to fetch the next page.") total_count: StrictInt = Field(description="The total number of wallets") - __properties: ClassVar[list[str]] = ["data", "has_more", "next_page", "total_count"] + __properties: ClassVar[List[str]] = ["data", "has_more", "next_page", "total_count"] model_config = ConfigDict( populate_by_name=True, @@ -38,6 +39,7 @@ class WalletList(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -48,11 +50,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of WalletList from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -62,7 +64,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -75,11 +78,11 @@ def to_dict(self) -> dict[str, Any]: for _item_data in self.data: if _item_data: _items.append(_item_data.to_dict()) - _dict["data"] = _items + _dict['data'] = _items return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of WalletList from a dict""" if obj is None: return None @@ -87,14 +90,12 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "data": [Wallet.from_dict(_item) for _item in obj["data"]] - if obj.get("data") is not None - else None, - "has_more": obj.get("has_more"), - "next_page": obj.get("next_page"), - "total_count": obj.get("total_count"), - } - ) + _obj = cls.model_validate({ + "data": [Wallet.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None, + "has_more": obj.get("has_more"), + "next_page": obj.get("next_page"), + "total_count": obj.get("total_count") + }) return _obj + + diff --git a/cdp/client/models/webhook.py b/cdp/client/models/webhook.py index 60cdfb7..e71b31c 100644 --- a/cdp/client/models/webhook.py +++ b/cdp/client/models/webhook.py @@ -1,66 +1,45 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from datetime import datetime -from typing import Any, ClassVar +import json +from datetime import datetime from pydantic import BaseModel, ConfigDict, Field, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List, Optional from cdp.client.models.webhook_event_filter import WebhookEventFilter from cdp.client.models.webhook_event_type import WebhookEventType from cdp.client.models.webhook_event_type_filter import WebhookEventTypeFilter - +from typing import Optional, Set +from typing_extensions import Self class Webhook(BaseModel): - """Webhook that is used for getting notifications when monitored events occur.""" - - id: StrictStr | None = Field(default=None, description="Identifier of the webhook.") - network_id: StrictStr | None = Field( - default=None, description="The ID of the blockchain network" - ) - event_type: WebhookEventType | None = None - event_type_filter: WebhookEventTypeFilter | None = None - event_filters: list[WebhookEventFilter] | None = Field( - default=None, - description="Webhook will monitor all events that matches any one of the event filters.", - ) - notification_uri: StrictStr | None = Field( - default=None, description="The URL to which the notifications will be sent." - ) - created_at: datetime | None = Field( - default=None, description="The date and time the webhook was created." - ) - updated_at: datetime | None = Field( - default=None, description="The date and time the webhook was last updated." - ) - signature_header: StrictStr | None = Field( - default=None, - description="The header that will contain the signature of the webhook payload.", - ) - __properties: ClassVar[list[str]] = [ - "id", - "network_id", - "event_type", - "event_type_filter", - "event_filters", - "notification_uri", - "created_at", - "updated_at", - "signature_header", - ] + """ + Webhook that is used for getting notifications when monitored events occur. + """ # noqa: E501 + id: Optional[StrictStr] = Field(default=None, description="Identifier of the webhook.") + network_id: Optional[StrictStr] = Field(default=None, description="The ID of the blockchain network") + event_type: Optional[WebhookEventType] = None + event_type_filter: Optional[WebhookEventTypeFilter] = None + event_filters: Optional[List[WebhookEventFilter]] = Field(default=None, description="Webhook will monitor all events that matches any one of the event filters.") + notification_uri: Optional[StrictStr] = Field(default=None, description="The URL to which the notifications will be sent.") + created_at: Optional[datetime] = Field(default=None, description="The date and time the webhook was created.") + updated_at: Optional[datetime] = Field(default=None, description="The date and time the webhook was last updated.") + signature_header: Optional[StrictStr] = Field(default=None, description="The header that will contain the signature of the webhook payload.") + __properties: ClassVar[List[str]] = ["id", "network_id", "event_type", "event_type_filter", "event_filters", "notification_uri", "created_at", "updated_at", "signature_header"] model_config = ConfigDict( populate_by_name=True, @@ -68,6 +47,7 @@ class Webhook(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -78,11 +58,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Webhook from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -92,7 +72,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -101,18 +82,18 @@ def to_dict(self) -> dict[str, Any]: ) # override the default output from pydantic by calling `to_dict()` of event_type_filter if self.event_type_filter: - _dict["event_type_filter"] = self.event_type_filter.to_dict() + _dict['event_type_filter'] = self.event_type_filter.to_dict() # override the default output from pydantic by calling `to_dict()` of each item in event_filters (list) _items = [] if self.event_filters: for _item_event_filters in self.event_filters: if _item_event_filters: _items.append(_item_event_filters.to_dict()) - _dict["event_filters"] = _items + _dict['event_filters'] = _items return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Webhook from a dict""" if obj is None: return None @@ -120,23 +101,17 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "id": obj.get("id"), - "network_id": obj.get("network_id"), - "event_type": obj.get("event_type"), - "event_type_filter": WebhookEventTypeFilter.from_dict(obj["event_type_filter"]) - if obj.get("event_type_filter") is not None - else None, - "event_filters": [ - WebhookEventFilter.from_dict(_item) for _item in obj["event_filters"] - ] - if obj.get("event_filters") is not None - else None, - "notification_uri": obj.get("notification_uri"), - "created_at": obj.get("created_at"), - "updated_at": obj.get("updated_at"), - "signature_header": obj.get("signature_header"), - } - ) + _obj = cls.model_validate({ + "id": obj.get("id"), + "network_id": obj.get("network_id"), + "event_type": obj.get("event_type"), + "event_type_filter": WebhookEventTypeFilter.from_dict(obj["event_type_filter"]) if obj.get("event_type_filter") is not None else None, + "event_filters": [WebhookEventFilter.from_dict(_item) for _item in obj["event_filters"]] if obj.get("event_filters") is not None else None, + "notification_uri": obj.get("notification_uri"), + "created_at": obj.get("created_at"), + "updated_at": obj.get("updated_at"), + "signature_header": obj.get("signature_header") + }) return _obj + + diff --git a/cdp/client/models/webhook_event_filter.py b/cdp/client/models/webhook_event_filter.py index 0a5f762..6e160ca 100644 --- a/cdp/client/models/webhook_event_filter.py +++ b/cdp/client/models/webhook_event_filter.py @@ -1,40 +1,35 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set from typing_extensions import Self - class WebhookEventFilter(BaseModel): - """The event_filter parameter specifies the criteria to filter events from the blockchain. It allows filtering events by contract address, sender address and receiver address. For a single event filter, not all of the properties need to be presented.""" - - contract_address: StrictStr | None = Field( - default=None, - description="The onchain contract address of the token for which the events should be tracked.", - ) - from_address: StrictStr | None = Field( - default=None, - description="The onchain address of the sender. Set this filter to track all transfer events originating from your address.", - ) - to_address: StrictStr | None = Field( - default=None, - description="The onchain address of the receiver. Set this filter to track all transfer events sent to your address.", - ) - __properties: ClassVar[list[str]] = ["contract_address", "from_address", "to_address"] + """ + The event_filter parameter specifies the criteria to filter events from the blockchain. It allows filtering events by contract address, sender address and receiver address. For a single event filter, not all of the properties need to be presented. + """ # noqa: E501 + contract_address: Optional[StrictStr] = Field(default=None, description="The onchain contract address of the token for which the events should be tracked.") + from_address: Optional[StrictStr] = Field(default=None, description="The onchain address of the sender. Set this filter to track all transfer events originating from your address.") + to_address: Optional[StrictStr] = Field(default=None, description="The onchain address of the receiver. Set this filter to track all transfer events sent to your address.") + __properties: ClassVar[List[str]] = ["contract_address", "from_address", "to_address"] model_config = ConfigDict( populate_by_name=True, @@ -42,6 +37,7 @@ class WebhookEventFilter(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -52,11 +48,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of WebhookEventFilter from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -66,7 +62,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -76,7 +73,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of WebhookEventFilter from a dict""" if obj is None: return None @@ -84,11 +81,11 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "contract_address": obj.get("contract_address"), - "from_address": obj.get("from_address"), - "to_address": obj.get("to_address"), - } - ) + _obj = cls.model_validate({ + "contract_address": obj.get("contract_address"), + "from_address": obj.get("from_address"), + "to_address": obj.get("to_address") + }) return _obj + + diff --git a/cdp/client/models/webhook_event_type.py b/cdp/client/models/webhook_event_type.py index 08fab35..d2438b7 100644 --- a/cdp/client/models/webhook_event_type.py +++ b/cdp/client/models/webhook_event_type.py @@ -1,33 +1,39 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import json from enum import Enum - from typing_extensions import Self class WebhookEventType(str, Enum): - """WebhookEventType""" + """ + WebhookEventType + """ """ allowed enum values """ - UNSPECIFIED = "unspecified" - ERC20_TRANSFER = "erc20_transfer" - ERC721_TRANSFER = "erc721_transfer" - WALLET_ACTIVITY = "wallet_activity" + UNSPECIFIED = 'unspecified' + ERC20_TRANSFER = 'erc20_transfer' + ERC721_TRANSFER = 'erc721_transfer' + WALLET_ACTIVITY = 'wallet_activity' @classmethod def from_json(cls, json_str: str) -> Self: """Create an instance of WebhookEventType from a JSON string""" return cls(json.loads(json_str)) + + diff --git a/cdp/client/models/webhook_event_type_filter.py b/cdp/client/models/webhook_event_type_filter.py index 51ee554..6344979 100644 --- a/cdp/client/models/webhook_event_type_filter.py +++ b/cdp/client/models/webhook_event_type_filter.py @@ -1,83 +1,75 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import json import pprint -from typing import Any - -from pydantic import BaseModel, ConfigDict, ValidationError, field_validator -from typing_extensions import Self - +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional from cdp.client.models.webhook_wallet_activity_filter import WebhookWalletActivityFilter +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self WEBHOOKEVENTTYPEFILTER_ONE_OF_SCHEMAS = ["WebhookWalletActivityFilter"] - class WebhookEventTypeFilter(BaseModel): - """The event_type_filter parameter specifies the criteria to filter events based on event type.""" - + """ + The event_type_filter parameter specifies the criteria to filter events based on event type. + """ # data type: WebhookWalletActivityFilter - oneof_schema_1_validator: WebhookWalletActivityFilter | None = None - actual_instance: WebhookWalletActivityFilter | None = None - one_of_schemas: set[str] = {"WebhookWalletActivityFilter"} + oneof_schema_1_validator: Optional[WebhookWalletActivityFilter] = None + actual_instance: Optional[Union[WebhookWalletActivityFilter]] = None + one_of_schemas: Set[str] = { "WebhookWalletActivityFilter" } model_config = ConfigDict( validate_assignment=True, protected_namespaces=(), ) + def __init__(self, *args, **kwargs) -> None: if args: if len(args) > 1: - raise ValueError( - "If a position argument is used, only 1 is allowed to set `actual_instance`" - ) + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") if kwargs: - raise ValueError( - "If a position argument is used, keyword arguments cannot be used." - ) + raise ValueError("If a position argument is used, keyword arguments cannot be used.") super().__init__(actual_instance=args[0]) else: super().__init__(**kwargs) - @field_validator("actual_instance") + @field_validator('actual_instance') def actual_instance_must_validate_oneof(cls, v): instance = WebhookEventTypeFilter.model_construct() error_messages = [] match = 0 # validate data type: WebhookWalletActivityFilter if not isinstance(v, WebhookWalletActivityFilter): - error_messages.append( - f"Error! Input type `{type(v)}` is not `WebhookWalletActivityFilter`" - ) + error_messages.append(f"Error! Input type `{type(v)}` is not `WebhookWalletActivityFilter`") else: match += 1 if match > 1: # more than 1 match - raise ValueError( - "Multiple matches found when setting `actual_instance` in WebhookEventTypeFilter with oneOf schemas: WebhookWalletActivityFilter. Details: " - + ", ".join(error_messages) - ) + raise ValueError("Multiple matches found when setting `actual_instance` in WebhookEventTypeFilter with oneOf schemas: WebhookWalletActivityFilter. Details: " + ", ".join(error_messages)) elif match == 0: # no match - raise ValueError( - "No match found when setting `actual_instance` in WebhookEventTypeFilter with oneOf schemas: WebhookWalletActivityFilter. Details: " - + ", ".join(error_messages) - ) + raise ValueError("No match found when setting `actual_instance` in WebhookEventTypeFilter with oneOf schemas: WebhookWalletActivityFilter. Details: " + ", ".join(error_messages)) else: return v @classmethod - def from_dict(cls, obj: str | dict[str, Any]) -> Self: + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: return cls.from_json(json.dumps(obj)) @classmethod @@ -96,16 +88,10 @@ def from_json(cls, json_str: str) -> Self: if match > 1: # more than 1 match - raise ValueError( - "Multiple matches found when deserializing the JSON string into WebhookEventTypeFilter with oneOf schemas: WebhookWalletActivityFilter. Details: " - + ", ".join(error_messages) - ) + raise ValueError("Multiple matches found when deserializing the JSON string into WebhookEventTypeFilter with oneOf schemas: WebhookWalletActivityFilter. Details: " + ", ".join(error_messages)) elif match == 0: # no match - raise ValueError( - "No match found when deserializing the JSON string into WebhookEventTypeFilter with oneOf schemas: WebhookWalletActivityFilter. Details: " - + ", ".join(error_messages) - ) + raise ValueError("No match found when deserializing the JSON string into WebhookEventTypeFilter with oneOf schemas: WebhookWalletActivityFilter. Details: " + ", ".join(error_messages)) else: return instance @@ -119,7 +105,7 @@ def to_json(self) -> str: else: return json.dumps(self.actual_instance) - def to_dict(self) -> dict[str, Any] | WebhookWalletActivityFilter | None: + def to_dict(self) -> Optional[Union[Dict[str, Any], WebhookWalletActivityFilter]]: """Returns the dict representation of the actual instance""" if self.actual_instance is None: return None @@ -133,3 +119,5 @@ def to_dict(self) -> dict[str, Any] | WebhookWalletActivityFilter | None: def to_str(self) -> str: """Returns the string representation of the actual instance""" return pprint.pformat(self.model_dump()) + + diff --git a/cdp/client/models/webhook_list.py b/cdp/client/models/webhook_list.py index e949a74..b97f900 100644 --- a/cdp/client/models/webhook_list.py +++ b/cdp/client/models/webhook_list.py @@ -1,38 +1,36 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr -from typing_extensions import Self - +from typing import Any, ClassVar, Dict, List, Optional from cdp.client.models.webhook import Webhook - +from typing import Optional, Set +from typing_extensions import Self class WebhookList(BaseModel): - """ """ - - data: list[Webhook] - has_more: StrictBool | None = Field( - default=None, - description="True if this list has another page of items after this one that can be fetched.", - ) - next_page: StrictStr | None = Field( - default=None, description="The page token to be used to fetch the next page." - ) - __properties: ClassVar[list[str]] = ["data", "has_more", "next_page"] + """ + + """ # noqa: E501 + data: List[Webhook] + has_more: Optional[StrictBool] = Field(default=None, description="True if this list has another page of items after this one that can be fetched.") + next_page: Optional[StrictStr] = Field(default=None, description="The page token to be used to fetch the next page.") + __properties: ClassVar[List[str]] = ["data", "has_more", "next_page"] model_config = ConfigDict( populate_by_name=True, @@ -40,6 +38,7 @@ class WebhookList(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -50,11 +49,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of WebhookList from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -64,7 +63,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -77,11 +77,11 @@ def to_dict(self) -> dict[str, Any]: for _item_data in self.data: if _item_data: _items.append(_item_data.to_dict()) - _dict["data"] = _items + _dict['data'] = _items return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of WebhookList from a dict""" if obj is None: return None @@ -89,13 +89,11 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - { - "data": [Webhook.from_dict(_item) for _item in obj["data"]] - if obj.get("data") is not None - else None, - "has_more": obj.get("has_more"), - "next_page": obj.get("next_page"), - } - ) + _obj = cls.model_validate({ + "data": [Webhook.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None, + "has_more": obj.get("has_more"), + "next_page": obj.get("next_page") + }) return _obj + + diff --git a/cdp/client/models/webhook_wallet_activity_filter.py b/cdp/client/models/webhook_wallet_activity_filter.py index 5c7777e..30356d4 100644 --- a/cdp/client/models/webhook_wallet_activity_filter.py +++ b/cdp/client/models/webhook_wallet_activity_filter.py @@ -1,34 +1,34 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. -Do not edit the class manually. -""" + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) -from __future__ import annotations + Do not edit the class manually. +""" # noqa: E501 -import json + +from __future__ import annotations import pprint import re # noqa: F401 -from typing import Any, ClassVar +import json from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set from typing_extensions import Self - class WebhookWalletActivityFilter(BaseModel): - """Filter for wallet activity events. This filter allows the client to specify one or more wallet addresses to monitor for activities such as transactions, transfers, or other types of events that are associated with the specified addresses.""" - - addresses: list[StrictStr] | None = Field( - default=None, description="A list of wallet addresses to filter on." - ) - wallet_id: StrictStr | None = Field( - default=None, description="The ID of the wallet that owns the webhook." - ) - __properties: ClassVar[list[str]] = ["addresses", "wallet_id"] + """ + Filter for wallet activity events. This filter allows the client to specify one or more wallet addresses to monitor for activities such as transactions, transfers, or other types of events that are associated with the specified addresses. + """ # noqa: E501 + addresses: Optional[List[StrictStr]] = Field(default=None, description="A list of wallet addresses to filter on.") + wallet_id: Optional[StrictStr] = Field(default=None, description="The ID of the wallet that owns the webhook.") + __properties: ClassVar[List[str]] = ["addresses", "wallet_id"] model_config = ConfigDict( populate_by_name=True, @@ -36,6 +36,7 @@ class WebhookWalletActivityFilter(BaseModel): protected_namespaces=(), ) + def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.model_dump(by_alias=True)) @@ -46,11 +47,11 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self | None: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of WebhookWalletActivityFilter from a JSON string""" return cls.from_dict(json.loads(json_str)) - def to_dict(self) -> dict[str, Any]: + def to_dict(self) -> Dict[str, Any]: """Return the dictionary representation of the model using alias. This has the following differences from calling pydantic's @@ -60,7 +61,8 @@ def to_dict(self) -> dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ - excluded_fields: set[str] = set([]) + excluded_fields: Set[str] = set([ + ]) _dict = self.model_dump( by_alias=True, @@ -70,7 +72,7 @@ def to_dict(self) -> dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of WebhookWalletActivityFilter from a dict""" if obj is None: return None @@ -78,7 +80,10 @@ def from_dict(cls, obj: dict[str, Any] | None) -> Self | None: if not isinstance(obj, dict): return cls.model_validate(obj) - _obj = cls.model_validate( - {"addresses": obj.get("addresses"), "wallet_id": obj.get("wallet_id")} - ) + _obj = cls.model_validate({ + "addresses": obj.get("addresses"), + "wallet_id": obj.get("wallet_id") + }) return _obj + + diff --git a/cdp/client/rest.py b/cdp/client/rest.py index ff864c2..78c1966 100644 --- a/cdp/client/rest.py +++ b/cdp/client/rest.py @@ -1,12 +1,16 @@ -"""Coinbase Platform API +# coding: utf-8 -This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. +""" + Coinbase Platform API -The version of the OpenAPI document: 0.0.1-alpha -Generated by OpenAPI Generator (https://openapi-generator.tech) + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 -Do not edit the class manually. -""" import io import json @@ -32,6 +36,7 @@ def is_socks_proxy_url(url): class RESTResponse(io.IOBase): + def __init__(self, resp) -> None: self.response = resp self.status = resp.status @@ -53,11 +58,12 @@ def getheader(self, name, default=None): class RESTClientObject: + def __init__(self, configuration) -> None: # urllib3.PoolManager will pass all kw parameters to connectionpool - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 - # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html + # 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 + # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 # cert_reqs if configuration.verify_ssl: @@ -72,19 +78,22 @@ def __init__(self, configuration) -> None: "key_file": configuration.key_file, } if configuration.assert_hostname is not None: - pool_args["assert_hostname"] = configuration.assert_hostname + pool_args['assert_hostname'] = ( + configuration.assert_hostname + ) if configuration.retries is not None: - pool_args["retries"] = configuration.retries + pool_args['retries'] = configuration.retries if configuration.tls_server_name: - pool_args["server_hostname"] = configuration.tls_server_name + pool_args['server_hostname'] = configuration.tls_server_name + if configuration.socket_options is not None: - pool_args["socket_options"] = configuration.socket_options + pool_args['socket_options'] = configuration.socket_options if configuration.connection_pool_maxsize is not None: - pool_args["maxsize"] = configuration.connection_pool_maxsize + pool_args['maxsize'] = configuration.connection_pool_maxsize # https pool manager self.pool_manager: urllib3.PoolManager @@ -92,7 +101,6 @@ def __init__(self, configuration) -> None: if configuration.proxy: if is_socks_proxy_url(configuration.proxy): from urllib3.contrib.socks import SOCKSProxyManager - pool_args["proxy_url"] = configuration.proxy pool_args["headers"] = configuration.proxy_headers self.pool_manager = SOCKSProxyManager(**pool_args) @@ -104,7 +112,13 @@ def __init__(self, configuration) -> None: self.pool_manager = urllib3.PoolManager(**pool_args) def request( - self, method, url, headers=None, body=None, post_params=None, _request_timeout=None + self, + method, + url, + headers=None, + body=None, + post_params=None, + _request_timeout=None ): """Perform requests. @@ -121,10 +135,20 @@ def request( (connection, read) timeouts. """ method = method.upper() - assert method in ["GET", "HEAD", "DELETE", "POST", "PUT", "PATCH", "OPTIONS"] + assert method in [ + 'GET', + 'HEAD', + 'DELETE', + 'POST', + 'PUT', + 'PATCH', + 'OPTIONS' + ] if post_params and body: - raise ApiValueError("body parameter cannot be used with post_params parameter.") + raise ApiValueError( + "body parameter cannot be used with post_params parameter." + ) post_params = post_params or {} headers = headers or {} @@ -133,15 +157,25 @@ def request( if _request_timeout: if isinstance(_request_timeout, (int, float)): 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]) + elif ( + isinstance(_request_timeout, tuple) + and len(_request_timeout) == 2 + ): + timeout = urllib3.Timeout( + connect=_request_timeout[0], + read=_request_timeout[1] + ) try: # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` - if method in ["POST", "PUT", "PATCH", "OPTIONS", "DELETE"]: + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + # no content type provided or payload is json - content_type = headers.get("Content-Type") - if not content_type or re.search("json", content_type, re.IGNORECASE): + content_type = headers.get('Content-Type') + if ( + not content_type + or re.search('json', content_type, re.IGNORECASE) + ): request_body = None if body is not None: request_body = json.dumps(body) @@ -151,9 +185,9 @@ def request( body=request_body, timeout=timeout, headers=headers, - preload_content=False, + preload_content=False ) - elif content_type == "application/x-www-form-urlencoded": + elif content_type == 'application/x-www-form-urlencoded': r = self.pool_manager.request( method, url, @@ -161,18 +195,15 @@ def request( encode_multipart=False, timeout=timeout, headers=headers, - preload_content=False, + preload_content=False ) - elif content_type == "multipart/form-data": + elif 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"] + del headers['Content-Type'] # Ensures that dict objects are serialized - post_params = [ - (a, json.dumps(b)) if isinstance(b, dict) else (a, b) - for a, b in post_params - ] + post_params = [(a, json.dumps(b)) if isinstance(b, dict) else (a,b) for a, b in post_params] r = self.pool_manager.request( method, url, @@ -180,7 +211,7 @@ def request( encode_multipart=True, timeout=timeout, headers=headers, - preload_content=False, + preload_content=False ) # Pass a `string` parameter directly in the body to support # other content types than JSON when `body` argument is @@ -192,9 +223,9 @@ def request( body=body, timeout=timeout, headers=headers, - preload_content=False, + preload_content=False ) - elif headers["Content-Type"] == "text/plain" and isinstance(body, bool): + elif headers['Content-Type'] == 'text/plain' and isinstance(body, bool): request_body = "true" if body else "false" r = self.pool_manager.request( method, @@ -202,8 +233,7 @@ def request( body=request_body, preload_content=False, timeout=timeout, - headers=headers, - ) + headers=headers) else: # Cannot generate the request from given parameters msg = """Cannot prepare a request message for provided @@ -213,7 +243,12 @@ def request( # For `GET`, `HEAD` else: r = self.pool_manager.request( - method, url, fields={}, timeout=timeout, headers=headers, preload_content=False + method, + url, + fields={}, + timeout=timeout, + headers=headers, + preload_content=False ) except urllib3.exceptions.SSLError as e: msg = "\n".join([type(e).__name__, str(e)]) diff --git a/cdp/smart_contract.py b/cdp/smart_contract.py new file mode 100644 index 0000000..809793c --- /dev/null +++ b/cdp/smart_contract.py @@ -0,0 +1,352 @@ +import json +import time +from enum import Enum +from typing import Any + +from eth_account.signers.local import LocalAccount + +from cdp.cdp import Cdp +from cdp.client.models.create_smart_contract_request import CreateSmartContractRequest +from cdp.client.models.deploy_smart_contract_request import DeploySmartContractRequest +from cdp.client.models.multi_token_contract_options import MultiTokenContractOptions +from cdp.client.models.nft_contract_options import NFTContractOptions +from cdp.client.models.smart_contract import SmartContract as SmartContractModel +from cdp.client.models.smart_contract_options import SmartContractOptions +from cdp.client.models.token_contract_options import TokenContractOptions +from cdp.transaction import Transaction + + +class SmartContract: + """A representation of a SmartContract on the blockchain.""" + + class Type(Enum): + """Enumeration of SmartContract types.""" + + ERC20 = "erc20" + ERC721 = "erc721" + ERC1155 = "erc1155" + + def __str__(self) -> str: + """Return a string representation of the Type.""" + return self.value + + def __repr__(self) -> str: + """Return a string representation of the Type.""" + return str(self) + + class TokenContractOptions(dict): + """Options for token contracts (ERC20).""" + + def __init__(self, name: str, symbol: str, total_supply: str): + """Initialize the TokenContractOptions. + + Args: + name: The name of the token. + symbol: The symbol of the token. + total_supply: The total supply of the token. + + """ + super().__init__(name=name, symbol=symbol, total_supply=total_supply) + + class NFTContractOptions(dict): + """Options for NFT contracts (ERC721).""" + + def __init__(self, name: str, symbol: str, base_uri: str): + """Initialize the NFTContractOptions. + + Args: + name: The name of the NFT collection. + symbol: The symbol of the NFT collection. + base_uri: The base URI for the NFT metadata. + + """ + super().__init__(name=name, symbol=symbol, base_uri=base_uri) + + class MultiTokenContractOptions(dict): + """Options for multi-token contracts (ERC1155).""" + + def __init__(self, uri: str): + """Initialize the MultiTokenContractOptions. + + Args: + uri: The URI for all token metadata. + + """ + super().__init__(uri=uri) + + def __init__(self, model: SmartContractModel) -> None: + """Initialize the SmartContract class. + + Args: + model: The model representing the smart contract. + + Raises: + ValueError: If the smart contract model is empty. + + """ + if not model: + raise ValueError("SmartContract model cannot be empty") + self._model = model + self._transaction = None + + @property + def smart_contract_id(self) -> str: + """Get the smart contract ID. + + Returns: + The smart contract ID. + + """ + return self._model.smart_contract_id + + @property + def network_id(self) -> str: + """Get the network ID of the smart contract. + + Returns: + The network ID. + + """ + return self._model.network_id + + @property + def wallet_id(self) -> str: + """Get the wallet ID that deployed the smart contract. + + Returns: + The wallet ID. + + """ + return self._model.wallet_id + + @property + def contract_address(self) -> str: + """Get the contract address of the smart contract. + + Returns: + The contract address. + + """ + return self._model.contract_address + + @property + def deployer_address(self) -> str: + """Get the deployer address of the smart contract. + + Returns: + The deployer address. + + """ + return self._model.deployer_address + + @property + def type(self) -> Type: + """Get the type of the smart contract. + + Returns: + The smart contract type. + + Raises: + ValueError: If the smart contract type is unknown. + + """ + return self.Type(self._model.type) + + @property + def options(self) -> TokenContractOptions | NFTContractOptions | MultiTokenContractOptions: + """Get the options of the smart contract. + + Returns: + The smart contract options as a higher-level options class. + + Raises: + ValueError: If the smart contract type is unknown or if options are not set. + + """ + if self._model.options is None or self._model.options.actual_instance is None: + raise ValueError("Smart contract options are not set") + + options_dict = self._model.options.actual_instance.__dict__ + if self.type == self.Type.ERC20: + return self.TokenContractOptions(**options_dict) + elif self.type == self.Type.ERC721: + return self.NFTContractOptions(**options_dict) + elif self.type == self.Type.ERC1155: + return self.MultiTokenContractOptions(**options_dict) + else: + raise ValueError(f"Unknown smart contract type: {self.type}") + + @property + def abi(self) -> dict[str, Any]: + """Get the ABI of the smart contract. + + Returns: + The ABI as a JSON object. + + """ + return json.loads(self._model.abi) + + @property + def transaction(self) -> Transaction | None: + """Get the transaction associated with the smart contract deployment. + + Returns: + Transaction: The transaction. + + """ + if self._transaction is None and self._model.transaction is not None: + self._update_transaction(self._model) + return self._transaction + + def sign(self, key: LocalAccount) -> "SmartContract": + """Sign the smart contract deployment with the given key. + + Args: + key: The key to sign the smart contract deployment with. + + Returns: + The signed SmartContract object. + + Raises: + ValueError: If the key is not a LocalAccount. + + """ + if not isinstance(key, LocalAccount): + raise ValueError("key must be a LocalAccount") + + self.transaction.sign(key) + return self + + def broadcast(self) -> "SmartContract": + """Broadcast the smart contract deployment to the network. + + Returns: + The broadcasted SmartContract object. + + Raises: + ValueError: If the smart contract deployment is not signed. + + """ + if not self.transaction.signed: + raise ValueError("Cannot broadcast unsigned SmartContract deployment") + + deploy_smart_contract_request = DeploySmartContractRequest( + signed_payload=self.transaction.signature + ) + + model = Cdp.api_clients.smart_contracts.deploy_smart_contract( + wallet_id=self.wallet_id, + address_id=self.deployer_address, + smart_contract_id=self.smart_contract_id, + deploy_smart_contract_request=deploy_smart_contract_request, + ) + self._model = model + return self + + def reload(self) -> "SmartContract": + """Reload the SmartContract model with the latest data from the server. + + Returns: + The updated SmartContract object. + + """ + model = Cdp.api_clients.smart_contracts.get_smart_contract( + wallet_id=self.wallet_id, + address_id=self.deployer_address, + smart_contract_id=self.smart_contract_id, + ) + self._model = model + self._update_transaction(model) + return self + + def wait(self, interval_seconds: float = 0.2, timeout_seconds: float = 10) -> "SmartContract": + """Wait until the smart contract deployment is confirmed on the network or fails onchain. + + Args: + interval_seconds: The interval to check the status of the smart contract deployment. + timeout_seconds: The maximum time to wait for the smart contract deployment to be confirmed. + + Returns: + The SmartContract object in a terminal state. + + Raises: + TimeoutError: If the smart contract deployment times out. + + """ + start_time = time.time() + while self.transaction is not None and not self.transaction.terminal_state: + self.reload() + + if time.time() - start_time > timeout_seconds: + raise TimeoutError("SmartContract deployment timed out") + + time.sleep(interval_seconds) + + return self + + @classmethod + def create( + cls, + wallet_id: str, + address_id: str, + type: Type, + options: TokenContractOptions | NFTContractOptions | MultiTokenContractOptions, + ) -> "SmartContract": + """Create a new SmartContract object. + + Args: + wallet_id: The ID of the wallet that will deploy the smart contract. + address_id: The ID of the address that will deploy the smart contract. + type: The type of the smart contract (ERC20, ERC721, or ERC1155). + options: The options of the smart contract. + + Returns: + The created smart contract. + + Raises: + ValueError: If the options type is unsupported. + + """ + if isinstance(options, cls.TokenContractOptions): + openapi_options = TokenContractOptions(**options) + elif isinstance(options, cls.NFTContractOptions): + openapi_options = NFTContractOptions(**options) + elif isinstance(options, cls.MultiTokenContractOptions): + openapi_options = MultiTokenContractOptions(**options) + else: + raise ValueError(f"Unsupported options type: {type(options)}") + + smart_contract_options = SmartContractOptions(actual_instance=openapi_options) + + create_smart_contract_request = CreateSmartContractRequest( + type=type.value, + options=smart_contract_options, + ) + + model = Cdp.api_clients.smart_contracts.create_smart_contract( + wallet_id=wallet_id, + address_id=address_id, + create_smart_contract_request=create_smart_contract_request, + ) + + return cls(model) + + def _update_transaction(self, model: SmartContractModel) -> None: + """Update the transaction with the new model.""" + if model.transaction is not None: + self._transaction = Transaction(model.transaction) + + def __str__(self) -> str: + """Return a string representation of the smart contract.""" + return ( + f"SmartContract: (smart_contract_id: {self.smart_contract_id}, " + f"wallet_id: {self.wallet_id}, network_id: {self.network_id}, " + f"contract_address: {self.contract_address}, type: {self.type}, " + f"transaction_hash: {self.transaction.transaction_hash if self.transaction else None}, " + f"transaction_link: {self.transaction.transaction_link if self.transaction else None}, " + f"status: {self.transaction.status if self.transaction else None})" + ) + + def __repr__(self) -> str: + """Return a string representation of the smart contract.""" + return str(self) diff --git a/cdp/transaction.py b/cdp/transaction.py index 14f078b..816ad1a 100644 --- a/cdp/transaction.py +++ b/cdp/transaction.py @@ -125,12 +125,16 @@ def raw(self) -> DynamicFeeTransaction: "maxPriorityFeePerGas": int(parsed_payload["maxPriorityFeePerGas"], 16), "maxFeePerGas": int(parsed_payload["maxFeePerGas"], 16), "gas": int(parsed_payload["gas"], 16), - "to": Web3.to_bytes(hexstr=parsed_payload["to"]), "value": int(parsed_payload["value"], 16), "data": parsed_payload.get("input", ""), "type": "0x2", # EIP-1559 transaction type } + # Handle 'to' field separately since smart contract deployments have an empty 'to' field + if parsed_payload["to"]: + transaction_dict["to"] = Web3.to_bytes(hexstr=parsed_payload["to"]) + else: + transaction_dict["to"] = b"" # Empty bytes for contract deployment self._raw = DynamicFeeTransaction(transaction_dict) return self._raw diff --git a/cdp/wallet.py b/cdp/wallet.py index c117641..4f37ba1 100644 --- a/cdp/wallet.py +++ b/cdp/wallet.py @@ -29,6 +29,7 @@ from cdp.contract_invocation import ContractInvocation from cdp.faucet_transaction import FaucetTransaction from cdp.payload_signature import PayloadSignature +from cdp.smart_contract import SmartContract from cdp.trade import Trade from cdp.wallet_address import WalletAddress from cdp.wallet_data import WalletData @@ -716,3 +717,63 @@ def __repr__(self) -> str: """ return str(self) + + def deploy_token( + self, name: str, symbol: str, total_supply: Number | Decimal | str + ) -> SmartContract: + """Deploy a token smart contract. + + Args: + name (str): The name of the token. + symbol (str): The symbol of the token. + total_supply (Union[Number, Decimal, str]): The total supply of the token. + + Returns: + SmartContract: The deployed smart contract. + + Raises: + ValueError: If the default address does not exist. + + """ + if self.default_address is None: + raise ValueError("Default address does not exist") + + return self.default_address.deploy_token(name, symbol, str(total_supply)) + + def deploy_nft(self, name: str, symbol: str, base_uri: str) -> SmartContract: + """Deploy an NFT smart contract. + + Args: + name (str): The name of the NFT. + symbol (str): The symbol of the NFT. + base_uri (str): The base URI for the NFT. + + Returns: + SmartContract: The deployed smart contract. + + Raises: + ValueError: If the default address does not exist. + + """ + if self.default_address is None: + raise ValueError("Default address does not exist") + + return self.default_address.deploy_nft(name, symbol, base_uri) + + def deploy_multi_token(self, uri: str) -> SmartContract: + """Deploy a multi-token smart contract. + + Args: + uri (str): The URI for the multi-token contract. + + Returns: + SmartContract: The deployed smart contract. + + Raises: + ValueError: If the default address does not exist. + + """ + if self.default_address is None: + raise ValueError("Default address does not exist") + + return self.default_address.deploy_multi_token(uri) diff --git a/cdp/wallet_address.py b/cdp/wallet_address.py index c530781..389012f 100644 --- a/cdp/wallet_address.py +++ b/cdp/wallet_address.py @@ -12,6 +12,7 @@ from cdp.contract_invocation import ContractInvocation from cdp.errors import InsufficientFundsError from cdp.payload_signature import PayloadSignature +from cdp.smart_contract import SmartContract from cdp.trade import Trade from cdp.transfer import Transfer @@ -221,6 +222,89 @@ def sign_payload(self, unsigned_payload: str) -> PayloadSignature: signature=signature, ) + def deploy_token( + self, name: str, symbol: str, total_supply: Number | Decimal | str + ) -> SmartContract: + """Deploy a token smart contract. + + Args: + name (str): The name of the token. + symbol (str): The symbol of the token. + total_supply (Union[Number, Decimal, str]): The total supply of the token. + + Returns: + SmartContract: The deployed smart contract. + + """ + smart_contract = SmartContract.create( + wallet_id=self.wallet_id, + address_id=self.address_id, + type=SmartContract.Type.ERC20, + options=SmartContract.TokenContractOptions( + name=name, symbol=symbol, total_supply=str(total_supply) + ), + ) + + if Cdp.use_server_signer: + return smart_contract + + smart_contract.sign(self.key) + smart_contract.broadcast() + + return smart_contract + + def deploy_nft(self, name: str, symbol: str, base_uri: str) -> SmartContract: + """Deploy an NFT smart contract. + + Args: + name (str): The name of the NFT. + symbol (str): The symbol of the NFT. + base_uri (str): The base URI for the NFT. + + Returns: + SmartContract: The deployed smart contract. + + """ + smart_contract = SmartContract.create( + wallet_id=self.wallet_id, + address_id=self.address_id, + type=SmartContract.Type.ERC721, + options=SmartContract.NFTContractOptions(name=name, symbol=symbol, base_uri=base_uri), + ) + + if Cdp.use_server_signer: + return smart_contract + + smart_contract.sign(self.key) + smart_contract.broadcast() + + return smart_contract + + def deploy_multi_token(self, uri: str) -> SmartContract: + """Deploy a multi-token smart contract. + + Args: + uri (str): The URI for the multi-token contract. + + Returns: + SmartContract: The deployed smart contract. + + """ + smart_contract = SmartContract.create( + wallet_id=self.wallet_id, + address_id=self.address_id, + type=SmartContract.Type.ERC1155, + options=SmartContract.MultiTokenContractOptions(uri=uri), + ) + + if Cdp.use_server_signer: + return smart_contract + + smart_contract.sign(self.key) + smart_contract.broadcast() + + return smart_contract + def transfers(self) -> Iterator[Transfer]: """List transfers for this wallet address. diff --git a/tests/test_smart_contract.py b/tests/test_smart_contract.py new file mode 100644 index 0000000..18cdad1 --- /dev/null +++ b/tests/test_smart_contract.py @@ -0,0 +1,237 @@ +from unittest.mock import ANY, Mock, call, patch + +import pytest + +from cdp.client.models.smart_contract import SmartContract as SmartContractModel +from cdp.client.models.smart_contract_options import SmartContractOptions +from cdp.client.models.token_contract_options import TokenContractOptions +from cdp.client.models.transaction import Transaction as TransactionModel +from cdp.smart_contract import SmartContract + + +@pytest.fixture +def transaction_model_factory(): + """Create and return a factory for creating TransactionModel fixtures.""" + + def _create_transaction_model(status="complete"): + return TransactionModel( + network_id="base-sepolia", + transaction_hash="0xtransactionhash", + from_address_id="0xaddressid", + to_address_id="0xdestination", + unsigned_payload="0xunsignedpayload", + signed_payload="0xsignedpayload" + if status in ["signed", "broadcast", "complete"] + else None, + status=status, + transaction_link="https://sepolia.basescan.org/tx/0xtransactionlink" + if status == "complete" + else None, + ) + + return _create_transaction_model + + +@pytest.fixture +def smart_contract_model_factory(transaction_model_factory): + """Create and return a factory for creating SmartContractModel fixtures.""" + + def _create_smart_contract_model(status="complete"): + token_options = TokenContractOptions(name="TestToken", symbol="TT", total_supply="1000000") + smart_contract_options = SmartContractOptions(actual_instance=token_options) + + return SmartContractModel( + smart_contract_id="test-contract-id", + network_id="base-sepolia", + wallet_id="test-wallet-id", + contract_address="0xcontractaddress", + deployer_address="0xdeployeraddress", + type="erc20", + options=smart_contract_options, + abi='{"abi": "data"}', + transaction=transaction_model_factory(status), + ) + + return _create_smart_contract_model + + +@pytest.fixture +def smart_contract_factory(smart_contract_model_factory): + """Create and return a factory for creating SmartContract fixtures.""" + + def _create_smart_contract(status="complete"): + smart_contract_model = smart_contract_model_factory(status) + return SmartContract(smart_contract_model) + + return _create_smart_contract + + +def test_smart_contract_initialization(smart_contract_factory): + """Test the initialization of a SmartContract object.""" + smart_contract = smart_contract_factory() + assert isinstance(smart_contract, SmartContract) + + +def test_smart_contract_properties(smart_contract_factory): + """Test the properties of a SmartContract object.""" + smart_contract = smart_contract_factory() + assert smart_contract.smart_contract_id == "test-contract-id" + assert smart_contract.wallet_id == "test-wallet-id" + assert smart_contract.network_id == "base-sepolia" + assert smart_contract.contract_address == "0xcontractaddress" + assert smart_contract.deployer_address == "0xdeployeraddress" + assert smart_contract.type.value == SmartContract.Type.ERC20.value + assert smart_contract.options == { + "name": "TestToken", + "symbol": "TT", + "total_supply": "1000000", + } + assert smart_contract.abi == {"abi": "data"} + assert smart_contract.transaction.status.value == "complete" + assert ( + smart_contract.transaction.transaction_link + == "https://sepolia.basescan.org/tx/0xtransactionlink" + ) + assert smart_contract.transaction.transaction_hash == "0xtransactionhash" + + +@patch("cdp.Cdp.api_clients") +def test_create_smart_contract(mock_api_clients, smart_contract_factory): + """Test the creation of a SmartContract object.""" + mock_create_contract = Mock() + mock_create_contract.return_value = smart_contract_factory()._model + mock_api_clients.smart_contracts.create_smart_contract = mock_create_contract + + smart_contract = SmartContract.create( + wallet_id="test-wallet-id", + address_id="0xaddressid", + type=SmartContract.Type.ERC20, + options=SmartContract.TokenContractOptions( + name="TestToken", symbol="TT", total_supply="1000000" + ), + ) + + assert isinstance(smart_contract, SmartContract) + mock_create_contract.assert_called_once_with( + wallet_id="test-wallet-id", + address_id="0xaddressid", + create_smart_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_broadcast_smart_contract(mock_api_clients, smart_contract_factory): + """Test the broadcasting of a SmartContract object.""" + smart_contract = smart_contract_factory(status="signed") + mock_broadcast = Mock(return_value=smart_contract_factory(status="broadcast")._model) + mock_api_clients.smart_contracts.deploy_smart_contract = mock_broadcast + + response = smart_contract.broadcast() + + assert isinstance(response, SmartContract) + mock_broadcast.assert_called_once_with( + wallet_id=smart_contract.wallet_id, + address_id=smart_contract.deployer_address, + smart_contract_id=smart_contract.smart_contract_id, + deploy_smart_contract_request=ANY, + ) + + +def test_broadcast_unsigned_smart_contract(smart_contract_factory): + """Test the broadcasting of an unsigned SmartContract object.""" + smart_contract = smart_contract_factory(status="pending") + with pytest.raises(ValueError, match="Cannot broadcast unsigned SmartContract deployment"): + smart_contract.broadcast() + + +@patch("cdp.Cdp.api_clients") +def test_reload_smart_contract(mock_api_clients, smart_contract_factory): + """Test the reloading of a SmartContract object.""" + smart_contract = smart_contract_factory(status="pending") + complete_contract = smart_contract_factory(status="complete") + mock_get_contract = Mock() + mock_api_clients.smart_contracts.get_smart_contract = mock_get_contract + mock_get_contract.return_value = complete_contract._model + + smart_contract.reload() + + mock_get_contract.assert_called_once_with( + wallet_id=smart_contract.wallet_id, + address_id=smart_contract.deployer_address, + smart_contract_id=smart_contract.smart_contract_id, + ) + assert smart_contract.transaction.status.value == "complete" + + +@patch("cdp.Cdp.api_clients") +@patch("cdp.smart_contract.time.sleep") +@patch("cdp.smart_contract.time.time") +def test_wait_for_smart_contract(mock_time, mock_sleep, mock_api_clients, smart_contract_factory): + """Test the waiting for a SmartContract object to complete.""" + pending_contract = smart_contract_factory(status="pending") + complete_contract = smart_contract_factory(status="complete") + mock_get_contract = Mock() + mock_api_clients.smart_contracts.get_smart_contract = mock_get_contract + mock_get_contract.side_effect = [pending_contract._model, complete_contract._model] + + mock_time.side_effect = [0, 0.2, 0.4] + + result = pending_contract.wait(interval_seconds=0.2, timeout_seconds=1) + + assert result.transaction.status.value == "complete" + mock_get_contract.assert_called_with( + wallet_id=pending_contract.wallet_id, + address_id=pending_contract.deployer_address, + smart_contract_id=pending_contract.smart_contract_id, + ) + assert mock_get_contract.call_count == 2 + mock_sleep.assert_has_calls([call(0.2)] * 2) + assert mock_time.call_count == 3 + + +@patch("cdp.Cdp.api_clients") +@patch("cdp.smart_contract.time.sleep") +@patch("cdp.smart_contract.time.time") +def test_wait_for_smart_contract_timeout( + mock_time, mock_sleep, mock_api_clients, smart_contract_factory +): + """Test the waiting for a SmartContract object to complete with a timeout.""" + pending_contract = smart_contract_factory(status="pending") + mock_get_contract = Mock(return_value=pending_contract._model) + mock_api_clients.smart_contracts.get_smart_contract = mock_get_contract + + mock_time.side_effect = [0, 0.5, 1.0, 1.5, 2.0, 2.5] + + with pytest.raises(TimeoutError, match="SmartContract deployment timed out"): + pending_contract.wait(interval_seconds=0.5, timeout_seconds=2) + + assert mock_get_contract.call_count == 5 + mock_sleep.assert_has_calls([call(0.5)] * 4) + assert mock_time.call_count == 6 + + +def test_sign_smart_contract_invalid_key(smart_contract_factory): + """Test the signing of a SmartContract object with an invalid key.""" + smart_contract = smart_contract_factory() + with pytest.raises(ValueError, match="key must be a LocalAccount"): + smart_contract.sign("invalid_key") + + +def test_smart_contract_str_representation(smart_contract_factory): + """Test the string representation of a SmartContract object.""" + smart_contract = smart_contract_factory() + expected_str = ( + f"SmartContract: (smart_contract_id: {smart_contract.smart_contract_id}, " + f"wallet_id: {smart_contract.wallet_id}, network_id: {smart_contract.network_id}, " + f"contract_address: {smart_contract.contract_address}, type: {smart_contract.type}, " + f"transaction_hash: {smart_contract.transaction.transaction_hash}, " + f"transaction_link: {smart_contract.transaction.transaction_link}, " + f"status: {smart_contract.transaction.status})" + ) + assert str(smart_contract) == expected_str + + +def test_smart_contract_repr(smart_contract_factory): + """Test the representation of a SmartContract object.""" + smart_contract = smart_contract_factory() + assert repr(smart_contract) == str(smart_contract) diff --git a/tests/test_wallet.py b/tests/test_wallet.py index 60cb9db..d7b4133 100644 --- a/tests/test_wallet.py +++ b/tests/test_wallet.py @@ -12,6 +12,7 @@ from cdp.client.models.wallet import Wallet as WalletModel from cdp.contract_invocation import ContractInvocation from cdp.payload_signature import PayloadSignature +from cdp.smart_contract import SmartContract from cdp.trade import Trade from cdp.transfer import Transfer from cdp.wallet import Wallet @@ -535,3 +536,171 @@ def test_wallet_fetch(mock_api_clients, wallet_factory): assert isinstance(fetched_wallet, Wallet) assert fetched_wallet.id == "fetched-wallet-id" mock_get_wallet.assert_called_once_with("fetched-wallet-id") + + +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_deploy_token(wallet_factory): + """Test the deploy_token method of a Wallet.""" + wallet = wallet_factory() + mock_default_address = Mock(spec=WalletAddress) + mock_smart_contract = Mock(spec=SmartContract) + mock_default_address.deploy_token.return_value = mock_smart_contract + + with patch.object( + Wallet, "default_address", new_callable=PropertyMock + ) as mock_default_address_prop: + mock_default_address_prop.return_value = mock_default_address + + smart_contract = wallet.deploy_token(name="TestToken", symbol="TT", total_supply="1000000") + + assert isinstance(smart_contract, SmartContract) + mock_default_address.deploy_token.assert_called_once_with("TestToken", "TT", "1000000") + + +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_deploy_nft(wallet_factory): + """Test the deploy_nft method of a Wallet.""" + wallet = wallet_factory() + mock_default_address = Mock(spec=WalletAddress) + mock_smart_contract = Mock(spec=SmartContract) + mock_default_address.deploy_nft.return_value = mock_smart_contract + + with patch.object( + Wallet, "default_address", new_callable=PropertyMock + ) as mock_default_address_prop: + mock_default_address_prop.return_value = mock_default_address + + smart_contract = wallet.deploy_nft( + name="TestNFT", symbol="TNFT", base_uri="https://example.com/nft/" + ) + + assert isinstance(smart_contract, SmartContract) + mock_default_address.deploy_nft.assert_called_once_with( + "TestNFT", "TNFT", "https://example.com/nft/" + ) + + +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_deploy_multi_token(wallet_factory): + """Test the deploy_multi_token method of a Wallet.""" + wallet = wallet_factory() + mock_default_address = Mock(spec=WalletAddress) + mock_smart_contract = Mock(spec=SmartContract) + mock_default_address.deploy_multi_token.return_value = mock_smart_contract + + with patch.object( + Wallet, "default_address", new_callable=PropertyMock + ) as mock_default_address_prop: + mock_default_address_prop.return_value = mock_default_address + + smart_contract = wallet.deploy_multi_token(uri="https://example.com/multi-token/{id}.json") + + assert isinstance(smart_contract, SmartContract) + mock_default_address.deploy_multi_token.assert_called_once_with( + "https://example.com/multi-token/{id}.json" + ) + + +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_deploy_token_no_default_address(wallet_factory): + """Test the deploy_token method of a Wallet with no default address.""" + wallet = wallet_factory() + + with patch.object( + Wallet, "default_address", new_callable=PropertyMock + ) as mock_default_address_prop: + mock_default_address_prop.return_value = None + + with pytest.raises(ValueError, match="Default address does not exist"): + wallet.deploy_token(name="TestToken", symbol="TT", total_supply="1000000") + + +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_deploy_nft_no_default_address(wallet_factory): + """Test the deploy_nft method of a Wallet with no default address.""" + wallet = wallet_factory() + + with patch.object( + Wallet, "default_address", new_callable=PropertyMock + ) as mock_default_address_prop: + mock_default_address_prop.return_value = None + + with pytest.raises(ValueError, match="Default address does not exist"): + wallet.deploy_nft(name="TestNFT", symbol="TNFT", base_uri="https://example.com/nft/") + + +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_deploy_multi_token_no_default_address(wallet_factory): + """Test the deploy_multi_token method of a Wallet with no default address.""" + wallet = wallet_factory() + + with patch.object( + Wallet, "default_address", new_callable=PropertyMock + ) as mock_default_address_prop: + mock_default_address_prop.return_value = None + + with pytest.raises(ValueError, match="Default address does not exist"): + wallet.deploy_multi_token(uri="https://example.com/multi-token/{id}.json") + + +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_deploy_token_with_server_signer(wallet_factory): + """Test the deploy_token method of a Wallet with server-signer.""" + wallet = wallet_factory() + mock_default_address = Mock(spec=WalletAddress) + mock_smart_contract = Mock(spec=SmartContract) + mock_default_address.deploy_token.return_value = mock_smart_contract + + with patch.object( + Wallet, "default_address", new_callable=PropertyMock + ) as mock_default_address_prop: + mock_default_address_prop.return_value = mock_default_address + + smart_contract = wallet.deploy_token(name="TestToken", symbol="TT", total_supply="1000000") + + assert isinstance(smart_contract, SmartContract) + mock_default_address.deploy_token.assert_called_once_with("TestToken", "TT", "1000000") + + +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_deploy_nft_with_server_signer(wallet_factory): + """Test the deploy_nft method of a Wallet with server-signer.""" + wallet = wallet_factory() + mock_default_address = Mock(spec=WalletAddress) + mock_smart_contract = Mock(spec=SmartContract) + mock_default_address.deploy_nft.return_value = mock_smart_contract + + with patch.object( + Wallet, "default_address", new_callable=PropertyMock + ) as mock_default_address_prop: + mock_default_address_prop.return_value = mock_default_address + + smart_contract = wallet.deploy_nft( + name="TestNFT", symbol="TNFT", base_uri="https://example.com/nft/" + ) + + assert isinstance(smart_contract, SmartContract) + mock_default_address.deploy_nft.assert_called_once_with( + "TestNFT", "TNFT", "https://example.com/nft/" + ) + + +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_deploy_multi_token_with_server_signer(wallet_factory): + """Test the deploy_multi_token method of a Wallet with server-signer.""" + wallet = wallet_factory() + mock_default_address = Mock(spec=WalletAddress) + mock_smart_contract = Mock(spec=SmartContract) + mock_default_address.deploy_multi_token.return_value = mock_smart_contract + + with patch.object( + Wallet, "default_address", new_callable=PropertyMock + ) as mock_default_address_prop: + mock_default_address_prop.return_value = mock_default_address + + smart_contract = wallet.deploy_multi_token(uri="https://example.com/multi-token/{id}.json") + + assert isinstance(smart_contract, SmartContract) + mock_default_address.deploy_multi_token.assert_called_once_with( + "https://example.com/multi-token/{id}.json" + ) diff --git a/tests/test_wallet_address.py b/tests/test_wallet_address.py index 9772714..49835d0 100644 --- a/tests/test_wallet_address.py +++ b/tests/test_wallet_address.py @@ -11,9 +11,15 @@ from cdp.client.models.address import Address as AddressModel from cdp.client.models.asset import Asset as AssetModel from cdp.client.models.balance import Balance as BalanceModel +from cdp.client.models.create_smart_contract_request import CreateSmartContractRequest +from cdp.client.models.multi_token_contract_options import MultiTokenContractOptions +from cdp.client.models.nft_contract_options import NFTContractOptions +from cdp.client.models.smart_contract_options import SmartContractOptions +from cdp.client.models.token_contract_options import TokenContractOptions from cdp.contract_invocation import ContractInvocation from cdp.errors import InsufficientFundsError from cdp.payload_signature import PayloadSignature +from cdp.smart_contract import SmartContract from cdp.trade import Trade from cdp.transfer import Transfer from cdp.wallet_address import WalletAddress @@ -228,7 +234,7 @@ def test_transfer_broadcast_api_error( address_id=wallet_address_with_key.address_id, asset_id="eth", ) - mock_transfer.createassert_called_once_with( + mock_transfer.create.assert_called_once_with( address_id=wallet_address_with_key.address_id, amount=Decimal("1.0"), asset_id="eth", @@ -513,9 +519,8 @@ def test_invoke_contract_broadcast_api_error( @patch("cdp.wallet_address.PayloadSignature") -@patch("cdp.Cdp.api_clients") @patch("cdp.Cdp.use_server_signer", True) -def test_sign_payload_with_server_signer(mock_api_clients, mock_payload_signature, wallet_address): +def test_sign_payload_with_server_signer(mock_payload_signature, wallet_address): """Test the sign_payload method with a server signer.""" mock_payload_signature_instance = Mock(spec=PayloadSignature) mock_payload_signature.create.return_value = mock_payload_signature_instance @@ -533,9 +538,8 @@ def test_sign_payload_with_server_signer(mock_api_clients, mock_payload_signatur @patch("cdp.wallet_address.to_hex", Mock(return_value="0xsignature")) @patch("cdp.wallet_address.PayloadSignature") -@patch("cdp.Cdp.api_clients") @patch("cdp.Cdp.use_server_signer", False) -def test_sign_payload(mock_api_clients, mock_payload_signature, wallet_address_with_key): +def test_sign_payload(mock_payload_signature, wallet_address_with_key): """Test the sign_payload method.""" mock_payload_signature_instance = Mock(spec=PayloadSignature) mock_payload_signature.create.return_value = mock_payload_signature_instance @@ -563,9 +567,8 @@ def test_sign_payload(mock_api_clients, mock_payload_signature, wallet_address_w @patch("cdp.wallet_address.to_hex", Mock(return_value="0xsignature")) @patch("cdp.wallet_address.PayloadSignature") -@patch("cdp.Cdp.api_clients") @patch("cdp.Cdp.use_server_signer", False) -def test_sign_payload_api_error(mock_api_clients, mock_payload_signature, wallet_address_with_key): +def test_sign_payload_api_error(mock_payload_signature, wallet_address_with_key): """Test the sign_payload method.""" mock_signature = Mock(spec=SignedMessage) mock_signature.signature = "0xsignature" @@ -629,3 +632,302 @@ def test_repr(wallet_address): """Test the repr representation of a WalletAddress.""" expected_repr = "WalletAddress: (address_id: 0x1234567890123456789012345678901234567890, wallet_id: test-wallet-id-1, network_id: base-sepolia)" assert repr(wallet_address) == expected_repr + + +@patch("cdp.Cdp.api_clients") +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_address_deploy_token_total_supply_string(mock_api_clients, wallet_address): + """Test the deploy_token method of a WalletAddress with a string total_supply.""" + mock_smart_contract = Mock(spec=SmartContract) + mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract + + smart_contract = wallet_address.deploy_token( + name="TestToken", symbol="TT", total_supply="1000000" + ) + + assert isinstance(smart_contract, SmartContract) + mock_api_clients.smart_contracts.create_smart_contract.assert_called_once_with( + wallet_id=wallet_address.wallet_id, + address_id=wallet_address.address_id, + create_smart_contract_request=CreateSmartContractRequest( + type="erc20", + options=SmartContractOptions( + actual_instance=TokenContractOptions( + name="TestToken", symbol="TT", total_supply="1000000" + ) + ), + ), + ) + + +@patch("cdp.Cdp.api_clients") +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_address_deploy_token_total_supply_number(mock_api_clients, wallet_address): + """Test the deploy_token method of a WalletAddress with a number total_supply.""" + mock_smart_contract = Mock(spec=SmartContract) + mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract + + smart_contract = wallet_address.deploy_token( + name="TestToken", symbol="TT", total_supply=1000000 + ) + + assert isinstance(smart_contract, SmartContract) + mock_api_clients.smart_contracts.create_smart_contract.assert_called_once_with( + wallet_id=wallet_address.wallet_id, + address_id=wallet_address.address_id, + create_smart_contract_request=CreateSmartContractRequest( + type="erc20", + options=SmartContractOptions( + actual_instance=TokenContractOptions( + name="TestToken", symbol="TT", total_supply="1000000" + ) + ), + ), + ) + + +@patch("cdp.Cdp.api_clients") +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_address_deploy_token_total_supply_decimal(mock_api_clients, wallet_address): + """Test the deploy_token method of a WalletAddress with a Decimal total_supply.""" + mock_smart_contract = Mock(spec=SmartContract) + mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract + + smart_contract = wallet_address.deploy_token( + name="TestToken", symbol="TT", total_supply=Decimal("1000000.5") + ) + + assert isinstance(smart_contract, SmartContract) + mock_api_clients.smart_contracts.create_smart_contract.assert_called_once_with( + wallet_id=wallet_address.wallet_id, + address_id=wallet_address.address_id, + create_smart_contract_request=CreateSmartContractRequest( + type="erc20", + options=SmartContractOptions( + actual_instance=TokenContractOptions( + name="TestToken", symbol="TT", total_supply="1000000.5" + ) + ), + ), + ) + + +@patch("cdp.Cdp.api_clients") +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_address_deploy_nft(mock_api_clients, wallet_address): + """Test the deploy_nft method of a WalletAddress.""" + mock_smart_contract = Mock(spec=SmartContract) + mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract + + smart_contract = wallet_address.deploy_nft( + name="TestNFT", symbol="TNFT", base_uri="https://example.com/nft/" + ) + + assert isinstance(smart_contract, SmartContract) + mock_api_clients.smart_contracts.create_smart_contract.assert_called_once_with( + wallet_id=wallet_address.wallet_id, + address_id=wallet_address.address_id, + create_smart_contract_request=CreateSmartContractRequest( + type="erc721", + options=SmartContractOptions( + actual_instance=NFTContractOptions( + name="TestNFT", symbol="TNFT", base_uri="https://example.com/nft/" + ) + ), + ), + ) + + +@patch("cdp.Cdp.api_clients") +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_address_deploy_multi_token(mock_api_clients, wallet_address): + """Test the deploy_multi_token method of a WalletAddress.""" + mock_smart_contract = Mock(spec=SmartContract) + mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract + + smart_contract = wallet_address.deploy_multi_token( + uri="https://example.com/multi-token/{id}.json" + ) + + assert isinstance(smart_contract, SmartContract) + mock_api_clients.smart_contracts.create_smart_contract.assert_called_once_with( + wallet_id=wallet_address.wallet_id, + address_id=wallet_address.address_id, + create_smart_contract_request=CreateSmartContractRequest( + type="erc1155", + options=SmartContractOptions( + actual_instance=MultiTokenContractOptions( + uri="https://example.com/multi-token/{id}.json" + ) + ), + ), + ) + + +@patch("cdp.Cdp.api_clients") +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_address_deploy_token_with_server_signer(mock_api_clients, wallet_address): + """Test the deploy_token method of a WalletAddress with server signer.""" + mock_smart_contract = Mock(spec=SmartContract) + mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract + + smart_contract = wallet_address.deploy_token( + name="TestToken", symbol="TT", total_supply="1000000" + ) + + assert isinstance(smart_contract, SmartContract) + mock_api_clients.smart_contracts.create_smart_contract.assert_called_once_with( + wallet_id=wallet_address.wallet_id, + address_id=wallet_address.address_id, + create_smart_contract_request=CreateSmartContractRequest( + type="erc20", + options=SmartContractOptions( + actual_instance=TokenContractOptions( + name="TestToken", symbol="TT", total_supply="1000000" + ) + ), + ), + ) + # Verify that sign and broadcast methods are not called when using server signer + mock_smart_contract.sign.assert_not_called() + mock_smart_contract.broadcast.assert_not_called() + + +@patch("cdp.Cdp.api_clients") +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_address_deploy_nft_with_server_signer(mock_api_clients, wallet_address): + """Test the deploy_nft method of a WalletAddress with server signer.""" + mock_smart_contract = Mock(spec=SmartContract) + mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract + + smart_contract = wallet_address.deploy_nft( + name="TestNFT", symbol="TNFT", base_uri="https://example.com/nft/" + ) + + assert isinstance(smart_contract, SmartContract) + mock_api_clients.smart_contracts.create_smart_contract.assert_called_once_with( + wallet_id=wallet_address.wallet_id, + address_id=wallet_address.address_id, + create_smart_contract_request=CreateSmartContractRequest( + type="erc721", + options=SmartContractOptions( + actual_instance=NFTContractOptions( + name="TestNFT", symbol="TNFT", base_uri="https://example.com/nft/" + ) + ), + ), + ) + # Verify that sign and broadcast methods are not called when using server signer + mock_smart_contract.sign.assert_not_called() + mock_smart_contract.broadcast.assert_not_called() + + +@patch("cdp.Cdp.api_clients") +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_address_deploy_multi_token_with_server_signer(mock_api_clients, wallet_address): + """Test the deploy_multi_token method of a WalletAddress with server signer.""" + mock_smart_contract = Mock(spec=SmartContract) + mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract + + smart_contract = wallet_address.deploy_multi_token( + uri="https://example.com/multi-token/{id}.json" + ) + + assert isinstance(smart_contract, SmartContract) + mock_api_clients.smart_contracts.create_smart_contract.assert_called_once_with( + wallet_id=wallet_address.wallet_id, + address_id=wallet_address.address_id, + create_smart_contract_request=CreateSmartContractRequest( + type="erc1155", + options=SmartContractOptions( + actual_instance=MultiTokenContractOptions( + uri="https://example.com/multi-token/{id}.json" + ) + ), + ), + ) + # Verify that sign and broadcast methods are not called when using server signer + mock_smart_contract.sign.assert_not_called() + mock_smart_contract.broadcast.assert_not_called() + + +@patch("cdp.wallet_address.SmartContract") +def test_deploy_token_api_error(mock_smart_contract, wallet_address_with_key): + """Test the deploy_token method raises an error when the create API call fails.""" + mock_smart_contract.create.side_effect = Exception("API Error") + + with pytest.raises(Exception, match="API Error"): + wallet_address_with_key.deploy_token(name="TestToken", symbol="TT", total_supply="1000000") + + mock_smart_contract.create.assert_called_once() + + +@patch("cdp.wallet_address.SmartContract") +def test_deploy_token_broadcast_api_error(mock_smart_contract, wallet_address_with_key): + """Test the deploy_token method raises an error when the broadcast API call fails.""" + mock_smart_contract_instance = Mock(spec=SmartContract) + mock_smart_contract.create.return_value = mock_smart_contract_instance + mock_smart_contract_instance.broadcast.side_effect = Exception("API Error") + + with pytest.raises(Exception, match="API Error"): + wallet_address_with_key.deploy_token(name="TestToken", symbol="TT", total_supply="1000000") + + mock_smart_contract.create.assert_called_once() + mock_smart_contract_instance.sign.assert_called_once_with(wallet_address_with_key.key) + mock_smart_contract_instance.broadcast.assert_called_once() + + +@patch("cdp.wallet_address.SmartContract") +def test_deploy_nft_api_error(mock_smart_contract, wallet_address_with_key): + """Test the deploy_nft method raises an error when the create API call fails.""" + mock_smart_contract.create.side_effect = Exception("API Error") + + with pytest.raises(Exception, match="API Error"): + wallet_address_with_key.deploy_nft( + name="TestNFT", symbol="TNFT", base_uri="https://example.com/nft/" + ) + + mock_smart_contract.create.assert_called_once() + + +@patch("cdp.wallet_address.SmartContract") +def test_deploy_nft_broadcast_api_error(mock_smart_contract, wallet_address_with_key): + """Test the deploy_nft method raises an error when the broadcast API call fails.""" + mock_smart_contract_instance = Mock(spec=SmartContract) + mock_smart_contract.create.return_value = mock_smart_contract_instance + mock_smart_contract_instance.broadcast.side_effect = Exception("API Error") + + with pytest.raises(Exception, match="API Error"): + wallet_address_with_key.deploy_nft( + name="TestNFT", symbol="TNFT", base_uri="https://example.com/nft/" + ) + + mock_smart_contract.create.assert_called_once() + mock_smart_contract_instance.sign.assert_called_once_with(wallet_address_with_key.key) + mock_smart_contract_instance.broadcast.assert_called_once() + + +@patch("cdp.wallet_address.SmartContract") +def test_deploy_multi_token_api_error(mock_smart_contract, wallet_address_with_key): + """Test the deploy_multi_token method raises an error when the create API call fails.""" + mock_smart_contract.create.side_effect = Exception("API Error") + + with pytest.raises(Exception, match="API Error"): + wallet_address_with_key.deploy_multi_token(uri="https://example.com/multi-token/{id}.json") + + mock_smart_contract.create.assert_called_once() + + +@patch("cdp.wallet_address.SmartContract") +def test_deploy_multi_token_broadcast_api_error(mock_smart_contract, wallet_address_with_key): + """Test the deploy_multi_token method raises an error when the broadcast API call fails.""" + mock_smart_contract_instance = Mock(spec=SmartContract) + mock_smart_contract.create.return_value = mock_smart_contract_instance + mock_smart_contract_instance.broadcast.side_effect = Exception("API Error") + + with pytest.raises(Exception, match="API Error"): + wallet_address_with_key.deploy_multi_token(uri="https://example.com/multi-token/{id}.json") + + mock_smart_contract.create.assert_called_once() + mock_smart_contract_instance.sign.assert_called_once_with(wallet_address_with_key.key) + mock_smart_contract_instance.broadcast.assert_called_once() From dd045a36a458d3d69656bce7fec8a0da4dae60c0 Mon Sep 17 00:00:00 2001 From: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> Date: Tue, 1 Oct 2024 17:42:04 -0400 Subject: [PATCH 13/40] chore(PSDK-540): Move test factories under a factories package (#21) --- tests/conftest.py | 7 + tests/factories/__init__.py | 0 tests/factories/address_factory.py | 16 ++ tests/factories/asset_factory.py | 25 ++ tests/factories/balance_factory.py | 30 ++ .../factories/contract_invocation_factory.py | 36 +++ tests/factories/payload_signature_factory.py | 34 +++ tests/factories/smart_contract_factory.py | 40 +++ tests/factories/sponsored_send_factory.py | 25 ++ tests/factories/trade_factory.py | 47 ++++ tests/factories/transaction_factory.py | 40 +++ tests/factories/transfer_factory.py | 47 ++++ tests/factories/wallet_address_factory.py | 45 +++ tests/factories/wallet_factory.py | 60 ++++ tests/test_address.py | 73 ++--- tests/test_asset.py | 72 ++--- tests/test_balance.py | 70 ++--- tests/test_contract_invocation.py | 80 ------ tests/test_payload_signature.py | 31 --- tests/test_smart_contract.py | 61 ---- tests/test_trade.py | 91 ------ tests/test_transaction.py | 114 ++++---- tests/test_transfer.py | 113 -------- tests/test_wallet.py | 90 ------ tests/test_wallet_address.py | 263 ++++++++++++------ 25 files changed, 781 insertions(+), 729 deletions(-) create mode 100644 tests/conftest.py create mode 100644 tests/factories/__init__.py create mode 100644 tests/factories/address_factory.py create mode 100644 tests/factories/asset_factory.py create mode 100644 tests/factories/balance_factory.py create mode 100644 tests/factories/contract_invocation_factory.py create mode 100644 tests/factories/payload_signature_factory.py create mode 100644 tests/factories/smart_contract_factory.py create mode 100644 tests/factories/sponsored_send_factory.py create mode 100644 tests/factories/trade_factory.py create mode 100644 tests/factories/transaction_factory.py create mode 100644 tests/factories/transfer_factory.py create mode 100644 tests/factories/wallet_address_factory.py create mode 100644 tests/factories/wallet_factory.py diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..627976e --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,7 @@ +import os + +factory_modules = [ + f[:-3] for f in os.listdir("./tests/factories") if f.endswith(".py") and f != "__init__.py" +] + +pytest_plugins = [f"tests.factories.{module_name}" for module_name in factory_modules] diff --git a/tests/factories/__init__.py b/tests/factories/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/factories/address_factory.py b/tests/factories/address_factory.py new file mode 100644 index 0000000..6b0c4e6 --- /dev/null +++ b/tests/factories/address_factory.py @@ -0,0 +1,16 @@ +import pytest + +from cdp.address import Address + + +@pytest.fixture +def address_factory(): + """Create and return a factory for Address fixtures.""" + + def _create_address( + network_id="base-sepolia", + address_id="0x1234567890123456789012345678901234567890", + ): + return Address(network_id, address_id) + + return _create_address diff --git a/tests/factories/asset_factory.py b/tests/factories/asset_factory.py new file mode 100644 index 0000000..51d92a0 --- /dev/null +++ b/tests/factories/asset_factory.py @@ -0,0 +1,25 @@ +import pytest + +from cdp.asset import Asset +from cdp.client.models.asset import Asset as AssetModel + + +@pytest.fixture +def asset_model_factory(): + """Create and return a factory for creating AssetModel fixtures.""" + + def _create_asset_model(network_id="base-sepolia", asset_id="usdc", decimals=6): + return AssetModel(network_id=network_id, asset_id=asset_id, decimals=decimals) + + return _create_asset_model + + +@pytest.fixture +def asset_factory(asset_model_factory): + """Create and return a factory for creating Asset fixtures.""" + + def _create_asset(network_id="base-sepolia", asset_id="usdc", decimals=6): + asset_model = asset_model_factory(network_id, asset_id, decimals) + return Asset.from_model(asset_model) + + return _create_asset diff --git a/tests/factories/balance_factory.py b/tests/factories/balance_factory.py new file mode 100644 index 0000000..e665149 --- /dev/null +++ b/tests/factories/balance_factory.py @@ -0,0 +1,30 @@ +import pytest + +from cdp.balance import Balance +from cdp.client.models.balance import Balance as BalanceModel + + +@pytest.fixture +def balance_model_factory(asset_model_factory): + """Create and return a factory for creating BalanceModel fixtures.""" + + def _create_balance_model( + amount="1000000000000000000", network_id="base-sepolia", asset_id="eth", decimals=18 + ): + asset_model = asset_model_factory(network_id, asset_id, decimals) + return BalanceModel(amount=amount, asset=asset_model) + + return _create_balance_model + + +@pytest.fixture +def balance_factory(asset_factory): + """Create and return a factory for creating Balance fixtures.""" + + def _create_balance( + amount="1000000000000000000", network_id="base-sepolia", asset_id="eth", decimals=18 + ): + asset = asset_factory(network_id="base-sepolia", asset_id="eth", decimals=18) + return Balance(amount, asset) + + return _create_balance diff --git a/tests/factories/contract_invocation_factory.py b/tests/factories/contract_invocation_factory.py new file mode 100644 index 0000000..f188872 --- /dev/null +++ b/tests/factories/contract_invocation_factory.py @@ -0,0 +1,36 @@ +import pytest + +from cdp.client.models.contract_invocation import ContractInvocation as ContractInvocationModel +from cdp.contract_invocation import ContractInvocation + + +@pytest.fixture +def contract_invocation_model_factory(transaction_model_factory): + """Create and return a factory for creating ContractInvocationModel fixtures.""" + + def _create_contract_invocation_model(status="complete"): + return ContractInvocationModel( + network_id="base-sepolia", + wallet_id="test-wallet-id", + address_id="0xaddressid", + contract_invocation_id="test-invocation-id", + contract_address="0xcontractaddress", + method="testMethod", + args='{"arg1": "value1"}', + abi='{"abi": "data"}', + amount="1", + transaction=transaction_model_factory(status), + ) + + return _create_contract_invocation_model + + +@pytest.fixture +def contract_invocation_factory(contract_invocation_model_factory): + """Create and return a factory for creating ContractInvocation fixtures.""" + + def _create_contract_invocation(status="complete"): + contract_invocation_model = contract_invocation_model_factory(status) + return ContractInvocation(contract_invocation_model) + + return _create_contract_invocation diff --git a/tests/factories/payload_signature_factory.py b/tests/factories/payload_signature_factory.py new file mode 100644 index 0000000..55323fd --- /dev/null +++ b/tests/factories/payload_signature_factory.py @@ -0,0 +1,34 @@ +import pytest + +from cdp.client.models.payload_signature import PayloadSignature as PayloadSignatureModel +from cdp.payload_signature import PayloadSignature + + +@pytest.fixture +def payload_signature_model_factory(): + """Create and return a factory for creating PayloadSignatureModel fixtures.""" + + def _create_payload_signature_model(status="signed"): + payload_signature_model = PayloadSignatureModel( + payload_signature_id="test-payload-signature-id", + address_id="0xaddressid", + wallet_id="test-wallet-id", + unsigned_payload="0xunsignedpayload", + signature="0xsignature" if status == "signed" else None, + status=status, + ) + + return payload_signature_model + + return _create_payload_signature_model + + +@pytest.fixture +def payload_signature_factory(payload_signature_model_factory): + """Create and return a factory for creating PayloadSignature fixtures.""" + + def _create_payload_signature(status="signed"): + payload_signature_model = payload_signature_model_factory(status) + return PayloadSignature(payload_signature_model) + + return _create_payload_signature diff --git a/tests/factories/smart_contract_factory.py b/tests/factories/smart_contract_factory.py new file mode 100644 index 0000000..4350848 --- /dev/null +++ b/tests/factories/smart_contract_factory.py @@ -0,0 +1,40 @@ +import pytest + +from cdp.client.models.smart_contract import SmartContract as SmartContractModel +from cdp.client.models.smart_contract_options import SmartContractOptions +from cdp.client.models.token_contract_options import TokenContractOptions +from cdp.smart_contract import SmartContract + + +@pytest.fixture +def smart_contract_model_factory(transaction_model_factory): + """Create and return a factory for creating SmartContractModel fixtures.""" + + def _create_smart_contract_model(status="complete"): + token_options = TokenContractOptions(name="TestToken", symbol="TT", total_supply="1000000") + smart_contract_options = SmartContractOptions(actual_instance=token_options) + + return SmartContractModel( + smart_contract_id="test-contract-id", + network_id="base-sepolia", + wallet_id="test-wallet-id", + contract_address="0xcontractaddress", + deployer_address="0xdeployeraddress", + type="erc20", + options=smart_contract_options, + abi='{"abi": "data"}', + transaction=transaction_model_factory(status), + ) + + return _create_smart_contract_model + + +@pytest.fixture +def smart_contract_factory(smart_contract_model_factory): + """Create and return a factory for creating SmartContract fixtures.""" + + def _create_smart_contract(status="complete"): + smart_contract_model = smart_contract_model_factory(status) + return SmartContract(smart_contract_model) + + return _create_smart_contract diff --git a/tests/factories/sponsored_send_factory.py b/tests/factories/sponsored_send_factory.py new file mode 100644 index 0000000..d549a92 --- /dev/null +++ b/tests/factories/sponsored_send_factory.py @@ -0,0 +1,25 @@ +import pytest + +from cdp.client.models.sponsored_send import SponsoredSend as SponsoredSendModel + + +@pytest.fixture +def sponsored_send_model_factory(): + """Create and return a factory for creating SponsoredSendModel fixtures.""" + + def _create_sponsored_send_model(status="complete"): + status = "submitted" if status == "broadcast" else status + + return SponsoredSendModel( + to_address_id="0xdestination", + raw_typed_data="0xtypeddata", + typed_data_hash="0xtypeddatahash", + signature="0xsignature" if status in ["signed", "submitted", "complete"] else None, + transaction_hash="0xtransactionhash" if status == "complete" else None, + transaction_link="https://sepolia.basescan.org/tx/0xtransactionlink" + if status == "complete" + else None, + status=status, + ) + + return _create_sponsored_send_model diff --git a/tests/factories/trade_factory.py b/tests/factories/trade_factory.py new file mode 100644 index 0000000..975f583 --- /dev/null +++ b/tests/factories/trade_factory.py @@ -0,0 +1,47 @@ +import pytest + +from cdp.client.models.trade import Trade as TradeModel +from cdp.trade import Trade + + +@pytest.fixture +def trade_model_factory(asset_model_factory, transaction_model_factory): + """Create and return a factory for creating TradeModel fixtures.""" + + def _create_trade_model( + status="complete", + from_asset_id="usdc", + to_asset_id="eth", + from_asset_decimals=6, + to_asset_decimals=18, + ): + from_asset_model = asset_model_factory(asset_id=from_asset_id, decimals=from_asset_decimals) + to_asset_model = asset_model_factory(asset_id=to_asset_id, decimals=to_asset_decimals) + transaction_model = transaction_model_factory(status) + approve_transaction_model = transaction_model_factory(status) + + return TradeModel( + network_id="base-sepolia", + wallet_id="test-wallet-id", + address_id="0xaddressid", + trade_id="test-trade-id", + from_asset=from_asset_model, + to_asset=to_asset_model, + from_amount="1000000", # 1 USDC + to_amount="500000000000000000", # 0.5 ETH + transaction=transaction_model, + approve_transaction=approve_transaction_model, + ) + + return _create_trade_model + + +@pytest.fixture +def trade_factory(trade_model_factory): + """Create and return a factory for creating Trade fixtures.""" + + def _create_trade(status="complete", from_asset_id="usdc", to_asset_id="eth"): + trade_model = trade_model_factory(status, from_asset_id, to_asset_id) + return Trade(trade_model) + + return _create_trade diff --git a/tests/factories/transaction_factory.py b/tests/factories/transaction_factory.py new file mode 100644 index 0000000..5fd9712 --- /dev/null +++ b/tests/factories/transaction_factory.py @@ -0,0 +1,40 @@ +import pytest + +from cdp.client.models.transaction import Transaction as TransactionModel +from cdp.transaction import Transaction + + +@pytest.fixture +def transaction_model_factory(): + """Create and return a factory for creating TransactionModel fixtures.""" + + def _create_transaction_model(status="complete"): + return TransactionModel( + network_id="base-sepolia", + transaction_hash="0xtransactionhash", + from_address_id="0xaddressid", + to_address_id="0xdestination", + unsigned_payload="0xunsignedpayload", + signed_payload="0xsignedpayload" + if status in ["signed", "broadcast", "complete"] + else None, + status=status, + transaction_link="https://sepolia.basescan.org/tx/0xtransactionlink" + if status == "complete" + else None, + block_hash="0xblockhash" if status == "complete" else None, + block_height="123456" if status == "complete" else None, + ) + + return _create_transaction_model + + +@pytest.fixture +def transaction_factory(transaction_model_factory): + """Create and return a factory for creating Transaction fixtures.""" + + def _create_transaction(status="complete"): + model = transaction_model_factory(status) + return Transaction(model) + + return _create_transaction diff --git a/tests/factories/transfer_factory.py b/tests/factories/transfer_factory.py new file mode 100644 index 0000000..2ac26df --- /dev/null +++ b/tests/factories/transfer_factory.py @@ -0,0 +1,47 @@ +import pytest + +from cdp.client.models.transfer import Transfer as TransferModel +from cdp.transfer import Transfer + + +@pytest.fixture +def transfer_model_factory( + asset_model_factory, sponsored_send_model_factory, transaction_model_factory +): + """Create and return a factory for creating TransferModel fixtures.""" + + def _create_transfer_model(gasless=True, status="complete", asset_id="usdc"): + asset_model = asset_model_factory(asset_id=asset_id) + if gasless: + sponsored_send_model = sponsored_send_model_factory(status) + transaction_model = None + else: + sponsored_send_model = None + transaction_model = transaction_model_factory(status) + + return TransferModel( + network_id="base-sepolia", + wallet_id="test-wallet-id", + address_id="0xaddressid", + destination="0xdestination", + amount="1000000", # 1 USDC or 1 ETH in wei + asset_id=asset_model.asset_id, + transfer_id="test-transfer-id", + asset=asset_model, + gasless=gasless, + sponsored_send=sponsored_send_model, + transaction=transaction_model, + ) + + return _create_transfer_model + + +@pytest.fixture +def transfer_factory(transfer_model_factory): + """Create and return a factory for creating Transfer fixtures.""" + + def _create_transfer(gasless=True, status="complete", asset_id="usdc"): + transfer_model = transfer_model_factory(gasless, status, asset_id) + return Transfer(transfer_model) + + return _create_transfer diff --git a/tests/factories/wallet_address_factory.py b/tests/factories/wallet_address_factory.py new file mode 100644 index 0000000..23b15d7 --- /dev/null +++ b/tests/factories/wallet_address_factory.py @@ -0,0 +1,45 @@ +from unittest.mock import Mock + +import pytest +from eth_account.signers.local import LocalAccount + +from cdp.client.models.address import Address as AddressModel +from cdp.wallet_address import WalletAddress + + +@pytest.fixture +def address_model_factory(): + """Create and return a factory for AddressModel fixtures.""" + + def _create_address_model( + network_id="base-sepolia", + address_id="0x1234567890123456789012345678901234567890", + wallet_id="test-wallet-id", + public_key="0xpublickey", + index=0, + ): + return AddressModel( + network_id=network_id, + address_id=address_id, + wallet_id=wallet_id, + public_key=public_key, + index=index, + ) + + return _create_address_model + + +@pytest.fixture +def wallet_address_factory(address_model_factory): + """Create and return a factory for WalletAddress fixtures.""" + + def _create_wallet_address(key=False, **kwargs): + model = address_model_factory(**kwargs) + + _key = None + if key: + _key = Mock(spec=LocalAccount) + + return WalletAddress(model, _key) + + return _create_wallet_address diff --git a/tests/factories/wallet_factory.py b/tests/factories/wallet_factory.py new file mode 100644 index 0000000..220bf9e --- /dev/null +++ b/tests/factories/wallet_factory.py @@ -0,0 +1,60 @@ +import pytest +from bip_utils import Bip32Slip10Secp256k1 + +from cdp.client.models.feature_set import FeatureSet +from cdp.client.models.wallet import Wallet as WalletModel +from cdp.wallet import Wallet + + +@pytest.fixture +def wallet_model_factory(address_model_factory): + """Create and return a factory for WalletModel fixtures.""" + + def _create_wallet_model( + id="test-wallet-id", + network_id="base-sepolia", + default_address=None, + feature_set=None, + server_signer_status="active_seed", + ): + if default_address is None: + default_address = address_model_factory() + if feature_set is None: + feature_set = FeatureSet( + faucet=True, + server_signer=True, + transfer=True, + trade=True, + stake=True, + gasless_send=True, + ) + return WalletModel( + id=id, + network_id=network_id, + default_address=default_address, + feature_set=feature_set, + server_signer_status=server_signer_status, + ) + + return _create_wallet_model + + +@pytest.fixture +def master_key_factory(): + """Create and return a factory for master key fixtures.""" + + def _create_master_key(seed=b"\x00" * 64): + return Bip32Slip10Secp256k1.FromSeed(seed) + + return _create_master_key + + +@pytest.fixture +def wallet_factory(wallet_model_factory): + """Create and return a factory for Wallet fixtures.""" + + def _create_wallet(seed=None, **kwargs): + model = wallet_model_factory(**kwargs) + return Wallet(model, seed) + + return _create_wallet diff --git a/tests/test_address.py b/tests/test_address.py index 1074b7a..b88f781 100644 --- a/tests/test_address.py +++ b/tests/test_address.py @@ -6,46 +6,31 @@ from cdp.address import Address from cdp.balance_map import BalanceMap from cdp.client.exceptions import ApiException -from cdp.client.models.asset import Asset as AssetModel -from cdp.client.models.balance import Balance as BalanceModel from cdp.errors import ApiError from cdp.faucet_transaction import FaucetTransaction -@pytest.fixture -def address(): - """Create and return a fixture for an Address.""" - return Address( - network_id="base-sepolia", address_id="0x1234567890123456789012345678901234567890" - ) - - -@pytest.fixture -def asset_model(): - """Create and return a fixture for an AssetModel.""" - return AssetModel(network_id="base-sepolia", asset_id="eth", decimals=18) - - -@pytest.fixture -def balance_model(asset_model): - """Create and return a fixture for a BalanceModel.""" - return BalanceModel(amount="1000000000000000000", asset=asset_model) - - -def test_address_initialization(address): +def test_address_initialization(address_factory): """Test the initialization of an Address.""" + address = address_factory() + + assert isinstance(address, Address) assert address.network_id == "base-sepolia" assert address.address_id == "0x1234567890123456789012345678901234567890" -def test_address_can_sign(address): +def test_address_can_sign(address_factory): """Test the can_sign property of an Address.""" + address = address_factory() + assert not address.can_sign @patch("cdp.Cdp.api_clients") -def test_address_faucet(mock_api_clients, address): +def test_address_faucet(mock_api_clients, address_factory): """Test the faucet method of an Address.""" + address = address_factory() + mock_request_faucet = Mock() mock_request_faucet.return_value = Mock(spec=FaucetTransaction) mock_api_clients.external_addresses.request_external_faucet_funds = mock_request_faucet @@ -59,8 +44,10 @@ def test_address_faucet(mock_api_clients, address): @patch("cdp.Cdp.api_clients") -def test_address_faucet_with_asset_id(mock_api_clients, address): +def test_address_faucet_with_asset_id(mock_api_clients, address_factory): """Test the faucet method of an Address with an asset_id.""" + address = address_factory() + mock_request_faucet = Mock() mock_request_faucet.return_value = Mock(spec=FaucetTransaction) mock_api_clients.external_addresses.request_external_faucet_funds = mock_request_faucet @@ -74,8 +61,10 @@ def test_address_faucet_with_asset_id(mock_api_clients, address): @patch("cdp.Cdp.api_clients") -def test_address_faucet_api_error(mock_api_clients, address): +def test_address_faucet_api_error(mock_api_clients, address_factory): """Test the faucet method of an Address raises an error when the API call fails.""" + address = address_factory() + mock_request_faucet = Mock() err = ApiException(500, "boom") mock_request_faucet.side_effect = ApiError(err, code="boom", message="boom") @@ -86,8 +75,11 @@ def test_address_faucet_api_error(mock_api_clients, address): @patch("cdp.Cdp.api_clients") -def test_address_balance(mock_api_clients, address, balance_model): +def test_address_balance(mock_api_clients, address_factory, balance_model_factory): """Test the balance method of an Address.""" + address = address_factory() + balance_model = balance_model_factory() + mock_get_balance = Mock() mock_get_balance.return_value = balance_model mock_api_clients.external_addresses.get_external_address_balance = mock_get_balance @@ -102,8 +94,10 @@ def test_address_balance(mock_api_clients, address, balance_model): @patch("cdp.Cdp.api_clients") -def test_address_balance_zero(mock_api_clients, address): +def test_address_balance_zero(mock_api_clients, address_factory): """Test the balance method of an Address returns 0 when the balance is not found.""" + address = address_factory() + mock_get_balance = Mock() mock_get_balance.return_value = None mock_api_clients.external_addresses.get_external_address_balance = mock_get_balance @@ -115,8 +109,10 @@ def test_address_balance_zero(mock_api_clients, address): @patch("cdp.Cdp.api_clients") -def test_address_balance_api_error(mock_api_clients, address): +def test_address_balance_api_error(mock_api_clients, address_factory): """Test the balance method of an Address raises an error when the API call fails.""" + address = address_factory() + mock_get_balance = Mock() err = ApiException(500, "boom") mock_get_balance.side_effect = ApiError(err, code="boom", message="boom") @@ -127,8 +123,11 @@ def test_address_balance_api_error(mock_api_clients, address): @patch("cdp.Cdp.api_clients") -def test_address_balances(mock_api_clients, address, balance_model): +def test_address_balances(mock_api_clients, address_factory, balance_model_factory): """Test the balances method of an Address.""" + address = address_factory() + balance_model = balance_model_factory() + mock_list_balances = Mock() mock_list_balances.return_value = Mock(data=[balance_model]) mock_api_clients.external_addresses.list_external_address_balances = mock_list_balances @@ -145,8 +144,10 @@ def test_address_balances(mock_api_clients, address, balance_model): @patch("cdp.Cdp.api_clients") -def test_address_balances_api_error(mock_api_clients, address): +def test_address_balances_api_error(mock_api_clients, address_factory): """Test the balances method of an Address raises an error when the API call fails.""" + address = address_factory() + mock_list_balances = Mock() err = ApiException(500, "boom") mock_list_balances.side_effect = ApiError(err, code="boom", message="boom") @@ -156,13 +157,17 @@ def test_address_balances_api_error(mock_api_clients, address): address.balances() -def test_address_str_representation(address): +def test_address_str_representation(address_factory): """Test the str representation of an Address.""" + address = address_factory() + expected_str = f"Address: (address_id: {address.address_id}, network_id: {address.network_id})" assert str(address) == expected_str -def test_address_repr(address): +def test_address_repr(address_factory): """Test the repr representation of an Address.""" + address = address_factory() + expected_repr = f"Address: (address_id: {address.address_id}, network_id: {address.network_id})" assert repr(address) == expected_repr diff --git a/tests/test_asset.py b/tests/test_asset.py index 9fe43f2..3b36338 100644 --- a/tests/test_asset.py +++ b/tests/test_asset.py @@ -4,30 +4,22 @@ import pytest from cdp.asset import Asset -from cdp.client.models.asset import Asset as AssetModel -@pytest.fixture -def asset_model(): - """Create and return a fixture for asset model.""" - return AssetModel(network_id="ethereum-goerli", asset_id="eth", decimals=18) - - -@pytest.fixture -def asset(asset_model): - """Create and return a fixture for asset.""" - return Asset.from_model(asset_model) - - -def test_asset_initialization(asset): +def test_asset_initialization(asset_factory): """Test asset initialization.""" - assert asset.network_id == "ethereum-goerli" - assert asset.asset_id == "eth" - assert asset.decimals == 18 + asset = asset_factory() + assert isinstance(asset, Asset) + assert asset.network_id == "base-sepolia" + assert asset.asset_id == "usdc" + assert asset.decimals == 6 -def test_asset_from_model(asset_model): + +def test_asset_from_model(asset_model_factory): """Test asset from model.""" + asset_model = asset_model_factory() + asset = Asset.from_model(asset_model) assert isinstance(asset, Asset) assert asset.network_id == asset_model.network_id @@ -35,36 +27,44 @@ def test_asset_from_model(asset_model): assert asset.decimals == asset_model.decimals -def test_asset_from_model_with_gwei(asset_model): +def test_asset_from_model_with_gwei(asset_model_factory): """Test asset from model with gwei.""" + asset_model = asset_model_factory(asset_id="eth", decimals=18) + asset = Asset.from_model(asset_model, asset_id="gwei") assert asset.decimals == 9 -def test_asset_from_model_with_wei(asset_model): +def test_asset_from_model_with_wei(asset_model_factory): """Test asset from model with wei.""" + asset_model = asset_model_factory(asset_id="eth", decimals=18) + asset = Asset.from_model(asset_model, asset_id="wei") assert asset.decimals == 0 -def test_asset_from_model_with_invalid_asset_id(asset_model): +def test_asset_from_model_with_invalid_asset_id(asset_model_factory): """Test asset from model with invalid asset ID.""" + asset_model = asset_model_factory(asset_id="eth", decimals=18) + with pytest.raises(ValueError, match="Unsupported asset ID: invalid"): Asset.from_model(asset_model, asset_id="invalid") @patch("cdp.Cdp.api_clients") -def test_asset_fetch(mock_api_clients, asset_model): +def test_asset_fetch(mock_api_clients, asset_model_factory): """Test asset fetch.""" + asset_model = asset_model_factory() + mock_get_asset = Mock() mock_get_asset.return_value = asset_model mock_api_clients.assets.get_asset = mock_get_asset - asset = Asset.fetch("ethereum-goerli", "eth") + asset = Asset.fetch("base-sepolia", "usdc") assert isinstance(asset, Asset) - assert asset.network_id == "ethereum-goerli" - assert asset.asset_id == "eth" - mock_get_asset.assert_called_once_with(network_id="ethereum-goerli", asset_id="eth") + assert asset.network_id == asset_model.network_id + assert asset.asset_id == asset_model.asset_id + mock_get_asset.assert_called_once_with(network_id="base-sepolia", asset_id="usdc") @patch("cdp.Cdp.api_clients") @@ -92,29 +92,37 @@ def test_primary_denomination(input_asset_id, expected_output): assert Asset.primary_denomination(input_asset_id) == expected_output -def test_from_atomic_amount(asset): +def test_from_atomic_amount(asset_factory): """Test from atomic amount.""" + asset = asset_factory(asset_id="eth", decimals=18) + assert asset.from_atomic_amount(Decimal("1000000000000000000")) == Decimal("1") assert asset.from_atomic_amount(Decimal("500000000000000000")) == Decimal("0.5") -def test_to_atomic_amount(asset): +def test_to_atomic_amount(asset_factory): """Test to atomic amount.""" + asset = asset_factory(asset_id="eth", decimals=18) + assert asset.to_atomic_amount(Decimal("1")) == Decimal("1000000000000000000") assert asset.to_atomic_amount(Decimal("0.5")) == Decimal("500000000000000000") -def test_asset_str_representation(asset): +def test_asset_str_representation(asset_factory): """Test asset string representation.""" + asset = asset_factory(asset_id="eth", decimals=18) + expected_str = ( - "Asset: (asset_id: eth, network_id: ethereum-goerli, contract_address: None, decimals: 18)" + "Asset: (asset_id: eth, network_id: base-sepolia, contract_address: None, decimals: 18)" ) assert str(asset) == expected_str -def test_asset_repr(asset): +def test_asset_repr(asset_factory): """Test asset repr.""" + asset = asset_factory(asset_id="eth", decimals=18) + expected_repr = ( - "Asset: (asset_id: eth, network_id: ethereum-goerli, contract_address: None, decimals: 18)" + "Asset: (asset_id: eth, network_id: base-sepolia, contract_address: None, decimals: 18)" ) assert repr(asset) == expected_repr diff --git a/tests/test_balance.py b/tests/test_balance.py index 53218d2..3f4f691 100644 --- a/tests/test_balance.py +++ b/tests/test_balance.py @@ -1,55 +1,33 @@ from decimal import Decimal -import pytest - from cdp.asset import Asset from cdp.balance import Balance -from cdp.client.models.asset import Asset as AssetModel -from cdp.client.models.balance import Balance as BalanceModel - - -@pytest.fixture -def asset_model(): - """Create and return a fixture for an AssetModel.""" - return AssetModel(network_id="ethereum-goerli", asset_id="eth", decimals=18) - - -@pytest.fixture -def asset(asset_model): - """Create and return a fixture for an Asset.""" - return Asset.from_model(asset_model) -@pytest.fixture -def balance_model(asset_model): - """Create and return a fixture for a BalanceModel.""" - return BalanceModel(amount="1000000000000000000", asset=asset_model) - - -@pytest.fixture -def balance(asset): - """Create and return a fixture for a Balance.""" - return Balance(Decimal("1.5"), asset) - - -def test_balance_initialization(asset): +def test_balance_initialization(asset_factory): """Test balance initialization.""" + asset = asset_factory(asset_id="eth", decimals=18) + balance = Balance(Decimal("1"), asset) assert balance.amount == Decimal("1") assert balance.asset == asset assert balance.asset_id == "eth" -def test_balance_initialization_with_asset_id(asset): +def test_balance_initialization_with_asset_id(asset_factory): """Test balance initialization with asset ID.""" + asset = asset_factory(asset_id="eth", decimals=18) + balance = Balance(Decimal("10"), asset, asset_id="gwei") assert balance.amount == Decimal("10") assert balance.asset == asset assert balance.asset_id == "gwei" -def test_balance_from_model(balance_model): +def test_balance_from_model(balance_model_factory): """Test balance from model.""" + balance_model = balance_model_factory() + balance = Balance.from_model(balance_model) assert balance.amount == Decimal("1") assert isinstance(balance.asset, Asset) @@ -57,8 +35,10 @@ def test_balance_from_model(balance_model): assert balance.asset_id == "eth" -def test_balance_from_model_with_asset_id(balance_model): +def test_balance_from_model_with_asset_id(balance_model_factory): """Test balance from model with asset ID.""" + balance_model = balance_model_factory() + balance = Balance.from_model(balance_model, asset_id="gwei") assert balance.amount == Decimal("1000000000") assert isinstance(balance.asset, Asset) @@ -66,34 +46,26 @@ def test_balance_from_model_with_asset_id(balance_model): assert balance.asset_id == "gwei" -def test_balance_amount(balance): +def test_balance_amount(balance_factory): """Test balance amount.""" - assert balance.amount == Decimal("1.5") - + balance = balance_factory(amount=1.5) -def test_balance_asset(balance, asset): - """Test balance asset.""" - assert balance.asset == asset - - -def test_balance_asset_id(balance, asset): - """Test balance asset ID.""" - assert balance.asset_id == asset.asset_id + assert balance.amount == Decimal("1.5") -def test_balance_str_representation(asset): +def test_balance_str_representation(balance_factory): """Test balance string representation.""" - balance = Balance(Decimal("1.5"), asset) + balance = balance_factory(amount=1.5) assert ( str(balance) - == "Balance: (amount: 1.5, asset: Asset: (asset_id: eth, network_id: ethereum-goerli, contract_address: None, decimals: 18))" + == "Balance: (amount: 1.5, asset: Asset: (asset_id: eth, network_id: base-sepolia, contract_address: None, decimals: 18))" ) -def test_balance_repr(asset): +def test_balance_repr(balance_factory): """Test balance repr.""" - balance = Balance(Decimal("1.5"), asset) + balance = balance_factory(amount=1.5) assert ( repr(balance) - == "Balance: (amount: 1.5, asset: Asset: (asset_id: eth, network_id: ethereum-goerli, contract_address: None, decimals: 18))" + == "Balance: (amount: 1.5, asset: Asset: (asset_id: eth, network_id: base-sepolia, contract_address: None, decimals: 18))" ) diff --git a/tests/test_contract_invocation.py b/tests/test_contract_invocation.py index 8fb4080..a96bf1a 100644 --- a/tests/test_contract_invocation.py +++ b/tests/test_contract_invocation.py @@ -3,90 +3,10 @@ import pytest -from cdp.asset import Asset -from cdp.client.models.asset import Asset as AssetModel -from cdp.client.models.contract_invocation import ContractInvocation as ContractInvocationModel -from cdp.client.models.transaction import Transaction as TransactionModel from cdp.contract_invocation import ContractInvocation from cdp.errors import TransactionNotSignedError -@pytest.fixture -def asset_model_factory(): - """Create and return a factory for creating AssetModel fixtures.""" - - def _create_asset_model(network_id="base-sepolia", asset_id="usdc", decimals=6): - return AssetModel(network_id=network_id, asset_id=asset_id, decimals=decimals) - - return _create_asset_model - - -@pytest.fixture -def asset_factory(asset_model_factory): - """Create and return a factory for creating Asset fixtures.""" - - def _create_asset(network_id="base-sepolia", asset_id="usdc", decimals=6): - asset_model = asset_model_factory(network_id, asset_id, decimals) - return Asset.from_model(asset_model) - - return _create_asset - - -@pytest.fixture -def transaction_model_factory(): - """Create and return a factory for creating TransactionModel fixtures.""" - - def _create_transaction_model(status="complete"): - return TransactionModel( - network_id="base-sepolia", - transaction_hash="0xtransactionhash", - from_address_id="0xaddressid", - to_address_id="0xdestination", - unsigned_payload="0xunsignedpayload", - signed_payload="0xsignedpayload" - if status in ["signed", "broadcast", "complete"] - else None, - status=status, - transaction_link="https://sepolia.basescan.org/tx/0xtransactionlink" - if status == "complete" - else None, - ) - - return _create_transaction_model - - -@pytest.fixture -def contract_invocation_model_factory(transaction_model_factory): - """Create and return a factory for creating ContractInvocationModel fixtures.""" - - def _create_contract_invocation_model(status="complete"): - return ContractInvocationModel( - network_id="base-sepolia", - wallet_id="test-wallet-id", - address_id="0xaddressid", - contract_invocation_id="test-invocation-id", - contract_address="0xcontractaddress", - method="testMethod", - args='{"arg1": "value1"}', - abi='{"abi": "data"}', - amount="1", - transaction=transaction_model_factory(status), - ) - - return _create_contract_invocation_model - - -@pytest.fixture -def contract_invocation_factory(contract_invocation_model_factory): - """Create and return a factory for creating ContractInvocation fixtures.""" - - def _create_contract_invocation(status="complete"): - contract_invocation_model = contract_invocation_model_factory(status) - return ContractInvocation(contract_invocation_model) - - return _create_contract_invocation - - def test_contract_invocation_initialization(contract_invocation_factory): """Test the initialization of a ContractInvocation object.""" contract_invocation = contract_invocation_factory() diff --git a/tests/test_payload_signature.py b/tests/test_payload_signature.py index 7721fca..24db9bf 100644 --- a/tests/test_payload_signature.py +++ b/tests/test_payload_signature.py @@ -2,40 +2,9 @@ import pytest -from cdp.client.models.payload_signature import PayloadSignature as PayloadSignatureModel from cdp.payload_signature import PayloadSignature -@pytest.fixture -def payload_signature_model_factory(): - """Create and return a factory for creating PayloadSignatureModel fixtures.""" - - def _create_payload_signature_model(status="signed"): - payload_signature_model = PayloadSignatureModel( - payload_signature_id="test-payload-signature-id", - address_id="0xaddressid", - wallet_id="test-wallet-id", - unsigned_payload="0xunsignedpayload", - signature="0xsignature" if status == "signed" else None, - status=status, - ) - - return payload_signature_model - - return _create_payload_signature_model - - -@pytest.fixture -def payload_signature_factory(payload_signature_model_factory): - """Create and return a factory for creating PayloadSignature fixtures.""" - - def _create_payload_signature(status="signed"): - payload_signature_model = payload_signature_model_factory(status) - return PayloadSignature(payload_signature_model) - - return _create_payload_signature - - def test_payload_signature_initialization(payload_signature_factory): """Test the initialization of a PayloadSignature object.""" payload_signature = payload_signature_factory() diff --git a/tests/test_smart_contract.py b/tests/test_smart_contract.py index 18cdad1..2c2876d 100644 --- a/tests/test_smart_contract.py +++ b/tests/test_smart_contract.py @@ -2,70 +2,9 @@ import pytest -from cdp.client.models.smart_contract import SmartContract as SmartContractModel -from cdp.client.models.smart_contract_options import SmartContractOptions -from cdp.client.models.token_contract_options import TokenContractOptions -from cdp.client.models.transaction import Transaction as TransactionModel from cdp.smart_contract import SmartContract -@pytest.fixture -def transaction_model_factory(): - """Create and return a factory for creating TransactionModel fixtures.""" - - def _create_transaction_model(status="complete"): - return TransactionModel( - network_id="base-sepolia", - transaction_hash="0xtransactionhash", - from_address_id="0xaddressid", - to_address_id="0xdestination", - unsigned_payload="0xunsignedpayload", - signed_payload="0xsignedpayload" - if status in ["signed", "broadcast", "complete"] - else None, - status=status, - transaction_link="https://sepolia.basescan.org/tx/0xtransactionlink" - if status == "complete" - else None, - ) - - return _create_transaction_model - - -@pytest.fixture -def smart_contract_model_factory(transaction_model_factory): - """Create and return a factory for creating SmartContractModel fixtures.""" - - def _create_smart_contract_model(status="complete"): - token_options = TokenContractOptions(name="TestToken", symbol="TT", total_supply="1000000") - smart_contract_options = SmartContractOptions(actual_instance=token_options) - - return SmartContractModel( - smart_contract_id="test-contract-id", - network_id="base-sepolia", - wallet_id="test-wallet-id", - contract_address="0xcontractaddress", - deployer_address="0xdeployeraddress", - type="erc20", - options=smart_contract_options, - abi='{"abi": "data"}', - transaction=transaction_model_factory(status), - ) - - return _create_smart_contract_model - - -@pytest.fixture -def smart_contract_factory(smart_contract_model_factory): - """Create and return a factory for creating SmartContract fixtures.""" - - def _create_smart_contract(status="complete"): - smart_contract_model = smart_contract_model_factory(status) - return SmartContract(smart_contract_model) - - return _create_smart_contract - - def test_smart_contract_initialization(smart_contract_factory): """Test the initialization of a SmartContract object.""" smart_contract = smart_contract_factory() diff --git a/tests/test_trade.py b/tests/test_trade.py index 5bf23e0..64f22d4 100644 --- a/tests/test_trade.py +++ b/tests/test_trade.py @@ -3,102 +3,11 @@ import pytest -from cdp.asset import Asset -from cdp.client.models.asset import Asset as AssetModel -from cdp.client.models.trade import Trade as TradeModel -from cdp.client.models.transaction import Transaction as TransactionModel from cdp.errors import TransactionNotSignedError from cdp.trade import Trade from cdp.transaction import Transaction -@pytest.fixture -def asset_model_factory(): - """Create and return a factory for creating AssetModel fixtures.""" - - def _create_asset_model(network_id="base-sepolia", asset_id="usdc", decimals=6): - return AssetModel(network_id=network_id, asset_id=asset_id, decimals=decimals) - - return _create_asset_model - - -@pytest.fixture -def asset_factory(asset_model_factory): - """Create and return a factory for creating Asset fixtures.""" - - def _create_asset(network_id="base-sepolia", asset_id="usdc", decimals=6): - asset_model = asset_model_factory(network_id, asset_id, decimals) - return Asset.from_model(asset_model) - - return _create_asset - - -@pytest.fixture -def transaction_model_factory(): - """Create and return a factory for creating TransactionModel fixtures.""" - - def _create_transaction_model(status="complete"): - return TransactionModel( - network_id="base-sepolia", - transaction_hash="0xtransactionhash", - from_address_id="0xaddressid", - to_address_id="0xdestination", - unsigned_payload="0xunsignedpayload", - signed_payload="0xsignedpayload" - if status in ["signed", "broadcast", "complete"] - else None, - status=status, - transaction_link="https://sepolia.basescan.org/tx/0xtransactionlink" - if status == "complete" - else None, - ) - - return _create_transaction_model - - -@pytest.fixture -def trade_model_factory(asset_model_factory, transaction_model_factory): - """Create and return a factory for creating TradeModel fixtures.""" - - def _create_trade_model( - status="complete", - from_asset_id="usdc", - to_asset_id="eth", - from_asset_decimals=6, - to_asset_decimals=18, - ): - from_asset_model = asset_model_factory(asset_id=from_asset_id, decimals=from_asset_decimals) - to_asset_model = asset_model_factory(asset_id=to_asset_id, decimals=to_asset_decimals) - transaction_model = transaction_model_factory(status) - approve_transaction_model = transaction_model_factory(status) - - return TradeModel( - network_id="base-sepolia", - wallet_id="test-wallet-id", - address_id="0xaddressid", - trade_id="test-trade-id", - from_asset=from_asset_model, - to_asset=to_asset_model, - from_amount="1000000", # 1 USDC - to_amount="500000000000000000", # 0.5 ETH - transaction=transaction_model, - approve_transaction=approve_transaction_model, - ) - - return _create_trade_model - - -@pytest.fixture -def trade_factory(trade_model_factory): - """Create and return a factory for creating Trade fixtures.""" - - def _create_trade(status="complete", from_asset_id="usdc", to_asset_id="eth"): - trade_model = trade_model_factory(status, from_asset_id, to_asset_id) - return Trade(trade_model) - - return _create_trade - - def test_trade_initialization(trade_factory): """Test the initialization of a Trade object.""" trade = trade_factory() diff --git a/tests/test_transaction.py b/tests/test_transaction.py index 575ce7e..2186fb2 100644 --- a/tests/test_transaction.py +++ b/tests/test_transaction.py @@ -4,49 +4,11 @@ from cdp.transaction import Transaction -@pytest.fixture -def transaction_model(): - """Create and return a fixture for a TransactionModel.""" - return TransactionModel( - network_id="base-sepolia", - transaction_hash="0xtransactionhash", - from_address_id="0xfromaddressid", - to_address_id="0xtoaddressid", - unsigned_payload="0xunsignedpayload", - signed_payload="0xsignedpayload", - status="complete", - block_hash="0xblockhash", - block_height="123456", - transaction_link="https://basescan.org/tx/0xtransactionlink", - ) - - -@pytest.fixture -def unsigned_transaction_model(): - """Create and return a fixture for an unsigned TransactionModel.""" - return TransactionModel( - network_id="base-sepolia", - from_address_id="0xfromaddressid", - to_address_id="0xtoaddressid", - unsigned_payload="0xunsignedpayload", - status="pending", - ) - - -@pytest.fixture -def transaction(transaction_model): - """Create and return a fixture for a Transaction.""" - return Transaction(transaction_model) - - -@pytest.fixture -def unsigned_transaction(unsigned_transaction_model): - """Create and return a fixture for an unsigned Transaction.""" - return Transaction(unsigned_transaction_model) - - -def test_transaction_initialization(transaction): +def test_transaction_initialization(transaction_factory): """Test transaction initialization.""" + transaction = transaction_factory() + + assert isinstance(transaction, Transaction) assert isinstance(transaction._model, TransactionModel) assert transaction._raw is None assert transaction._signature == "0xsignedpayload" @@ -58,18 +20,24 @@ def test_transaction_initialization_invalid_model(): Transaction("invalid_model") -def test_unsigned_payload(transaction): +def test_unsigned_payload(transaction_factory): """Test unsigned payload.""" + transaction = transaction_factory() + assert transaction.unsigned_payload == "0xunsignedpayload" -def test_signed_payload(transaction): +def test_signed_payload(transaction_factory): """Test signed payload.""" + transaction = transaction_factory() + assert transaction.signed_payload == "0xsignedpayload" -def test_transaction_hash(transaction): +def test_transaction_hash(transaction_factory): """Test transaction hash.""" + transaction = transaction_factory() + assert transaction.transaction_hash == "0xtransactionhash" @@ -84,67 +52,93 @@ def test_transaction_hash(transaction): ("unspecified", Transaction.Status.UNSPECIFIED), ], ) -def test_status(transaction, status, expected_status): +def test_status(transaction_factory, status, expected_status): """Test transaction status.""" + transaction = transaction_factory() + transaction._model.status = status assert transaction.status == expected_status -def test_from_address_id(transaction): +def test_from_address_id(transaction_factory): """Test from address ID.""" - assert transaction.from_address_id == "0xfromaddressid" + transaction = transaction_factory() + + assert transaction.from_address_id == "0xaddressid" -def test_to_address_id(transaction): +def test_to_address_id(transaction_factory): """Test to address ID.""" - assert transaction.to_address_id == "0xtoaddressid" + transaction = transaction_factory() + assert transaction.to_address_id == "0xdestination" -def test_terminal_state(unsigned_transaction, transaction): + +def test_terminal_state(transaction_factory): """Test terminal state.""" + unsigned_transaction = transaction_factory("pending") + transaction = transaction_factory() + assert not unsigned_transaction.terminal_state assert transaction.terminal_state -def test_block_hash(transaction): +def test_block_hash(transaction_factory): """Test block hash.""" + transaction = transaction_factory() + assert transaction.block_hash == "0xblockhash" -def test_block_height(transaction): +def test_block_height(transaction_factory): """Test block height.""" + transaction = transaction_factory() + assert transaction.block_height == "123456" -def test_transaction_link(transaction): +def test_transaction_link(transaction_factory): """Test transaction link.""" - assert transaction.transaction_link == "https://basescan.org/tx/0xtransactionlink" + transaction = transaction_factory() + assert transaction.transaction_link == "https://sepolia.basescan.org/tx/0xtransactionlink" -def test_signed(unsigned_transaction, transaction): + +def test_signed(transaction_factory): """Test signed.""" + unsigned_transaction = transaction_factory("pending") + transaction = transaction_factory() + assert not unsigned_transaction.signed assert transaction.signed -def test_signature(transaction): +def test_signature(transaction_factory): """Test signature.""" + transaction = transaction_factory() + assert transaction.signature == "0xsignedpayload" -def test_signature_not_signed(unsigned_transaction): +def test_signature_not_signed(transaction_factory): """Test signature not signed.""" + unsigned_transaction = transaction_factory("pending") + with pytest.raises(ValueError, match="Transaction is not signed"): unsigned_transaction.signature # noqa: B018 -def test_str_representation(transaction): +def test_str_representation(transaction_factory): """Test string representation.""" + transaction = transaction_factory() + expected_str = "Transaction: (transaction_hash: 0xtransactionhash, status: complete)" assert str(transaction) == expected_str -def test_repr(transaction): +def test_repr(transaction_factory): """Test repr.""" + transaction = transaction_factory() + expected_repr = "Transaction: (transaction_hash: 0xtransactionhash, status: complete)" assert repr(transaction) == expected_repr diff --git a/tests/test_transfer.py b/tests/test_transfer.py index 5573915..9153905 100644 --- a/tests/test_transfer.py +++ b/tests/test_transfer.py @@ -5,125 +5,12 @@ from eth_account.signers.local import LocalAccount from cdp.asset import Asset -from cdp.client.models.asset import Asset as AssetModel -from cdp.client.models.sponsored_send import SponsoredSend as SponsoredSendModel -from cdp.client.models.transaction import Transaction as TransactionModel -from cdp.client.models.transfer import Transfer as TransferModel from cdp.errors import TransactionNotSignedError from cdp.sponsored_send import SponsoredSend from cdp.transaction import Transaction from cdp.transfer import Transfer -@pytest.fixture -def asset_model_factory(): - """Create and return a factory for creating AssetModel fixtures.""" - - def _create_asset_model(network_id="base-sepolia", asset_id="usdc", decimals=6): - return AssetModel(network_id=network_id, asset_id=asset_id, decimals=decimals) - - return _create_asset_model - - -@pytest.fixture -def asset_factory(asset_model_factory): - """Create and return a factory for creating Asset fixtures.""" - - def _create_asset(network_id="base-sepolia", asset_id="usdc", decimals=6): - asset_model = asset_model_factory(network_id, asset_id, decimals) - return Asset.from_model(asset_model) - - return _create_asset - - -@pytest.fixture -def sponsored_send_model_factory(): - """Create and return a factory for creating SponsoredSendModel fixtures.""" - - def _create_sponsored_send_model(status="complete"): - status = "submitted" if status == "broadcast" else status - - return SponsoredSendModel( - to_address_id="0xdestination", - raw_typed_data="0xtypeddata", - typed_data_hash="0xtypeddatahash", - signature="0xsignature" if status in ["signed", "submitted", "complete"] else None, - transaction_hash="0xtransactionhash" if status == "complete" else None, - transaction_link="https://sepolia.basescan.org/tx/0xtransactionlink" - if status == "complete" - else None, - status=status, - ) - - return _create_sponsored_send_model - - -@pytest.fixture -def transaction_model_factory(): - """Create and return a factory for creating TransactionModel fixtures.""" - - def _create_transaction_model(status="complete"): - return TransactionModel( - network_id="base-sepolia", - transaction_hash="0xtransactionhash", - from_address_id="0xaddressid", - to_address_id="0xdestination", - unsigned_payload="0xunsignedpayload", - signed_payload="0xsignedpayload" - if status in ["signed", "broadcast", "complete"] - else None, - status=status, - transaction_link="https://sepolia.basescan.org/tx/0xtransactionlink" - if status == "complete" - else None, - ) - - return _create_transaction_model - - -@pytest.fixture -def transfer_model_factory( - asset_model_factory, sponsored_send_model_factory, transaction_model_factory -): - """Create and return a factory for creating TransferModel fixtures.""" - - def _create_transfer_model(gasless=True, status="complete", asset_id="usdc"): - asset_model = asset_model_factory(asset_id=asset_id) - if gasless: - sponsored_send_model = sponsored_send_model_factory(status) - transaction_model = None - else: - sponsored_send_model = None - transaction_model = transaction_model_factory(status) - - return TransferModel( - network_id="base-sepolia", - wallet_id="test-wallet-id", - address_id="0xaddressid", - destination="0xdestination", - amount="1000000", # 1 USDC or 1 ETH in wei - asset_id=asset_model.asset_id, - transfer_id="test-transfer-id", - asset=asset_model, - gasless=gasless, - sponsored_send=sponsored_send_model, - transaction=transaction_model, - ) - - return _create_transfer_model - - -@pytest.fixture -def transfer_factory(transfer_model_factory): - """Create and return a factory for creating Transfer fixtures.""" - - def _create_transfer(gasless=True, status="complete", asset_id="usdc"): - transfer_model = transfer_model_factory(gasless, status, asset_id) - return Transfer(transfer_model) - - return _create_transfer - - @pytest.mark.parametrize("gasless", [True, False]) def test_transfer_initialization(transfer_factory, gasless): """Test the initialization of a Transfer object.""" diff --git a/tests/test_wallet.py b/tests/test_wallet.py index d7b4133..41ff3a3 100644 --- a/tests/test_wallet.py +++ b/tests/test_wallet.py @@ -5,11 +5,8 @@ from bip_utils import Bip32Slip10Secp256k1 from eth_account import Account -from cdp.client.models.address import Address as AddressModel from cdp.client.models.create_address_request import CreateAddressRequest from cdp.client.models.create_wallet_request import CreateWalletRequest, CreateWalletRequestWallet -from cdp.client.models.feature_set import FeatureSet -from cdp.client.models.wallet import Wallet as WalletModel from cdp.contract_invocation import ContractInvocation from cdp.payload_signature import PayloadSignature from cdp.smart_contract import SmartContract @@ -19,93 +16,6 @@ from cdp.wallet_address import WalletAddress -@pytest.fixture -def address_model_factory(): - """Create and return a factory for AddressModel fixtures.""" - - def _create_address_model( - network_id="base-sepolia", - address_id="0x1234567890123456789012345678901234567890", - wallet_id="test-wallet-id", - public_key="0xpublickey", - index=0, - ): - return AddressModel( - network_id=network_id, - address_id=address_id, - wallet_id=wallet_id, - public_key=public_key, - index=index, - ) - - return _create_address_model - - -@pytest.fixture -def wallet_model_factory(address_model_factory): - """Create and return a factory for WalletModel fixtures.""" - - def _create_wallet_model( - id="test-wallet-id", - network_id="base-sepolia", - default_address=None, - feature_set=None, - server_signer_status="active_seed", - ): - if default_address is None: - default_address = address_model_factory() - if feature_set is None: - feature_set = FeatureSet( - faucet=True, - server_signer=True, - transfer=True, - trade=True, - stake=True, - gasless_send=True, - ) - return WalletModel( - id=id, - network_id=network_id, - default_address=default_address, - feature_set=feature_set, - server_signer_status=server_signer_status, - ) - - return _create_wallet_model - - -@pytest.fixture -def master_key_factory(): - """Create and return a factory for master key fixtures.""" - - def _create_master_key(seed=b"\x00" * 64): - return Bip32Slip10Secp256k1.FromSeed(seed) - - return _create_master_key - - -@pytest.fixture -def wallet_factory(wallet_model_factory): - """Create and return a factory for Wallet fixtures.""" - - def _create_wallet(seed=None, **kwargs): - model = wallet_model_factory(**kwargs) - return Wallet(model, seed) - - return _create_wallet - - -@pytest.fixture -def wallet_address_factory(address_model_factory): - """Create and return a factory for WalletAddress fixtures.""" - - def _create_wallet_address(key=None, **kwargs): - model = address_model_factory(**kwargs) - return WalletAddress(model, key) - - return _create_wallet_address - - @patch("cdp.Cdp.use_server_signer", False) @patch("cdp.wallet.os") @patch("cdp.wallet.Bip32Slip10Secp256k1") diff --git a/tests/test_wallet_address.py b/tests/test_wallet_address.py index 49835d0..336e0fd 100644 --- a/tests/test_wallet_address.py +++ b/tests/test_wallet_address.py @@ -8,9 +8,6 @@ from eth_utils import to_bytes from web3 import Web3 -from cdp.client.models.address import Address as AddressModel -from cdp.client.models.asset import Asset as AssetModel -from cdp.client.models.balance import Balance as BalanceModel from cdp.client.models.create_smart_contract_request import CreateSmartContractRequest from cdp.client.models.multi_token_contract_options import MultiTokenContractOptions from cdp.client.models.nft_contract_options import NFTContractOptions @@ -22,90 +19,68 @@ from cdp.smart_contract import SmartContract from cdp.trade import Trade from cdp.transfer import Transfer -from cdp.wallet_address import WalletAddress -@pytest.fixture -def address_model(): - """Fixture for an AddressModel.""" - return AddressModel( - network_id="base-sepolia", - address_id="0x1234567890123456789012345678901234567890", - wallet_id="test-wallet-id-1", - public_key="0x1234567890123456789012345678901234567890", - index=0, - ) - - -@pytest.fixture -def wallet_address(address_model): - """Fixture for a WalletAddress.""" - return WalletAddress(address_model) - - -@pytest.fixture -def wallet_address_with_key(address_model): - """Fixture for a WalletAddress with a key.""" - key = Mock(spec=LocalAccount) - return WalletAddress(address_model, key) - - -@pytest.fixture -def asset_model(): - """Fixture for an AssetModel.""" - return AssetModel(network_id="base-sepolia", asset_id="eth", decimals=18) - - -@pytest.fixture -def balance_model(asset_model): - """Fixture for a BalanceModel.""" - return BalanceModel(amount="5000000000000000000", asset=asset_model) - - -def test_wallet_address_initialization(wallet_address): +def test_wallet_address_initialization(wallet_address_factory): """Test the initialization of a WalletAddress.""" + wallet_address = wallet_address_factory() + assert wallet_address.network_id == "base-sepolia" assert wallet_address.address_id == "0x1234567890123456789012345678901234567890" - assert wallet_address.wallet_id == "test-wallet-id-1" + assert wallet_address.wallet_id == "test-wallet-id" assert wallet_address.key is None assert not wallet_address.can_sign -def test_wallet_address_initialization_with_key(wallet_address_with_key): +def test_wallet_address_initialization_with_key(wallet_address_factory): """Test the initialization of a WalletAddress with a key.""" + wallet_address_with_key = wallet_address_factory(key=True) + assert wallet_address_with_key.network_id == "base-sepolia" assert wallet_address_with_key.address_id == "0x1234567890123456789012345678901234567890" - assert wallet_address_with_key.wallet_id == "test-wallet-id-1" + assert wallet_address_with_key.wallet_id == "test-wallet-id" assert wallet_address_with_key.key is not None assert wallet_address_with_key.can_sign -def test_wallet_id_property(wallet_address): +def test_wallet_id_property(wallet_address_factory): """Test the wallet_id property of a WalletAddress.""" - assert wallet_address.wallet_id == "test-wallet-id-1" + wallet_address = wallet_address_factory() + assert wallet_address.wallet_id == "test-wallet-id" -def test_key_property(wallet_address, wallet_address_with_key): + +def test_key_property(wallet_address_factory): """Test the key property of a WalletAddress.""" + wallet_address = wallet_address_factory() + wallet_address_with_key = wallet_address_factory(True) + assert wallet_address.key is None assert wallet_address_with_key.key is not None -def test_key_setter(wallet_address): +def test_key_setter(wallet_address_factory): """Test the key setter of a WalletAddress.""" + wallet_address = wallet_address_factory() + new_key = Mock(spec=LocalAccount) wallet_address.key = new_key assert wallet_address.key == new_key -def test_can_sign_property(wallet_address, wallet_address_with_key): +def test_can_sign_property(wallet_address_factory): """Test the can_sign property of a WalletAddress.""" + wallet_address = wallet_address_factory() + wallet_address_with_key = wallet_address_factory(True) + assert not wallet_address.can_sign assert wallet_address_with_key.can_sign -def test_key_setter_raises_error_when_already_set(wallet_address_with_key): +def test_key_setter_raises_error_when_already_set(wallet_address_factory): """Test the key setter raises an error when already set.""" + wallet_address_with_key = wallet_address_factory(True) + new_key = Mock(spec=LocalAccount) with pytest.raises(ValueError, match="Private key is already set"): wallet_address_with_key.key = new_key @@ -115,9 +90,14 @@ def test_key_setter_raises_error_when_already_set(wallet_address_with_key): @patch("cdp.Cdp.api_clients") @patch("cdp.Cdp.use_server_signer", True) def test_transfer_with_server_signer( - mock_api_clients, mock_transfer, wallet_address, balance_model + mock_api_clients, mock_transfer, wallet_address_factory, balance_model_factory ): """Test the transfer method with a server signer.""" + wallet_address = wallet_address_factory() + balance_model = balance_model_factory( + amount="5000000000000000000", network_id="base-sepolia", asset_id="eth", decimals=18 + ) + mock_transfer_instance = Mock(spec=Transfer) mock_transfer.create.return_value = mock_transfer_instance @@ -147,8 +127,13 @@ def test_transfer_with_server_signer( @patch("cdp.wallet_address.Transfer") @patch("cdp.Cdp.api_clients") @patch("cdp.Cdp.use_server_signer", False) -def test_transfer(mock_api_clients, mock_transfer, wallet_address_with_key, balance_model): +def test_transfer(mock_api_clients, mock_transfer, wallet_address_factory, balance_model_factory): """Test the transfer method.""" + wallet_address_with_key = wallet_address_factory(key=True) + balance_model = balance_model_factory( + amount="5000000000000000000", network_id="base-sepolia", asset_id="eth", decimals=18 + ) + mock_transfer_instance = Mock(spec=Transfer) mock_transfer.create.return_value = mock_transfer_instance @@ -183,9 +168,14 @@ def test_transfer(mock_api_clients, mock_transfer, wallet_address_with_key, bala @patch("cdp.Cdp.api_clients") @patch("cdp.Cdp.use_server_signer", False) def test_transfer_create_api_error( - mock_api_clients, mock_transfer, wallet_address_with_key, balance_model + mock_api_clients, mock_transfer, wallet_address_factory, balance_model_factory ): """Test the transfer method raises an error when the create API call fails.""" + wallet_address_with_key = wallet_address_factory(key=True) + balance_model = balance_model_factory( + amount="5000000000000000000", network_id="base-sepolia", asset_id="eth", decimals=18 + ) + mock_transfer.create.side_effect = Exception("API Error") mock_get_balance = Mock() @@ -215,9 +205,14 @@ def test_transfer_create_api_error( @patch("cdp.Cdp.api_clients") @patch("cdp.Cdp.use_server_signer", False) def test_transfer_broadcast_api_error( - mock_api_clients, mock_transfer, wallet_address_with_key, balance_model + mock_api_clients, mock_transfer, wallet_address_factory, balance_model_factory ): """Test the transfer method raises an error when the broadcast API call fails.""" + wallet_address_with_key = wallet_address_factory(key=True) + balance_model = balance_model_factory( + amount="5000000000000000000", network_id="base-sepolia", asset_id="eth", decimals=18 + ) + mock_transfer_instance = Mock(spec=Transfer) mock_transfer_instance.broadcast.side_effect = Exception("API Error") mock_transfer.create.return_value = mock_transfer_instance @@ -250,8 +245,13 @@ def test_transfer_broadcast_api_error( @patch("cdp.wallet_address.Trade") @patch("cdp.Cdp.api_clients") @patch("cdp.Cdp.use_server_signer", True) -def test_trade(mock_api_clients, mock_trade, wallet_address, balance_model): +def test_trade(mock_api_clients, mock_trade, wallet_address_factory, balance_model_factory): """Test the trade method with a server signer.""" + wallet_address = wallet_address_factory() + balance_model = balance_model_factory( + amount="5000000000000000000", network_id="base-sepolia", asset_id="eth", decimals=18 + ) + mock_trade.create.return_value = Mock(spec=Trade) mock_get_balance = Mock() @@ -275,9 +275,14 @@ def test_trade(mock_api_clients, mock_trade, wallet_address, balance_model): @patch("cdp.Cdp.api_clients") @patch("cdp.Cdp.use_server_signer", False) def test_trade_with_client_signer( - mock_api_clients, mock_trade, wallet_address_with_key, balance_model + mock_api_clients, mock_trade, wallet_address_factory, balance_model_factory ): """Test the trade method.""" + wallet_address_with_key = wallet_address_factory(key=True) + balance_model = balance_model_factory( + amount="5000000000000000000", network_id="base-sepolia", asset_id="eth", decimals=18 + ) + mock_trade_instance = Mock(spec=Trade) mock_trade.create.return_value = mock_trade_instance @@ -301,8 +306,10 @@ def test_trade_with_client_signer( @patch("cdp.wallet_address.Transfer") -def test_transfers(mock_transfer, wallet_address): +def test_transfers(mock_transfer, wallet_address_factory): """Test the transfers method.""" + wallet_address = wallet_address_factory() + mock_transfer.list.return_value = iter([Mock(spec=Transfer), Mock(spec=Transfer)]) transfers = wallet_address.transfers() @@ -315,8 +322,10 @@ def test_transfers(mock_transfer, wallet_address): @patch("cdp.wallet_address.Transfer") -def test_transfers_api_error(mock_transfer, wallet_address): +def test_transfers_api_error(mock_transfer, wallet_address_factory): """Test the transfers method raises an error when the API call fails.""" + wallet_address = wallet_address_factory() + mock_transfer.list.side_effect = Exception("API Error") with pytest.raises(Exception, match="API Error"): @@ -324,8 +333,10 @@ def test_transfers_api_error(mock_transfer, wallet_address): @patch("cdp.wallet_address.Trade") -def test_trades(mock_trade, wallet_address): +def test_trades(mock_trade, wallet_address_factory): """Test the trades method.""" + wallet_address = wallet_address_factory() + mock_trade.list.return_value = iter([Mock(spec=Trade), Mock(spec=Trade)]) trades = wallet_address.trades() @@ -338,8 +349,10 @@ def test_trades(mock_trade, wallet_address): @patch("cdp.wallet_address.Trade") -def test_trades_api_error(mock_trade, wallet_address): +def test_trades_api_error(mock_trade, wallet_address_factory): """Test the trades method raises an error when the API call fails.""" + wallet_address = wallet_address_factory() + mock_trade.list.side_effect = Exception("API Error") with pytest.raises(Exception, match="API Error"): @@ -350,9 +363,14 @@ def test_trades_api_error(mock_trade, wallet_address): @patch("cdp.Cdp.api_clients") @patch("cdp.Cdp.use_server_signer", True) def test_invoke_contract_with_server_signer( - mock_api_clients, mock_contract_invocation, wallet_address, balance_model + mock_api_clients, mock_contract_invocation, wallet_address_factory, balance_model_factory ): """Test the invoke_contract method with a server signer.""" + wallet_address = wallet_address_factory() + balance_model = balance_model_factory( + amount="5000000000000000000", network_id="base-sepolia", asset_id="eth", decimals=18 + ) + mock_contract_invocation_instance = Mock(spec=ContractInvocation) mock_contract_invocation.create.return_value = mock_contract_invocation_instance @@ -392,9 +410,14 @@ def test_invoke_contract_with_server_signer( @patch("cdp.Cdp.api_clients") @patch("cdp.Cdp.use_server_signer", False) def test_invoke_contract( - mock_api_clients, mock_contract_invocation, wallet_address_with_key, balance_model + mock_api_clients, mock_contract_invocation, wallet_address_factory, balance_model_factory ): """Test the invoke_contract method.""" + wallet_address_with_key = wallet_address_factory(key=True) + balance_model = balance_model_factory( + amount="5000000000000000000", network_id="base-sepolia", asset_id="eth", decimals=18 + ) + mock_contract_invocation_instance = Mock(spec=ContractInvocation) mock_contract_invocation.create.return_value = mock_contract_invocation_instance @@ -436,9 +459,14 @@ def test_invoke_contract( @patch("cdp.Cdp.api_clients") @patch("cdp.Cdp.use_server_signer", False) def test_invoke_contract_api_error( - mock_api_clients, mock_contract_invocation, wallet_address_with_key, balance_model + mock_api_clients, mock_contract_invocation, wallet_address_factory, balance_model_factory ): """Test the invoke_contract method raises an error when the create API call fails.""" + wallet_address_with_key = wallet_address_factory(key=True) + balance_model = balance_model_factory( + amount="5000000000000000000", network_id="base-sepolia", asset_id="eth", decimals=18 + ) + mock_contract_invocation.create.side_effect = Exception("API Error") mock_get_balance = Mock() @@ -477,9 +505,14 @@ def test_invoke_contract_api_error( @patch("cdp.Cdp.api_clients") @patch("cdp.Cdp.use_server_signer", False) def test_invoke_contract_broadcast_api_error( - mock_api_clients, mock_contract_invocation, wallet_address_with_key, balance_model + mock_api_clients, mock_contract_invocation, wallet_address_factory, balance_model_factory ): """Test the invoke_contract method raises an error when the broadcast API call fails.""" + wallet_address_with_key = wallet_address_factory(key=True) + balance_model = balance_model_factory( + amount="5000000000000000000", network_id="base-sepolia", asset_id="eth", decimals=18 + ) + mock_contract_invocation_instance = Mock(spec=ContractInvocation) mock_contract_invocation.create.return_value = mock_contract_invocation_instance mock_contract_invocation_instance.broadcast.side_effect = Exception("API Error") @@ -520,8 +553,10 @@ def test_invoke_contract_broadcast_api_error( @patch("cdp.wallet_address.PayloadSignature") @patch("cdp.Cdp.use_server_signer", True) -def test_sign_payload_with_server_signer(mock_payload_signature, wallet_address): +def test_sign_payload_with_server_signer(mock_payload_signature, wallet_address_factory): """Test the sign_payload method with a server signer.""" + wallet_address = wallet_address_factory() + mock_payload_signature_instance = Mock(spec=PayloadSignature) mock_payload_signature.create.return_value = mock_payload_signature_instance @@ -539,8 +574,10 @@ def test_sign_payload_with_server_signer(mock_payload_signature, wallet_address) @patch("cdp.wallet_address.to_hex", Mock(return_value="0xsignature")) @patch("cdp.wallet_address.PayloadSignature") @patch("cdp.Cdp.use_server_signer", False) -def test_sign_payload(mock_payload_signature, wallet_address_with_key): +def test_sign_payload(mock_payload_signature, wallet_address_factory): """Test the sign_payload method.""" + wallet_address_with_key = wallet_address_factory(key=True) + mock_payload_signature_instance = Mock(spec=PayloadSignature) mock_payload_signature.create.return_value = mock_payload_signature_instance @@ -568,8 +605,10 @@ def test_sign_payload(mock_payload_signature, wallet_address_with_key): @patch("cdp.wallet_address.to_hex", Mock(return_value="0xsignature")) @patch("cdp.wallet_address.PayloadSignature") @patch("cdp.Cdp.use_server_signer", False) -def test_sign_payload_api_error(mock_payload_signature, wallet_address_with_key): +def test_sign_payload_api_error(mock_payload_signature, wallet_address_factory): """Test the sign_payload method.""" + wallet_address_with_key = wallet_address_factory(key=True) + mock_signature = Mock(spec=SignedMessage) mock_signature.signature = "0xsignature" wallet_address_with_key.key.unsafe_sign_hash.return_value = mock_signature @@ -594,8 +633,15 @@ def test_sign_payload_api_error(mock_payload_signature, wallet_address_with_key) @patch("cdp.Cdp.api_clients") -def test_ensure_sufficient_balance_sufficient(mock_api_clients, wallet_address, balance_model): +def test_ensure_sufficient_balance_sufficient( + mock_api_clients, wallet_address_factory, balance_model_factory +): """Test the ensure_sufficient_balance method with sufficient balance.""" + wallet_address = wallet_address_factory() + balance_model = balance_model_factory( + amount="5000000000000000000", network_id="base-sepolia", asset_id="eth", decimals=18 + ) + mock_get_balance = Mock() mock_get_balance.return_value = balance_model mock_api_clients.external_addresses.get_external_address_balance = mock_get_balance @@ -608,8 +654,15 @@ def test_ensure_sufficient_balance_sufficient(mock_api_clients, wallet_address, @patch("cdp.Cdp.api_clients") -def test_ensure_sufficient_balance_insufficient(mock_api_clients, wallet_address, balance_model): +def test_ensure_sufficient_balance_insufficient( + mock_api_clients, wallet_address_factory, balance_model_factory +): """Test the ensure_sufficient_balance method with insufficient balance.""" + wallet_address = wallet_address_factory() + balance_model = balance_model_factory( + amount="5000000000000000000", network_id="base-sepolia", asset_id="eth", decimals=18 + ) + mock_get_balance = Mock() mock_get_balance.return_value = balance_model mock_api_clients.external_addresses.get_external_address_balance = mock_get_balance @@ -622,22 +675,28 @@ def test_ensure_sufficient_balance_insufficient(mock_api_clients, wallet_address ) -def test_str_representation(wallet_address): +def test_str_representation(wallet_address_factory): """Test the str representation of a WalletAddress.""" - expected_str = "WalletAddress: (address_id: 0x1234567890123456789012345678901234567890, wallet_id: test-wallet-id-1, network_id: base-sepolia)" + wallet_address = wallet_address_factory() + + expected_str = "WalletAddress: (address_id: 0x1234567890123456789012345678901234567890, wallet_id: test-wallet-id, network_id: base-sepolia)" assert str(wallet_address) == expected_str -def test_repr(wallet_address): +def test_repr(wallet_address_factory): """Test the repr representation of a WalletAddress.""" - expected_repr = "WalletAddress: (address_id: 0x1234567890123456789012345678901234567890, wallet_id: test-wallet-id-1, network_id: base-sepolia)" + wallet_address = wallet_address_factory() + + expected_repr = "WalletAddress: (address_id: 0x1234567890123456789012345678901234567890, wallet_id: test-wallet-id, network_id: base-sepolia)" assert repr(wallet_address) == expected_repr @patch("cdp.Cdp.api_clients") @patch("cdp.Cdp.use_server_signer", True) -def test_wallet_address_deploy_token_total_supply_string(mock_api_clients, wallet_address): +def test_wallet_address_deploy_token_total_supply_string(mock_api_clients, wallet_address_factory): """Test the deploy_token method of a WalletAddress with a string total_supply.""" + wallet_address = wallet_address_factory() + mock_smart_contract = Mock(spec=SmartContract) mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract @@ -662,8 +721,10 @@ def test_wallet_address_deploy_token_total_supply_string(mock_api_clients, walle @patch("cdp.Cdp.api_clients") @patch("cdp.Cdp.use_server_signer", True) -def test_wallet_address_deploy_token_total_supply_number(mock_api_clients, wallet_address): +def test_wallet_address_deploy_token_total_supply_number(mock_api_clients, wallet_address_factory): """Test the deploy_token method of a WalletAddress with a number total_supply.""" + wallet_address = wallet_address_factory() + mock_smart_contract = Mock(spec=SmartContract) mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract @@ -688,8 +749,10 @@ def test_wallet_address_deploy_token_total_supply_number(mock_api_clients, walle @patch("cdp.Cdp.api_clients") @patch("cdp.Cdp.use_server_signer", True) -def test_wallet_address_deploy_token_total_supply_decimal(mock_api_clients, wallet_address): +def test_wallet_address_deploy_token_total_supply_decimal(mock_api_clients, wallet_address_factory): """Test the deploy_token method of a WalletAddress with a Decimal total_supply.""" + wallet_address = wallet_address_factory() + mock_smart_contract = Mock(spec=SmartContract) mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract @@ -714,8 +777,10 @@ def test_wallet_address_deploy_token_total_supply_decimal(mock_api_clients, wall @patch("cdp.Cdp.api_clients") @patch("cdp.Cdp.use_server_signer", True) -def test_wallet_address_deploy_nft(mock_api_clients, wallet_address): +def test_wallet_address_deploy_nft(mock_api_clients, wallet_address_factory): """Test the deploy_nft method of a WalletAddress.""" + wallet_address = wallet_address_factory() + mock_smart_contract = Mock(spec=SmartContract) mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract @@ -740,8 +805,10 @@ def test_wallet_address_deploy_nft(mock_api_clients, wallet_address): @patch("cdp.Cdp.api_clients") @patch("cdp.Cdp.use_server_signer", True) -def test_wallet_address_deploy_multi_token(mock_api_clients, wallet_address): +def test_wallet_address_deploy_multi_token(mock_api_clients, wallet_address_factory): """Test the deploy_multi_token method of a WalletAddress.""" + wallet_address = wallet_address_factory() + mock_smart_contract = Mock(spec=SmartContract) mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract @@ -766,8 +833,10 @@ def test_wallet_address_deploy_multi_token(mock_api_clients, wallet_address): @patch("cdp.Cdp.api_clients") @patch("cdp.Cdp.use_server_signer", True) -def test_wallet_address_deploy_token_with_server_signer(mock_api_clients, wallet_address): +def test_wallet_address_deploy_token_with_server_signer(mock_api_clients, wallet_address_factory): """Test the deploy_token method of a WalletAddress with server signer.""" + wallet_address = wallet_address_factory() + mock_smart_contract = Mock(spec=SmartContract) mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract @@ -795,8 +864,10 @@ def test_wallet_address_deploy_token_with_server_signer(mock_api_clients, wallet @patch("cdp.Cdp.api_clients") @patch("cdp.Cdp.use_server_signer", True) -def test_wallet_address_deploy_nft_with_server_signer(mock_api_clients, wallet_address): +def test_wallet_address_deploy_nft_with_server_signer(mock_api_clients, wallet_address_factory): """Test the deploy_nft method of a WalletAddress with server signer.""" + wallet_address = wallet_address_factory() + mock_smart_contract = Mock(spec=SmartContract) mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract @@ -824,8 +895,12 @@ def test_wallet_address_deploy_nft_with_server_signer(mock_api_clients, wallet_a @patch("cdp.Cdp.api_clients") @patch("cdp.Cdp.use_server_signer", True) -def test_wallet_address_deploy_multi_token_with_server_signer(mock_api_clients, wallet_address): +def test_wallet_address_deploy_multi_token_with_server_signer( + mock_api_clients, wallet_address_factory +): """Test the deploy_multi_token method of a WalletAddress with server signer.""" + wallet_address = wallet_address_factory() + mock_smart_contract = Mock(spec=SmartContract) mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract @@ -852,8 +927,10 @@ def test_wallet_address_deploy_multi_token_with_server_signer(mock_api_clients, @patch("cdp.wallet_address.SmartContract") -def test_deploy_token_api_error(mock_smart_contract, wallet_address_with_key): +def test_deploy_token_api_error(mock_smart_contract, wallet_address_factory): """Test the deploy_token method raises an error when the create API call fails.""" + wallet_address_with_key = wallet_address_factory(key=True) + mock_smart_contract.create.side_effect = Exception("API Error") with pytest.raises(Exception, match="API Error"): @@ -863,8 +940,10 @@ def test_deploy_token_api_error(mock_smart_contract, wallet_address_with_key): @patch("cdp.wallet_address.SmartContract") -def test_deploy_token_broadcast_api_error(mock_smart_contract, wallet_address_with_key): +def test_deploy_token_broadcast_api_error(mock_smart_contract, wallet_address_factory): """Test the deploy_token method raises an error when the broadcast API call fails.""" + wallet_address_with_key = wallet_address_factory(key=True) + mock_smart_contract_instance = Mock(spec=SmartContract) mock_smart_contract.create.return_value = mock_smart_contract_instance mock_smart_contract_instance.broadcast.side_effect = Exception("API Error") @@ -878,8 +957,10 @@ def test_deploy_token_broadcast_api_error(mock_smart_contract, wallet_address_wi @patch("cdp.wallet_address.SmartContract") -def test_deploy_nft_api_error(mock_smart_contract, wallet_address_with_key): +def test_deploy_nft_api_error(mock_smart_contract, wallet_address_factory): """Test the deploy_nft method raises an error when the create API call fails.""" + wallet_address_with_key = wallet_address_factory(key=True) + mock_smart_contract.create.side_effect = Exception("API Error") with pytest.raises(Exception, match="API Error"): @@ -891,8 +972,10 @@ def test_deploy_nft_api_error(mock_smart_contract, wallet_address_with_key): @patch("cdp.wallet_address.SmartContract") -def test_deploy_nft_broadcast_api_error(mock_smart_contract, wallet_address_with_key): +def test_deploy_nft_broadcast_api_error(mock_smart_contract, wallet_address_factory): """Test the deploy_nft method raises an error when the broadcast API call fails.""" + wallet_address_with_key = wallet_address_factory(key=True) + mock_smart_contract_instance = Mock(spec=SmartContract) mock_smart_contract.create.return_value = mock_smart_contract_instance mock_smart_contract_instance.broadcast.side_effect = Exception("API Error") @@ -908,8 +991,10 @@ def test_deploy_nft_broadcast_api_error(mock_smart_contract, wallet_address_with @patch("cdp.wallet_address.SmartContract") -def test_deploy_multi_token_api_error(mock_smart_contract, wallet_address_with_key): +def test_deploy_multi_token_api_error(mock_smart_contract, wallet_address_factory): """Test the deploy_multi_token method raises an error when the create API call fails.""" + wallet_address_with_key = wallet_address_factory(key=True) + mock_smart_contract.create.side_effect = Exception("API Error") with pytest.raises(Exception, match="API Error"): @@ -919,8 +1004,10 @@ def test_deploy_multi_token_api_error(mock_smart_contract, wallet_address_with_k @patch("cdp.wallet_address.SmartContract") -def test_deploy_multi_token_broadcast_api_error(mock_smart_contract, wallet_address_with_key): +def test_deploy_multi_token_broadcast_api_error(mock_smart_contract, wallet_address_factory): """Test the deploy_multi_token method raises an error when the broadcast API call fails.""" + wallet_address_with_key = wallet_address_factory(key=True) + mock_smart_contract_instance = Mock(spec=SmartContract) mock_smart_contract.create.return_value = mock_smart_contract_instance mock_smart_contract_instance.broadcast.side_effect = Exception("API Error") From ccfca49ea091a718be822c654c6a5314ec899276 Mon Sep 17 00:00:00 2001 From: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> Date: Tue, 1 Oct 2024 19:25:02 -0400 Subject: [PATCH 14/40] feat(PSDK-499): Message Hashing Utilities for EIP-191/712 (#23) --- CHANGELOG.md | 1 + cdp/__init__.py | 3 +++ cdp/hash_utils.py | 40 ++++++++++++++++++++++++++++++++++++ tests/test_hash_utils.py | 44 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 88 insertions(+) create mode 100644 cdp/hash_utils.py create mode 100644 tests/test_hash_utils.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 585a06a..de6e6e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ - Contract invocation support. - Arbitrary message signing support. - Deploy ERC20, ERC721, and ERC1155 smart contracts. +- Hashing utilities for EIP-191 / EIP-712 data messages. ### Fixed diff --git a/cdp/__init__.py b/cdp/__init__.py index 0c2f049..33a4168 100644 --- a/cdp/__init__.py +++ b/cdp/__init__.py @@ -6,6 +6,7 @@ from cdp.cdp import Cdp from cdp.contract_invocation import ContractInvocation from cdp.faucet_transaction import FaucetTransaction +from cdp.hash_utils import hash_message, hash_typed_data_message from cdp.payload_signature import PayloadSignature from cdp.smart_contract import SmartContract from cdp.sponsored_send import SponsoredSend @@ -34,4 +35,6 @@ "SponsoredSend", "PayloadSignature", "SmartContract", + "hash_message", + "hash_typed_data_message", ] diff --git a/cdp/hash_utils.py b/cdp/hash_utils.py new file mode 100644 index 0000000..70879c6 --- /dev/null +++ b/cdp/hash_utils.py @@ -0,0 +1,40 @@ +from typing import Any + +from eth_account.messages import _hash_eip191_message, encode_defunct, encode_typed_data +from eth_utils import to_hex + + +def hash_message(message_text: str) -> str: + """Hashes a message according to EIP-191 and returns the hash as a 0x-prefixed hexadecimal string. + + This function prefixes the message with the standard Ethereum message prefix and hashes it using Keccak-256. + + Args: + message_text (str): The message to hash. + + Returns: + str: The 0x-prefixed hexadecimal string of the message hash. + + """ + message = encode_defunct(text=message_text) + message_hash = _hash_eip191_message(message) + + return to_hex(message_hash) + + +def hash_typed_data_message(typed_data: dict[str, Any]) -> str: + """Hashes typed data according to EIP-712 and returns the hash as a 0x-prefixed hexadecimal string. + + This function encodes the typed data as per EIP-712 and hashes it using Keccak-256. + + Args: + typed_data (dict): The typed data to hash, following the EIP-712 specification. + + Returns: + str: The 0x-prefixed hexadecimal string of the typed data hash. + + """ + typed_data_message = encode_typed_data(full_message=typed_data) + typed_data_message_hash = _hash_eip191_message(typed_data_message) + + return to_hex(typed_data_message_hash) diff --git a/tests/test_hash_utils.py b/tests/test_hash_utils.py new file mode 100644 index 0000000..318d7ff --- /dev/null +++ b/tests/test_hash_utils.py @@ -0,0 +1,44 @@ +from cdp.hash_utils import hash_message, hash_typed_data_message + + +def test_hash_message(): + """Test hash_message utility method.""" + message_hash = hash_message("Hello, EIP-191!") + assert message_hash == "0x54c2490066f5b62dd2e2ea2310c2b3d63039bbce5e3f96175a1b66a0c484e74f" + + +def test_hash_typed_data_message(): + """Test hash_typed_data_message utility method.""" + typed_data = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"}, + ], + "Person": [{"name": "name", "type": "string"}, {"name": "wallet", "type": "address"}], + "Mail": [ + {"name": "from", "type": "Person"}, + {"name": "to", "type": "Person"}, + {"name": "contents", "type": "string"}, + ], + }, + "primaryType": "Mail", + "domain": { + "name": "Ether Mail", + "version": "1", + "chainId": 1, + "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", + }, + "message": { + "from": {"name": "Alice", "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826"}, + "to": {"name": "Bob", "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB"}, + "contents": "Hello, Bob!", + }, + } + typed_data_message_hash = hash_typed_data_message(typed_data) + assert ( + typed_data_message_hash + == "0x4644890d40a2ebb8cbf599801c4412c03f8027f04044d0dd12a0605fbd72bb8b" + ) From 8b9df0a5cf16eb8246baaa4df748f3111b78faf2 Mon Sep 17 00:00:00 2001 From: rohan-agarwal-coinbase Date: Tue, 1 Oct 2024 19:29:35 -0400 Subject: [PATCH 15/40] Fix wallet_address tests to mock at the smart_contract level instead of API level (#22) * Fix * WIP * lint --- tests/test_wallet_address.py | 212 +++++++++++++++-------------------- 1 file changed, 92 insertions(+), 120 deletions(-) diff --git a/tests/test_wallet_address.py b/tests/test_wallet_address.py index 336e0fd..d081131 100644 --- a/tests/test_wallet_address.py +++ b/tests/test_wallet_address.py @@ -8,11 +8,6 @@ from eth_utils import to_bytes from web3 import Web3 -from cdp.client.models.create_smart_contract_request import CreateSmartContractRequest -from cdp.client.models.multi_token_contract_options import MultiTokenContractOptions -from cdp.client.models.nft_contract_options import NFTContractOptions -from cdp.client.models.smart_contract_options import SmartContractOptions -from cdp.client.models.token_contract_options import TokenContractOptions from cdp.contract_invocation import ContractInvocation from cdp.errors import InsufficientFundsError from cdp.payload_signature import PayloadSignature @@ -691,239 +686,216 @@ def test_repr(wallet_address_factory): assert repr(wallet_address) == expected_repr -@patch("cdp.Cdp.api_clients") -@patch("cdp.Cdp.use_server_signer", True) -def test_wallet_address_deploy_token_total_supply_string(mock_api_clients, wallet_address_factory): +@patch("cdp.wallet_address.SmartContract") +@patch("cdp.Cdp.use_server_signer", False) +def test_wallet_address_deploy_token_total_supply_string(mock_smart_contract, wallet_address_factory): """Test the deploy_token method of a WalletAddress with a string total_supply.""" - wallet_address = wallet_address_factory() + wallet_address = wallet_address_factory(key=True) - mock_smart_contract = Mock(spec=SmartContract) - mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract + mock_smart_contract_instance = Mock(spec=SmartContract) + mock_smart_contract.create.return_value = mock_smart_contract_instance smart_contract = wallet_address.deploy_token( name="TestToken", symbol="TT", total_supply="1000000" ) assert isinstance(smart_contract, SmartContract) - mock_api_clients.smart_contracts.create_smart_contract.assert_called_once_with( + mock_smart_contract.create.assert_called_once_with( wallet_id=wallet_address.wallet_id, address_id=wallet_address.address_id, - create_smart_contract_request=CreateSmartContractRequest( - type="erc20", - options=SmartContractOptions( - actual_instance=TokenContractOptions( - name="TestToken", symbol="TT", total_supply="1000000" - ) - ), + type=mock_smart_contract.Type.ERC20, + options=mock_smart_contract.TokenContractOptions( + name="TestToken", symbol="TT", total_supply="1000000" ), ) + mock_smart_contract_instance.sign.assert_called_once_with(wallet_address.key) + mock_smart_contract_instance.broadcast.assert_called_once() - -@patch("cdp.Cdp.api_clients") -@patch("cdp.Cdp.use_server_signer", True) -def test_wallet_address_deploy_token_total_supply_number(mock_api_clients, wallet_address_factory): +@patch("cdp.wallet_address.SmartContract") +@patch("cdp.Cdp.use_server_signer", False) +def test_wallet_address_deploy_token_total_supply_number(mock_smart_contract, wallet_address_factory): """Test the deploy_token method of a WalletAddress with a number total_supply.""" - wallet_address = wallet_address_factory() + wallet_address = wallet_address_factory(key=True) - mock_smart_contract = Mock(spec=SmartContract) - mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract + mock_smart_contract_instance = Mock(spec=SmartContract) + mock_smart_contract.create.return_value = mock_smart_contract_instance smart_contract = wallet_address.deploy_token( name="TestToken", symbol="TT", total_supply=1000000 ) assert isinstance(smart_contract, SmartContract) - mock_api_clients.smart_contracts.create_smart_contract.assert_called_once_with( + mock_smart_contract.create.assert_called_once_with( wallet_id=wallet_address.wallet_id, address_id=wallet_address.address_id, - create_smart_contract_request=CreateSmartContractRequest( - type="erc20", - options=SmartContractOptions( - actual_instance=TokenContractOptions( - name="TestToken", symbol="TT", total_supply="1000000" - ) - ), + type=mock_smart_contract.Type.ERC20, + options=mock_smart_contract.TokenContractOptions( + name="TestToken", symbol="TT", total_supply="1000000" ), ) + mock_smart_contract_instance.sign.assert_called_once_with(wallet_address.key) + mock_smart_contract_instance.broadcast.assert_called_once() - -@patch("cdp.Cdp.api_clients") -@patch("cdp.Cdp.use_server_signer", True) -def test_wallet_address_deploy_token_total_supply_decimal(mock_api_clients, wallet_address_factory): +@patch("cdp.wallet_address.SmartContract") +@patch("cdp.Cdp.use_server_signer", False) +def test_wallet_address_deploy_token_total_supply_decimal(mock_smart_contract, wallet_address_factory): """Test the deploy_token method of a WalletAddress with a Decimal total_supply.""" - wallet_address = wallet_address_factory() + wallet_address = wallet_address_factory(key=True) - mock_smart_contract = Mock(spec=SmartContract) - mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract + mock_smart_contract_instance = Mock(spec=SmartContract) + mock_smart_contract.create.return_value = mock_smart_contract_instance smart_contract = wallet_address.deploy_token( name="TestToken", symbol="TT", total_supply=Decimal("1000000.5") ) assert isinstance(smart_contract, SmartContract) - mock_api_clients.smart_contracts.create_smart_contract.assert_called_once_with( + mock_smart_contract.create.assert_called_once_with( wallet_id=wallet_address.wallet_id, address_id=wallet_address.address_id, - create_smart_contract_request=CreateSmartContractRequest( - type="erc20", - options=SmartContractOptions( - actual_instance=TokenContractOptions( - name="TestToken", symbol="TT", total_supply="1000000.5" - ) - ), + type=mock_smart_contract.Type.ERC20, + options=mock_smart_contract.TokenContractOptions( + name="TestToken", symbol="TT", total_supply="1000000.5" ), ) + mock_smart_contract_instance.sign.assert_called_once_with(wallet_address.key) + mock_smart_contract_instance.broadcast.assert_called_once() - -@patch("cdp.Cdp.api_clients") -@patch("cdp.Cdp.use_server_signer", True) -def test_wallet_address_deploy_nft(mock_api_clients, wallet_address_factory): +@patch("cdp.wallet_address.SmartContract") +@patch("cdp.Cdp.use_server_signer", False) +def test_wallet_address_deploy_nft(mock_smart_contract, wallet_address_factory): """Test the deploy_nft method of a WalletAddress.""" - wallet_address = wallet_address_factory() + wallet_address = wallet_address_factory(key=True) - mock_smart_contract = Mock(spec=SmartContract) - mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract + mock_smart_contract_instance = Mock(spec=SmartContract) + mock_smart_contract.create.return_value = mock_smart_contract_instance smart_contract = wallet_address.deploy_nft( name="TestNFT", symbol="TNFT", base_uri="https://example.com/nft/" ) assert isinstance(smart_contract, SmartContract) - mock_api_clients.smart_contracts.create_smart_contract.assert_called_once_with( + mock_smart_contract.create.assert_called_once_with( wallet_id=wallet_address.wallet_id, address_id=wallet_address.address_id, - create_smart_contract_request=CreateSmartContractRequest( - type="erc721", - options=SmartContractOptions( - actual_instance=NFTContractOptions( - name="TestNFT", symbol="TNFT", base_uri="https://example.com/nft/" - ) - ), + type=mock_smart_contract.Type.ERC721, + options=mock_smart_contract.NFTContractOptions( + name="TestNFT", symbol="TNFT", base_uri="https://example.com/nft/" ), ) + mock_smart_contract_instance.sign.assert_called_once_with(wallet_address.key) + mock_smart_contract_instance.broadcast.assert_called_once() -@patch("cdp.Cdp.api_clients") -@patch("cdp.Cdp.use_server_signer", True) -def test_wallet_address_deploy_multi_token(mock_api_clients, wallet_address_factory): +@patch("cdp.wallet_address.SmartContract") +@patch("cdp.Cdp.use_server_signer", False) +def test_wallet_address_deploy_multi_token(mock_smart_contract, wallet_address_factory): """Test the deploy_multi_token method of a WalletAddress.""" - wallet_address = wallet_address_factory() + wallet_address = wallet_address_factory(key=True) - mock_smart_contract = Mock(spec=SmartContract) - mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract + mock_smart_contract_instance = Mock(spec=SmartContract) + mock_smart_contract.create.return_value = mock_smart_contract_instance smart_contract = wallet_address.deploy_multi_token( uri="https://example.com/multi-token/{id}.json" ) assert isinstance(smart_contract, SmartContract) - mock_api_clients.smart_contracts.create_smart_contract.assert_called_once_with( + mock_smart_contract.create.assert_called_once_with( wallet_id=wallet_address.wallet_id, address_id=wallet_address.address_id, - create_smart_contract_request=CreateSmartContractRequest( - type="erc1155", - options=SmartContractOptions( - actual_instance=MultiTokenContractOptions( - uri="https://example.com/multi-token/{id}.json" - ) - ), + type=mock_smart_contract.Type.ERC1155, + options=mock_smart_contract.MultiTokenContractOptions( + uri="https://example.com/multi-token/{id}.json" ), ) + mock_smart_contract_instance.sign.assert_called_once_with(wallet_address.key) + mock_smart_contract_instance.broadcast.assert_called_once() -@patch("cdp.Cdp.api_clients") +@patch("cdp.wallet_address.SmartContract") @patch("cdp.Cdp.use_server_signer", True) -def test_wallet_address_deploy_token_with_server_signer(mock_api_clients, wallet_address_factory): +def test_wallet_address_deploy_token_with_server_signer( + mock_smart_contract, wallet_address_factory +): """Test the deploy_token method of a WalletAddress with server signer.""" wallet_address = wallet_address_factory() - mock_smart_contract = Mock(spec=SmartContract) - mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract + mock_smart_contract_instance = Mock(spec=SmartContract) + mock_smart_contract.create.return_value = mock_smart_contract_instance smart_contract = wallet_address.deploy_token( name="TestToken", symbol="TT", total_supply="1000000" ) assert isinstance(smart_contract, SmartContract) - mock_api_clients.smart_contracts.create_smart_contract.assert_called_once_with( + mock_smart_contract.create.assert_called_once_with( wallet_id=wallet_address.wallet_id, address_id=wallet_address.address_id, - create_smart_contract_request=CreateSmartContractRequest( - type="erc20", - options=SmartContractOptions( - actual_instance=TokenContractOptions( - name="TestToken", symbol="TT", total_supply="1000000" - ) - ), + type=mock_smart_contract.Type.ERC20, + options=mock_smart_contract.TokenContractOptions( + name="TestToken", symbol="TT", total_supply="1000000" ), ) # Verify that sign and broadcast methods are not called when using server signer - mock_smart_contract.sign.assert_not_called() - mock_smart_contract.broadcast.assert_not_called() + mock_smart_contract_instance.sign.assert_not_called() + mock_smart_contract_instance.broadcast.assert_not_called() -@patch("cdp.Cdp.api_clients") +@patch("cdp.wallet_address.SmartContract") @patch("cdp.Cdp.use_server_signer", True) -def test_wallet_address_deploy_nft_with_server_signer(mock_api_clients, wallet_address_factory): +def test_wallet_address_deploy_nft_with_server_signer(mock_smart_contract, wallet_address_factory): """Test the deploy_nft method of a WalletAddress with server signer.""" wallet_address = wallet_address_factory() - mock_smart_contract = Mock(spec=SmartContract) - mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract + mock_smart_contract_instance = Mock(spec=SmartContract) + mock_smart_contract.create.return_value = mock_smart_contract_instance smart_contract = wallet_address.deploy_nft( name="TestNFT", symbol="TNFT", base_uri="https://example.com/nft/" ) assert isinstance(smart_contract, SmartContract) - mock_api_clients.smart_contracts.create_smart_contract.assert_called_once_with( + mock_smart_contract.create.assert_called_once_with( wallet_id=wallet_address.wallet_id, address_id=wallet_address.address_id, - create_smart_contract_request=CreateSmartContractRequest( - type="erc721", - options=SmartContractOptions( - actual_instance=NFTContractOptions( - name="TestNFT", symbol="TNFT", base_uri="https://example.com/nft/" - ) - ), + type=mock_smart_contract.Type.ERC721, + options=mock_smart_contract.NFTContractOptions( + name="TestNFT", symbol="TNFT", base_uri="https://example.com/nft/" ), ) # Verify that sign and broadcast methods are not called when using server signer - mock_smart_contract.sign.assert_not_called() - mock_smart_contract.broadcast.assert_not_called() + mock_smart_contract_instance.sign.assert_not_called() + mock_smart_contract_instance.broadcast.assert_not_called() -@patch("cdp.Cdp.api_clients") +@patch("cdp.wallet_address.SmartContract") @patch("cdp.Cdp.use_server_signer", True) def test_wallet_address_deploy_multi_token_with_server_signer( - mock_api_clients, wallet_address_factory + mock_smart_contract, wallet_address_factory ): """Test the deploy_multi_token method of a WalletAddress with server signer.""" wallet_address = wallet_address_factory() - mock_smart_contract = Mock(spec=SmartContract) - mock_api_clients.smart_contracts.create_smart_contract.return_value = mock_smart_contract + mock_smart_contract_instance = Mock(spec=SmartContract) + mock_smart_contract.create.return_value = mock_smart_contract_instance smart_contract = wallet_address.deploy_multi_token( uri="https://example.com/multi-token/{id}.json" ) assert isinstance(smart_contract, SmartContract) - mock_api_clients.smart_contracts.create_smart_contract.assert_called_once_with( + mock_smart_contract.create.assert_called_once_with( wallet_id=wallet_address.wallet_id, address_id=wallet_address.address_id, - create_smart_contract_request=CreateSmartContractRequest( - type="erc1155", - options=SmartContractOptions( - actual_instance=MultiTokenContractOptions( - uri="https://example.com/multi-token/{id}.json" - ) - ), + type=mock_smart_contract.Type.ERC1155, + options=mock_smart_contract.MultiTokenContractOptions( + uri="https://example.com/multi-token/{id}.json" ), ) # Verify that sign and broadcast methods are not called when using server signer - mock_smart_contract.sign.assert_not_called() - mock_smart_contract.broadcast.assert_not_called() + mock_smart_contract_instance.sign.assert_not_called() + mock_smart_contract_instance.broadcast.assert_not_called() @patch("cdp.wallet_address.SmartContract") From 59ec96e8240ba17d884c727ed664d7b0981c0844 Mon Sep 17 00:00:00 2001 From: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> Date: Tue, 1 Oct 2024 19:39:16 -0400 Subject: [PATCH 16/40] Release 0.0.4 (#24) --- CHANGELOG.md | 2 ++ cdp/__version__.py | 2 +- docs/conf.py | 2 +- pyproject.toml | 2 +- 4 files changed, 5 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index de6e6e6..e78d7fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## [0.0.4] - 2024-10-1 + ### Added - Contract invocation support. diff --git a/cdp/__version__.py b/cdp/__version__.py index 27fdca4..81f0fde 100644 --- a/cdp/__version__.py +++ b/cdp/__version__.py @@ -1 +1 @@ -__version__ = "0.0.3" +__version__ = "0.0.4" diff --git a/docs/conf.py b/docs/conf.py index e9c96db..d81a100 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -14,7 +14,7 @@ project = 'CDP SDK' author = 'Coinbase Developer Platform' -release = '0.0.3' +release = '0.0.4' # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration diff --git a/pyproject.toml b/pyproject.toml index 782d916..b0805f8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "cdp-sdk" -version = "0.0.3" +version = "0.0.4" description = "CDP Python SDK" readme = "README.md" authors = [{name = "John Peterson", email = "john.peterson@coinbase.com"}] From a09f7bfefe0a1eba5816414b1f80ab076c104931 Mon Sep 17 00:00:00 2001 From: xinyu-li-cb <142266583+xinyu-li-cb@users.noreply.github.com> Date: Thu, 3 Oct 2024 14:30:44 -0700 Subject: [PATCH 17/40] [History] add balance history and transactions function for address (#25) * [History] add balance history and transactions function for address * update changelog * fix merge typo * fix lint * address comment * minor * minor * address comments * fix merge issue * lint --- CHANGELOG.md | 4 + cdp/address.py | 30 ++++ cdp/api_clients.py | 34 +++++ cdp/historical_balance.py | 129 ++++++++++++++++++ cdp/transaction.py | 35 +++++ tests/factories/historical_balance_factory.py | 41 ++++++ tests/test_address.py | 77 +++++++++++ tests/test_historical_balance.py | 86 ++++++++++++ tests/test_transaction.py | 33 +++++ 9 files changed, 469 insertions(+) create mode 100644 cdp/historical_balance.py create mode 100644 tests/factories/historical_balance_factory.py create mode 100644 tests/test_historical_balance.py diff --git a/CHANGELOG.md b/CHANGELOG.md index e78d7fa..27a5f86 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +### Added + +- Support list historical balances and list transactions function for address. + ## [0.0.4] - 2024-10-1 ### Added diff --git a/cdp/address.py b/cdp/address.py index f3eadee..90dcdd0 100644 --- a/cdp/address.py +++ b/cdp/address.py @@ -1,3 +1,4 @@ +from collections.abc import Iterator from decimal import Decimal from cdp.asset import Asset @@ -5,6 +6,8 @@ from cdp.balance_map import BalanceMap from cdp.cdp import Cdp from cdp.faucet_transaction import FaucetTransaction +from cdp.historical_balance import HistoricalBalance +from cdp.transaction import Transaction class Address: @@ -98,6 +101,33 @@ def balances(self): return BalanceMap.from_models(response.data) + def historical_balances(self, asset_id) -> Iterator[HistoricalBalance]: + """List historical balances. + + Args: + asset_id (str): The asset ID. + + Returns: + Iterator[HistoricalBalance]: An iterator of HistoricalBalance objects. + + Raises: + Exception: If there's an error listing the historical balances. + + """ + return HistoricalBalance.list(network_id=self.network_id, address_id=self.address_id, asset_id=asset_id) + + def transactions(self) -> Iterator[Transaction]: + """List transactions of the address. + + Returns: + Iterator[Transaction]: An iterator of Transaction objects. + + Raises: + Exception: If there's an error listing the transactions. + + """ + return Transaction.list(network_id=self.network_id, address_id=self.address_id) + def __str__(self) -> str: """Return a string representation of the Address.""" return f"Address: (address_id: {self.address_id}, network_id: {self.network_id})" diff --git a/cdp/api_clients.py b/cdp/api_clients.py index a63b0e1..b93c943 100644 --- a/cdp/api_clients.py +++ b/cdp/api_clients.py @@ -1,11 +1,13 @@ from cdp.cdp_api_client import CdpApiClient from cdp.client.api.addresses_api import AddressesApi from cdp.client.api.assets_api import AssetsApi +from cdp.client.api.balance_history_api import BalanceHistoryApi from cdp.client.api.contract_invocations_api import ContractInvocationsApi from cdp.client.api.external_addresses_api import ExternalAddressesApi from cdp.client.api.networks_api import NetworksApi from cdp.client.api.smart_contracts_api import SmartContractsApi from cdp.client.api.trades_api import TradesApi +from cdp.client.api.transaction_history_api import TransactionHistoryApi from cdp.client.api.transfers_api import TransfersApi from cdp.client.api.wallets_api import WalletsApi @@ -46,6 +48,8 @@ def __init__(self, cdp_client: CdpApiClient) -> None: self._trades: TradesApi | None = None self._contract_invocations: ContractInvocationsApi | None = None self._smart_contracts: SmartContractsApi | None = None + self._balance_history: BalanceHistoryApi | None = None + self._transaction_history: TransactionHistoryApi | None = None @property def wallets(self) -> WalletsApi: @@ -167,6 +171,21 @@ def contract_invocations(self) -> ContractInvocationsApi: self._contract_invocations = ContractInvocationsApi(api_client=self._cdp_client) return self._contract_invocations + @property + def balance_history(self) -> BalanceHistoryApi: + """Get the BalanceHistoryApi client instance. + + Returns: + BalanceHistoryApi: The BalanceHistoryApi client instance. + + Note: + This property lazily initializes the BalanceHistoryApi client on first access. + + """ + if self._balance_history is None: + self._balance_history = BalanceHistoryApi(api_client=self._cdp_client) + return self._balance_history + @property def smart_contracts(self) -> SmartContractsApi: """Get the SmartContractsApi client instance. @@ -181,3 +200,18 @@ def smart_contracts(self) -> SmartContractsApi: if self._smart_contracts is None: self._smart_contracts = SmartContractsApi(api_client=self._cdp_client) return self._smart_contracts + + @property + def transaction_history(self) -> TransactionHistoryApi: + """Get the TransactionHistoryApi client instance. + + Returns: + TransactionHistoryApi: The TransactionHistoryApi client instance. + + Note: + This property lazily initializes the TransactionHistoryApi client on first access. + + """ + if self._transaction_history is None: + self._transaction_history = TransactionHistoryApi(api_client=self._cdp_client) + return self._transaction_history diff --git a/cdp/historical_balance.py b/cdp/historical_balance.py new file mode 100644 index 0000000..f58c98f --- /dev/null +++ b/cdp/historical_balance.py @@ -0,0 +1,129 @@ +from collections.abc import Iterator +from decimal import Decimal + +from cdp.asset import Asset +from cdp.cdp import Cdp +from cdp.client.models.address_historical_balance_list import AddressHistoricalBalanceList +from cdp.client.models.historical_balance import HistoricalBalance as HistoricalBalanceModel + + +class HistoricalBalance: + """A class representing a balance.""" + + def __init__(self, amount: Decimal, asset: Asset, block_height: str, block_hash: str): + """Initialize the Balance class. + + Args: + amount (Decimal): The amount. + asset (Asset): The asset. + block_height (str): the block height where the balance is in. + block_hash (str): the block hash where the balance is in. + + """ + self._amount = amount + self._asset = asset + self._block_height = block_height + self._block_hash = block_hash + + @classmethod + def from_model(cls, model: HistoricalBalanceModel) -> "HistoricalBalance": + """Create a Balance instance from a model. + + Args: + model (BalanceModel): The model representing the balance. + asset_id (Optional[str]): The asset ID. + + Returns: + Balance: The Balance instance. + + """ + asset = Asset.from_model(model.asset) + + return cls( + amount=asset.from_atomic_amount(model.amount), + asset=asset, + block_height=model.block_height, + block_hash=model.block_hash + ) + + @classmethod + def list(cls, network_id: str, address_id: str, asset_id: str) -> Iterator["HistoricalBalance"]: + """List historical balances of an address of an asset. + + Args: + network_id (str): The ID of the network to list historical balance for. + address_id (str): The ID of the address to list historical balance for. + asset_id(str): The asset ID to list historical balance. + + Returns: + Iterator[Transaction]: An iterator of HistoricalBalance objects. + + Raises: + Exception: If there's an error listing the historical_balances. + + """ + page = None + while True: + response: AddressHistoricalBalanceList = Cdp.api_clients.balance_history.list_address_historical_balance( + network_id=network_id, + address_id=address_id, + asset_id=Asset.primary_denomination(asset_id), + limit=100, + page=page, + ) + + for model in response.data: + yield cls.from_model(model) + + if not response.has_more: + break + + page = response.next_page + + @property + def amount(self) -> Decimal: + """Get the amount. + + Returns: + Decimal: The amount. + + """ + return self._amount + + @property + def asset(self) -> Asset: + """Get the asset. + + Returns: + Asset: The asset. + + """ + return self._asset + + @property + def block_height(self) -> str: + """Get the block height. + + Returns: + str: The block height. + + """ + return self._block_height + + @property + def block_hash(self) -> str: + """Get the block hash. + + Returns: + str: The block hash. + + """ + return self._block_hash + + def __str__(self) -> str: + """Return a string representation of the Balance.""" + return f"HistoricalBalance: (amount: {self.amount}, asset: {self.asset}, block_height: {self.block_height}, block_hash: {self.block_hash})" + + def __repr__(self) -> str: + """Return a string representation of the Balance.""" + return str(self) diff --git a/cdp/transaction.py b/cdp/transaction.py index 816ad1a..46e7f2c 100644 --- a/cdp/transaction.py +++ b/cdp/transaction.py @@ -1,11 +1,14 @@ import json +from collections.abc import Iterator from enum import Enum from eth_account.signers.local import LocalAccount from eth_account.typed_transactions import DynamicFeeTransaction from web3 import Web3 +from cdp.cdp import Cdp from cdp.client.models import Transaction as TransactionModel +from cdp.client.models.address_transaction_list import AddressTransactionList class Transaction: @@ -52,6 +55,38 @@ def __init__(self, model: TransactionModel): self._raw: DynamicFeeTransaction | None = None self._signature: str | None = model.signed_payload + @classmethod + def list(cls, network_id: str, address_id: str) -> Iterator["Transaction"]: + """List transactions of the address. + + Args: + network_id (str): The ID of the network to list transaction for. + address_id (str): The ID of the address to list transaction for. + + Returns: + Iterator[Transaction]: An iterator of Transaction objects. + + Raises: + Exception: If there's an error listing the transactions. + + """ + page = None + while True: + response: AddressTransactionList = Cdp.api_clients.transaction_history.list_address_transactions( + network_id=network_id, + address_id=address_id, + limit=1, + page=page, + ) + + for model in response.data: + yield cls(model) + + if not response.has_more: + break + + page = response.next_page + @property def unsigned_payload(self) -> str: """Get the unsigned payload.""" diff --git a/tests/factories/historical_balance_factory.py b/tests/factories/historical_balance_factory.py new file mode 100644 index 0000000..aabd4b2 --- /dev/null +++ b/tests/factories/historical_balance_factory.py @@ -0,0 +1,41 @@ +import pytest + +from cdp.client.models.historical_balance import HistoricalBalance as HistoricalBalanceModel +from cdp.historical_balance import HistoricalBalance + + +@pytest.fixture +def historical_balance_model_factory(asset_model_factory): + """Create and return a factory for creating HistoricalBalance fixtures.""" + + def _create_historical_balance_model( + amount="1000000000000000000", + network_id="base-sepolia", + asset_id="eth", + decimals=18, + block_hash="0xblockhash", + block_height="12345" + ): + asset_model = asset_model_factory(network_id, asset_id, decimals) + return HistoricalBalanceModel( + amount=amount, block_hash=block_hash, block_height=block_height, asset=asset_model) + + return _create_historical_balance_model + + +@pytest.fixture +def historical_balance_factory(asset_factory): + """Create and return a factory for creating HistoricalBalance fixtures.""" + + def _create_historical_balance( + amount="1000000000000000000", + network_id="base-sepolia", + asset_id="eth", + decimals=18, + block_hash="0xblockhash", + block_height="12345" + ): + asset = asset_factory(network_id=network_id, asset_id=asset_id, decimals=decimals) + return HistoricalBalance(amount, asset, block_height, block_hash) + + return _create_historical_balance diff --git a/tests/test_address.py b/tests/test_address.py index b88f781..90a3a48 100644 --- a/tests/test_address.py +++ b/tests/test_address.py @@ -8,6 +8,8 @@ from cdp.client.exceptions import ApiException from cdp.errors import ApiError from cdp.faucet_transaction import FaucetTransaction +from cdp.historical_balance import HistoricalBalance +from cdp.transaction import Transaction def test_address_initialization(address_factory): @@ -157,6 +159,81 @@ def test_address_balances_api_error(mock_api_clients, address_factory): address.balances() +@patch("cdp.Cdp.api_clients") +def test_address_historical_balances(mock_api_clients, address_factory, historical_balance_model_factory): + """Test the historical_balances method of an Address.""" + address = address_factory() + historical_balance_model = historical_balance_model_factory() + + mock_list_historical_balances = Mock() + mock_list_historical_balances.return_value = Mock(data=[historical_balance_model], has_more=False) + mock_api_clients.balance_history.list_address_historical_balance = mock_list_historical_balances + + historical_balances = address.historical_balances("eth") + + assert len(list(historical_balances)) == 1 + assert all(isinstance(h, HistoricalBalance) for h in historical_balances) + mock_list_historical_balances.assert_called_once_with( + network_id=address.network_id, + address_id=address.address_id, + asset_id="eth", + limit=100, + page=None + ) + + +@patch("cdp.Cdp.api_clients") +def test_address_historical_balances_error(mock_api_clients, address_factory): + """Test the historical_balances method of an Address raises an error when the API call fails.""" + address = address_factory() + + mock_list_historical_balances = Mock() + err = ApiException(500, "boom") + mock_list_historical_balances.side_effect = ApiError(err, code="boom", message="boom") + mock_api_clients.balance_history.list_address_historical_balance = mock_list_historical_balances + + with pytest.raises(ApiError): + historical_balances = address.historical_balances("eth") + next(historical_balances) + + +@patch("cdp.Cdp.api_clients") +def test_address_transactions(mock_api_clients, address_factory, transaction_model_factory): + """Test the list transactions method of an Address.""" + address = address_factory() + onchain_transaction_model = transaction_model_factory() + + mock_list_transactions = Mock() + mock_list_transactions.return_value = Mock(data=[onchain_transaction_model], has_more=False) + mock_api_clients.transaction_history.list_address_transactions = mock_list_transactions + + transactions = address.transactions() + + assert len(list(transactions)) == 1 + assert all(isinstance(t, Transaction) for t in transactions) + mock_list_transactions.assert_called_once_with( + network_id=address.network_id, + address_id=address.address_id, + limit=1, + page=None + ) + + +@patch("cdp.Cdp.api_clients") +def test_address_transactions_error(mock_api_clients, address_factory): + """Test the list transactions method of an Address raises an error when the API call fails.""" + address = address_factory() + + mock_list_transactions = Mock() + err = ApiException(500, "boom") + mock_list_transactions.side_effect = ApiError(err, code="boom", message="boom") + mock_api_clients.transaction_history.list_address_transactions = mock_list_transactions + + with pytest.raises(ApiError): + transactions = address.transactions() + next(transactions) + + def test_address_str_representation(address_factory): """Test the str representation of an Address.""" address = address_factory() diff --git a/tests/test_historical_balance.py b/tests/test_historical_balance.py new file mode 100644 index 0000000..a50f126 --- /dev/null +++ b/tests/test_historical_balance.py @@ -0,0 +1,86 @@ +from decimal import Decimal +from unittest.mock import Mock, patch + +import pytest + +from cdp.asset import Asset +from cdp.client.exceptions import ApiException +from cdp.errors import ApiError +from cdp.historical_balance import HistoricalBalance + + +def test_historical_balance_initialization(asset_factory): + """Test historical_balance initialization.""" + asset = asset_factory(asset_id="eth", decimals=18) + + historical_balance = HistoricalBalance(Decimal("1"), asset, "12345", "0xblockhash") + assert historical_balance.amount == Decimal("1") + assert historical_balance.asset == asset + + +def test_historical_balance_from_model(historical_balance_model_factory): + """Test historical_balance from model.""" + historical_balance_model = historical_balance_model_factory() + + balance = HistoricalBalance.from_model(historical_balance_model) + assert balance.amount == Decimal("1") + assert isinstance(balance.asset, Asset) + assert balance.asset.asset_id == "eth" + + +def test_historical_balance_amount(historical_balance_factory): + """Test historical balance amount.""" + historical_balance = historical_balance_factory(amount=1.5) + + assert historical_balance.amount == Decimal("1.5") + + +def test_historical_balance_str_representation(historical_balance_factory): + """Test historical balance string representation.""" + historical_balance = historical_balance_factory(amount=1.5) + assert ( + str(historical_balance) + == "HistoricalBalance: (amount: 1.5, asset: Asset: (asset_id: eth, network_id: base-sepolia, contract_address: None, decimals: 18), block_height: 12345, block_hash: 0xblockhash)" + ) + + +def test_historical_balance_repr(historical_balance_factory): + """Test historical balance repr.""" + historical_balance = historical_balance_factory(amount=1.5) + assert ( + repr(historical_balance) + == "HistoricalBalance: (amount: 1.5, asset: Asset: (asset_id: eth, network_id: base-sepolia, contract_address: None, decimals: 18), block_height: 12345, block_hash: 0xblockhash)" + ) + + +@patch("cdp.Cdp.api_clients") +def test_list_historical_balances(mock_api_clients, historical_balance_model_factory): + """Test the historical_balances method.""" + mock_list_historical_balances = Mock() + mock_list_historical_balances.return_value = Mock(data=[historical_balance_model_factory()], has_more=False) + mock_api_clients.balance_history.list_address_historical_balance = mock_list_historical_balances + + historical_balances = HistoricalBalance.list(network_id="test-network-id", address_id="0xaddressid", asset_id="eth") + + assert len(list(historical_balances)) == 1 + assert all(isinstance(h, HistoricalBalance) for h in historical_balances) + mock_list_historical_balances.assert_called_once_with( + network_id="test-network-id", + address_id="0xaddressid", + asset_id="eth", + limit=100, + page=None + ) + + +@patch("cdp.Cdp.api_clients") +def test_list_historical_balances_error(mock_api_clients): + """Test the historical_balances method getting api error.""" + mock_list_historical_balances = Mock() + err = ApiException(500, "boom") + mock_list_historical_balances.side_effect = ApiError(err, code="boom", message="boom") + mock_api_clients.balance_history.list_address_historical_balance = mock_list_historical_balances + + with pytest.raises(ApiError): + historical_balances = HistoricalBalance.list(network_id="test-network-id", address_id="0xaddressid", asset_id="eth") + next(historical_balances) diff --git a/tests/test_transaction.py b/tests/test_transaction.py index 2186fb2..ea8b58b 100644 --- a/tests/test_transaction.py +++ b/tests/test_transaction.py @@ -1,6 +1,10 @@ +from unittest.mock import Mock, patch + import pytest +from cdp.client.exceptions import ApiException from cdp.client.models.transaction import Transaction as TransactionModel +from cdp.errors import ApiError from cdp.transaction import Transaction @@ -142,3 +146,32 @@ def test_repr(transaction_factory): expected_repr = "Transaction: (transaction_hash: 0xtransactionhash, status: complete)" assert repr(transaction) == expected_repr + + +@patch("cdp.Cdp.api_clients") +def test_list_transactions(mock_api_clients, transaction_model_factory): + """Test the listing of transactions.""" + mock_list_transactions = Mock() + mock_list_transactions.return_value = Mock(data=[transaction_model_factory()], has_more=False) + mock_api_clients.transaction_history.list_address_transactions = mock_list_transactions + + transactions = Transaction.list(network_id="test-network-id", address_id="0xaddressid") + + assert len(list(transactions)) == 1 + assert all(isinstance(t, Transaction) for t in transactions) + mock_list_transactions.assert_called_once_with( + network_id="test-network-id", address_id="0xaddressid", limit=1, page=None + ) + + +@patch("cdp.Cdp.api_clients") +def test_list_transactions_error(mock_api_clients): + """Test the listing of transactions getting api error.""" + mock_list_transactions = Mock() + err = ApiException(500, "boom") + mock_list_transactions.side_effect = ApiError(err, code="boom", message="boom") + mock_api_clients.transaction_history.list_address_transactions = mock_list_transactions + + with pytest.raises(ApiError): + transactions = Transaction.list(network_id="test-network-id", address_id="0xaddressid") + next(transactions) From 04e9bab9123584e2534d50c067534e6ce6b68e29 Mon Sep 17 00:00:00 2001 From: xinyu-li-cb <142266583+xinyu-li-cb@users.noreply.github.com> Date: Fri, 4 Oct 2024 09:13:55 -0700 Subject: [PATCH 18/40] Release 0.0.5 (#26) --- CHANGELOG.md | 2 ++ cdp/__version__.py | 2 +- docs/conf.py | 2 +- pyproject.toml | 2 +- 4 files changed, 5 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 27a5f86..6ce6eec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## [0.0.5] - 2024-10-3 + ### Added - Support list historical balances and list transactions function for address. diff --git a/cdp/__version__.py b/cdp/__version__.py index 81f0fde..b1a19e3 100644 --- a/cdp/__version__.py +++ b/cdp/__version__.py @@ -1 +1 @@ -__version__ = "0.0.4" +__version__ = "0.0.5" diff --git a/docs/conf.py b/docs/conf.py index d81a100..c437b96 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -14,7 +14,7 @@ project = 'CDP SDK' author = 'Coinbase Developer Platform' -release = '0.0.4' +release = '0.0.5' # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration diff --git a/pyproject.toml b/pyproject.toml index b0805f8..42b1a6a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "cdp-sdk" -version = "0.0.4" +version = "0.0.5" description = "CDP Python SDK" readme = "README.md" authors = [{name = "John Peterson", email = "john.peterson@coinbase.com"}] From 34da99ff8cc31a3f3d45ab9f65411f14128ab5d1 Mon Sep 17 00:00:00 2001 From: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> Date: Tue, 8 Oct 2024 10:40:34 -0400 Subject: [PATCH 19/40] feat(PSDK-547): Optional API Debug Logging (#27) --- cdp/address.py | 4 +- cdp/cdp.py | 2 +- cdp/cdp_api_client.py | 43 ++++++++++++++++++- cdp/historical_balance.py | 16 ++++--- cdp/transaction.py | 12 +++--- tests/factories/historical_balance_factory.py | 7 +-- tests/test_address.py | 15 ++++--- tests/test_historical_balance.py | 18 ++++---- tests/test_wallet_address.py | 15 +++++-- 9 files changed, 95 insertions(+), 37 deletions(-) diff --git a/cdp/address.py b/cdp/address.py index 90dcdd0..da5a652 100644 --- a/cdp/address.py +++ b/cdp/address.py @@ -114,7 +114,9 @@ def historical_balances(self, asset_id) -> Iterator[HistoricalBalance]: Exception: If there's an error listing the historical balances. """ - return HistoricalBalance.list(network_id=self.network_id, address_id=self.address_id, asset_id=asset_id) + return HistoricalBalance.list( + network_id=self.network_id, address_id=self.address_id, asset_id=asset_id + ) def transactions(self) -> Iterator[Transaction]: """List transactions of the address. diff --git a/cdp/cdp.py b/cdp/cdp.py index 54c3159..2c2f003 100644 --- a/cdp/cdp.py +++ b/cdp/cdp.py @@ -73,7 +73,7 @@ def configure( cls.base_path = base_path cls.max_network_retries = max_network_retries - cdp_client = CdpApiClient(api_key_name, private_key, base_path) + cdp_client = CdpApiClient(api_key_name, private_key, base_path, debugging) cls.api_clients = ApiClients(cdp_client) @classmethod diff --git a/cdp/cdp_api_client.py b/cdp/cdp_api_client.py index 3cd5847..0708007 100644 --- a/cdp/cdp_api_client.py +++ b/cdp/cdp_api_client.py @@ -24,6 +24,7 @@ def __init__( api_key: str, private_key: str, host: str = "https://api.cdp.coinbase.com/platform", + debugging: bool = False, ): """Initialize the CDP API Client. @@ -31,12 +32,44 @@ def __init__( api_key (str): The API key for authentication. private_key (str): The private key for authentication. host (str, optional): The base URL for the API. Defaults to "https://api.cdp.coinbase.com/platform". + debugging (bool): Whether debugging is enabled. """ configuration = Configuration(host=host) super().__init__(configuration) - self.api_key = api_key - self.private_key = private_key + self._api_key = api_key + self._private_key = private_key + self._debugging = debugging + + @property + def api_key(self) -> str: + """The API key for authentication. + + Returns: + str: The API key. + + """ + return self._api_key + + @property + def private_key(self) -> str: + """The private key for authentication. + + Returns: + str: The private key. + + """ + return self._private_key + + @property + def debugging(self) -> str: + """Whether debugging is enabled. + + Returns: + bool: Whether debugging is enabled. + + """ + return self._debugging def call_api( self, @@ -63,6 +96,9 @@ def call_api( RESTResponse """ + if self.debugging is True: + print(f"CDP API REQUEST: {method} {url}") + if header_params is None: header_params = {} @@ -85,6 +121,9 @@ def response_deserialize( ApiResponse[ApiResponseT] """ + if self.debugging is True: + print(f"CDP API RESPONSE: Status: {response_data.status}, Data: {response_data.data}") + try: return super().response_deserialize(response_data, response_types_map) except ApiException as e: diff --git a/cdp/historical_balance.py b/cdp/historical_balance.py index f58c98f..e513e0b 100644 --- a/cdp/historical_balance.py +++ b/cdp/historical_balance.py @@ -43,7 +43,7 @@ def from_model(cls, model: HistoricalBalanceModel) -> "HistoricalBalance": amount=asset.from_atomic_amount(model.amount), asset=asset, block_height=model.block_height, - block_hash=model.block_hash + block_hash=model.block_hash, ) @classmethod @@ -64,12 +64,14 @@ def list(cls, network_id: str, address_id: str, asset_id: str) -> Iterator["Hist """ page = None while True: - response: AddressHistoricalBalanceList = Cdp.api_clients.balance_history.list_address_historical_balance( - network_id=network_id, - address_id=address_id, - asset_id=Asset.primary_denomination(asset_id), - limit=100, - page=page, + response: AddressHistoricalBalanceList = ( + Cdp.api_clients.balance_history.list_address_historical_balance( + network_id=network_id, + address_id=address_id, + asset_id=Asset.primary_denomination(asset_id), + limit=100, + page=page, + ) ) for model in response.data: diff --git a/cdp/transaction.py b/cdp/transaction.py index 46e7f2c..adab0c7 100644 --- a/cdp/transaction.py +++ b/cdp/transaction.py @@ -72,11 +72,13 @@ def list(cls, network_id: str, address_id: str) -> Iterator["Transaction"]: """ page = None while True: - response: AddressTransactionList = Cdp.api_clients.transaction_history.list_address_transactions( - network_id=network_id, - address_id=address_id, - limit=1, - page=page, + response: AddressTransactionList = ( + Cdp.api_clients.transaction_history.list_address_transactions( + network_id=network_id, + address_id=address_id, + limit=1, + page=page, + ) ) for model in response.data: diff --git a/tests/factories/historical_balance_factory.py b/tests/factories/historical_balance_factory.py index aabd4b2..708d733 100644 --- a/tests/factories/historical_balance_factory.py +++ b/tests/factories/historical_balance_factory.py @@ -14,11 +14,12 @@ def _create_historical_balance_model( asset_id="eth", decimals=18, block_hash="0xblockhash", - block_height="12345" + block_height="12345", ): asset_model = asset_model_factory(network_id, asset_id, decimals) return HistoricalBalanceModel( - amount=amount, block_hash=block_hash, block_height=block_height, asset=asset_model) + amount=amount, block_hash=block_hash, block_height=block_height, asset=asset_model + ) return _create_historical_balance_model @@ -33,7 +34,7 @@ def _create_historical_balance( asset_id="eth", decimals=18, block_hash="0xblockhash", - block_height="12345" + block_height="12345", ): asset = asset_factory(network_id=network_id, asset_id=asset_id, decimals=decimals) return HistoricalBalance(amount, asset, block_height, block_hash) diff --git a/tests/test_address.py b/tests/test_address.py index 90a3a48..c605bd8 100644 --- a/tests/test_address.py +++ b/tests/test_address.py @@ -160,13 +160,17 @@ def test_address_balances_api_error(mock_api_clients, address_factory): @patch("cdp.Cdp.api_clients") -def test_address_historical_balances(mock_api_clients, address_factory, historical_balance_model_factory): +def test_address_historical_balances( + mock_api_clients, address_factory, historical_balance_model_factory +): """Test the historical_balances method of an Address.""" address = address_factory() historical_balance_model = historical_balance_model_factory() mock_list_historical_balances = Mock() - mock_list_historical_balances.return_value = Mock(data=[historical_balance_model], has_more=False) + mock_list_historical_balances.return_value = Mock( + data=[historical_balance_model], has_more=False + ) mock_api_clients.balance_history.list_address_historical_balance = mock_list_historical_balances historical_balances = address.historical_balances("eth") @@ -178,7 +182,7 @@ def test_address_historical_balances(mock_api_clients, address_factory, historic address_id=address.address_id, asset_id="eth", limit=100, - page=None + page=None, ) @@ -212,10 +216,7 @@ def test_address_transactions(mock_api_clients, address_factory, transaction_mod assert len(list(transactions)) == 1 assert all(isinstance(t, Transaction) for t in transactions) mock_list_transactions.assert_called_once_with( - network_id=address.network_id, - address_id=address.address_id, - limit=1, - page=None + network_id=address.network_id, address_id=address.address_id, limit=1, page=None ) diff --git a/tests/test_historical_balance.py b/tests/test_historical_balance.py index a50f126..a97295d 100644 --- a/tests/test_historical_balance.py +++ b/tests/test_historical_balance.py @@ -57,19 +57,19 @@ def test_historical_balance_repr(historical_balance_factory): def test_list_historical_balances(mock_api_clients, historical_balance_model_factory): """Test the historical_balances method.""" mock_list_historical_balances = Mock() - mock_list_historical_balances.return_value = Mock(data=[historical_balance_model_factory()], has_more=False) + mock_list_historical_balances.return_value = Mock( + data=[historical_balance_model_factory()], has_more=False + ) mock_api_clients.balance_history.list_address_historical_balance = mock_list_historical_balances - historical_balances = HistoricalBalance.list(network_id="test-network-id", address_id="0xaddressid", asset_id="eth") + historical_balances = HistoricalBalance.list( + network_id="test-network-id", address_id="0xaddressid", asset_id="eth" + ) assert len(list(historical_balances)) == 1 assert all(isinstance(h, HistoricalBalance) for h in historical_balances) mock_list_historical_balances.assert_called_once_with( - network_id="test-network-id", - address_id="0xaddressid", - asset_id="eth", - limit=100, - page=None + network_id="test-network-id", address_id="0xaddressid", asset_id="eth", limit=100, page=None ) @@ -82,5 +82,7 @@ def test_list_historical_balances_error(mock_api_clients): mock_api_clients.balance_history.list_address_historical_balance = mock_list_historical_balances with pytest.raises(ApiError): - historical_balances = HistoricalBalance.list(network_id="test-network-id", address_id="0xaddressid", asset_id="eth") + historical_balances = HistoricalBalance.list( + network_id="test-network-id", address_id="0xaddressid", asset_id="eth" + ) next(historical_balances) diff --git a/tests/test_wallet_address.py b/tests/test_wallet_address.py index d081131..7e522f8 100644 --- a/tests/test_wallet_address.py +++ b/tests/test_wallet_address.py @@ -688,7 +688,9 @@ def test_repr(wallet_address_factory): @patch("cdp.wallet_address.SmartContract") @patch("cdp.Cdp.use_server_signer", False) -def test_wallet_address_deploy_token_total_supply_string(mock_smart_contract, wallet_address_factory): +def test_wallet_address_deploy_token_total_supply_string( + mock_smart_contract, wallet_address_factory +): """Test the deploy_token method of a WalletAddress with a string total_supply.""" wallet_address = wallet_address_factory(key=True) @@ -711,9 +713,12 @@ def test_wallet_address_deploy_token_total_supply_string(mock_smart_contract, wa mock_smart_contract_instance.sign.assert_called_once_with(wallet_address.key) mock_smart_contract_instance.broadcast.assert_called_once() + @patch("cdp.wallet_address.SmartContract") @patch("cdp.Cdp.use_server_signer", False) -def test_wallet_address_deploy_token_total_supply_number(mock_smart_contract, wallet_address_factory): +def test_wallet_address_deploy_token_total_supply_number( + mock_smart_contract, wallet_address_factory +): """Test the deploy_token method of a WalletAddress with a number total_supply.""" wallet_address = wallet_address_factory(key=True) @@ -736,9 +741,12 @@ def test_wallet_address_deploy_token_total_supply_number(mock_smart_contract, wa mock_smart_contract_instance.sign.assert_called_once_with(wallet_address.key) mock_smart_contract_instance.broadcast.assert_called_once() + @patch("cdp.wallet_address.SmartContract") @patch("cdp.Cdp.use_server_signer", False) -def test_wallet_address_deploy_token_total_supply_decimal(mock_smart_contract, wallet_address_factory): +def test_wallet_address_deploy_token_total_supply_decimal( + mock_smart_contract, wallet_address_factory +): """Test the deploy_token method of a WalletAddress with a Decimal total_supply.""" wallet_address = wallet_address_factory(key=True) @@ -761,6 +769,7 @@ def test_wallet_address_deploy_token_total_supply_decimal(mock_smart_contract, w mock_smart_contract_instance.sign.assert_called_once_with(wallet_address.key) mock_smart_contract_instance.broadcast.assert_called_once() + @patch("cdp.wallet_address.SmartContract") @patch("cdp.Cdp.use_server_signer", False) def test_wallet_address_deploy_nft(mock_smart_contract, wallet_address_factory): From 1192ef83d7430a67f46d12c83ea741f23ada6119 Mon Sep 17 00:00:00 2001 From: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> Date: Tue, 8 Oct 2024 15:41:28 -0400 Subject: [PATCH 20/40] chore: Set Network Retry Strategy (#28) --- .gitignore | 4 ++++ cdp/cdp.py | 4 +++- cdp/cdp_api_client.py | 35 +++++++++++++++++++++++++++-------- 3 files changed, 34 insertions(+), 9 deletions(-) diff --git a/.gitignore b/.gitignore index 76051c7..e42a270 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,10 @@ **/_build/ +**/build/ + +cdp_sdk.egg-info/ + venv/ .venv/ diff --git a/cdp/cdp.py b/cdp/cdp.py index 2c2f003..fba59ee 100644 --- a/cdp/cdp.py +++ b/cdp/cdp.py @@ -73,7 +73,9 @@ def configure( cls.base_path = base_path cls.max_network_retries = max_network_retries - cdp_client = CdpApiClient(api_key_name, private_key, base_path, debugging) + cdp_client = CdpApiClient( + api_key_name, private_key, base_path, debugging, max_network_retries + ) cls.api_clients = ApiClients(cdp_client) @classmethod diff --git a/cdp/cdp_api_client.py b/cdp/cdp_api_client.py index 0708007..783919d 100644 --- a/cdp/cdp_api_client.py +++ b/cdp/cdp_api_client.py @@ -5,6 +5,7 @@ import jwt from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import ec +from urllib3.util import Retry from cdp import __version__ from cdp.client import rest @@ -25,6 +26,7 @@ def __init__( private_key: str, host: str = "https://api.cdp.coinbase.com/platform", debugging: bool = False, + max_network_retries: int = 3, ): """Initialize the CDP API Client. @@ -33,9 +35,11 @@ def __init__( private_key (str): The private key for authentication. host (str, optional): The base URL for the API. Defaults to "https://api.cdp.coinbase.com/platform". debugging (bool): Whether debugging is enabled. + max_network_retries (int): The maximum number of network retries. Defaults to 3. """ - configuration = Configuration(host=host) + retry_strategy = self._get_retry_strategy(max_network_retries) + configuration = Configuration(host=host, retries=retry_strategy) super().__init__(configuration) self._api_key = api_key self._private_key = private_key @@ -158,7 +162,7 @@ def _build_jwt(self, url: str, method: str = "GET") -> str: method (str): The HTTP method to use. Returns: - The JWT for the given API endpoint URL. + str: The JWT for the given API endpoint URL. """ try: @@ -194,22 +198,20 @@ def _build_jwt(self, url: str, method: str = "GET") -> str: print(f"Error during JWT signing: {e!s}") raise InvalidAPIKeyFormatError("Could not sign the JWT") from e - @staticmethod - def _nonce() -> str: + def _nonce(self) -> str: """Generate a random nonce for the JWT. Returns: - The nonce. + str: The nonce. """ return "".join(random.choices("0123456789", k=16)) - @staticmethod - def _get_correlation_data() -> str: + def _get_correlation_data(self) -> str: """Return encoded correlation data including the SDK version and language. Returns: - The correlation data. + str: The correlation data. """ data = { @@ -217,3 +219,20 @@ def _get_correlation_data() -> str: "sdk_language": "python", } return ",".join(f"{key}={value}" for key, value in data.items()) + + def _get_retry_strategy(self, max_network_retries: int) -> Retry: + """Return the retry strategy for the CDP API Client. + + Args: + max_network_retries (int): The maximum number of network retries. + + Returns: + Retry: The retry strategy. + + """ + return Retry( + total=max_network_retries, # Number of total retries + status_forcelist=[500, 502, 503, 504], # Retry on HTTP status code 500 + allowed_methods=["GET"], # Retry only on GET requests + backoff_factor=1, # Exponential backoff factor + ) From dbd42d4de4f3f29cbf42dae8b5032f681b8225d1 Mon Sep 17 00:00:00 2001 From: rohan-agarwal-coinbase Date: Thu, 17 Oct 2024 13:33:05 -0400 Subject: [PATCH 21/40] Release v0.0.6 (#31) * feat(PSDK-584): Read contract support (#29) * Update to 0.0.6 and update docs and changelog (#30) --- CHANGELOG.md | 6 + cdp/__version__.py | 2 +- cdp/client/__init__.py | 2 + cdp/client/api/smart_contracts_api.py | 303 ++++ cdp/client/models/__init__.py | 2 + cdp/client/models/read_contract_request.py | 91 ++ cdp/client/models/solidity_value.py | 109 ++ cdp/client/models/update_webhook_request.py | 2 +- cdp/smart_contract.py | 84 ++ docs/cdp.client.api.rst | 8 + docs/cdp.client.models.rst | 32 + docs/cdp.rst | 32 + docs/conf.py | 2 +- pyproject.toml | 2 +- tests/factories/smart_contract_factory.py | 800 +++++++++++ tests/test_smart_contract.py | 1383 +++++++++++++++++++ 16 files changed, 2856 insertions(+), 4 deletions(-) create mode 100644 cdp/client/models/read_contract_request.py create mode 100644 cdp/client/models/solidity_value.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ce6eec..5a92322 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +## [0.0.6] - 2024-10-17 + +### Added + +- Support for read_contract to read from smart contracts + ## [0.0.5] - 2024-10-3 ### Added diff --git a/cdp/__version__.py b/cdp/__version__.py index b1a19e3..034f46c 100644 --- a/cdp/__version__.py +++ b/cdp/__version__.py @@ -1 +1 @@ -__version__ = "0.0.5" +__version__ = "0.0.6" diff --git a/cdp/client/__init__.py b/cdp/client/__init__.py index 8b003f5..018445d 100644 --- a/cdp/client/__init__.py +++ b/cdp/client/__init__.py @@ -98,6 +98,7 @@ from cdp.client.models.network_identifier import NetworkIdentifier from cdp.client.models.payload_signature import PayloadSignature from cdp.client.models.payload_signature_list import PayloadSignatureList +from cdp.client.models.read_contract_request import ReadContractRequest from cdp.client.models.seed_creation_event import SeedCreationEvent from cdp.client.models.seed_creation_event_result import SeedCreationEventResult from cdp.client.models.server_signer import ServerSigner @@ -112,6 +113,7 @@ from cdp.client.models.smart_contract_list import SmartContractList from cdp.client.models.smart_contract_options import SmartContractOptions from cdp.client.models.smart_contract_type import SmartContractType +from cdp.client.models.solidity_value import SolidityValue from cdp.client.models.sponsored_send import SponsoredSend from cdp.client.models.staking_balance import StakingBalance from cdp.client.models.staking_context import StakingContext diff --git a/cdp/client/api/smart_contracts_api.py b/cdp/client/api/smart_contracts_api.py index a507b57..db0c90f 100644 --- a/cdp/client/api/smart_contracts_api.py +++ b/cdp/client/api/smart_contracts_api.py @@ -20,8 +20,10 @@ from typing_extensions import Annotated from cdp.client.models.create_smart_contract_request import CreateSmartContractRequest from cdp.client.models.deploy_smart_contract_request import DeploySmartContractRequest +from cdp.client.models.read_contract_request import ReadContractRequest from cdp.client.models.smart_contract import SmartContract from cdp.client.models.smart_contract_list import SmartContractList +from cdp.client.models.solidity_value import SolidityValue from cdp.client.api_client import ApiClient, RequestSerialized from cdp.client.api_response import ApiResponse @@ -1217,3 +1219,304 @@ def _list_smart_contracts_serialize( ) + + + @validate_call + def read_contract( + self, + network_id: StrictStr, + contract_address: StrictStr, + read_contract_request: ReadContractRequest, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> SolidityValue: + """Read data from a smart contract + + Perform a read operation on a smart contract without creating a transaction + + :param network_id: (required) + :type network_id: str + :param contract_address: (required) + :type contract_address: str + :param read_contract_request: (required) + :type read_contract_request: ReadContractRequest + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._read_contract_serialize( + network_id=network_id, + contract_address=contract_address, + read_contract_request=read_contract_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "SolidityValue", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def read_contract_with_http_info( + self, + network_id: StrictStr, + contract_address: StrictStr, + read_contract_request: ReadContractRequest, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[SolidityValue]: + """Read data from a smart contract + + Perform a read operation on a smart contract without creating a transaction + + :param network_id: (required) + :type network_id: str + :param contract_address: (required) + :type contract_address: str + :param read_contract_request: (required) + :type read_contract_request: ReadContractRequest + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._read_contract_serialize( + network_id=network_id, + contract_address=contract_address, + read_contract_request=read_contract_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "SolidityValue", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def read_contract_without_preload_content( + self, + network_id: StrictStr, + contract_address: StrictStr, + read_contract_request: ReadContractRequest, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Read data from a smart contract + + Perform a read operation on a smart contract without creating a transaction + + :param network_id: (required) + :type network_id: str + :param contract_address: (required) + :type contract_address: str + :param read_contract_request: (required) + :type read_contract_request: ReadContractRequest + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._read_contract_serialize( + network_id=network_id, + contract_address=contract_address, + read_contract_request=read_contract_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "SolidityValue", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _read_contract_serialize( + self, + network_id, + contract_address, + read_contract_request, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if network_id is not None: + _path_params['network_id'] = network_id + if contract_address is not None: + _path_params['contract_address'] = contract_address + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if read_contract_request is not None: + _body_params = read_contract_request + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/v1/networks/{network_id}/smart_contracts/{contract_address}/read', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/cdp/client/models/__init__.py b/cdp/client/models/__init__.py index 679d3cb..a342db7 100644 --- a/cdp/client/models/__init__.py +++ b/cdp/client/models/__init__.py @@ -64,6 +64,7 @@ from cdp.client.models.network_identifier import NetworkIdentifier from cdp.client.models.payload_signature import PayloadSignature from cdp.client.models.payload_signature_list import PayloadSignatureList +from cdp.client.models.read_contract_request import ReadContractRequest from cdp.client.models.seed_creation_event import SeedCreationEvent from cdp.client.models.seed_creation_event_result import SeedCreationEventResult from cdp.client.models.server_signer import ServerSigner @@ -78,6 +79,7 @@ from cdp.client.models.smart_contract_list import SmartContractList from cdp.client.models.smart_contract_options import SmartContractOptions from cdp.client.models.smart_contract_type import SmartContractType +from cdp.client.models.solidity_value import SolidityValue from cdp.client.models.sponsored_send import SponsoredSend from cdp.client.models.staking_balance import StakingBalance from cdp.client.models.staking_context import StakingContext diff --git a/cdp/client/models/read_contract_request.py b/cdp/client/models/read_contract_request.py new file mode 100644 index 0000000..0e90ce2 --- /dev/null +++ b/cdp/client/models/read_contract_request.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class ReadContractRequest(BaseModel): + """ + ReadContractRequest + """ # noqa: E501 + method: StrictStr = Field(description="The name of the contract method to call") + args: StrictStr = Field(description="The JSON-encoded arguments to pass to the contract method. The keys should be the argument names and the values should be the argument values.") + abi: Optional[StrictStr] = Field(default=None, description="The JSON-encoded ABI of the contract method (optional, will use cached ABI if not provided)") + __properties: ClassVar[List[str]] = ["method", "args", "abi"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ReadContractRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ReadContractRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "method": obj.get("method"), + "args": obj.get("args"), + "abi": obj.get("abi") + }) + return _obj + + diff --git a/cdp/client/models/solidity_value.py b/cdp/client/models/solidity_value.py new file mode 100644 index 0000000..0efcf21 --- /dev/null +++ b/cdp/client/models/solidity_value.py @@ -0,0 +1,109 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class SolidityValue(BaseModel): + """ + SolidityValue + """ # noqa: E501 + type: StrictStr + name: Optional[StrictStr] = Field(default=None, description="The field name for tuple types. Not used for other types.") + value: Optional[StrictStr] = Field(default=None, description="The value as a string for simple types. Not used for complex types (array, tuple).") + values: Optional[List[SolidityValue]] = Field(default=None, description="For array and tuple types, the components of the value") + __properties: ClassVar[List[str]] = ["type", "name", "value", "values"] + + @field_validator('type') + def type_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['uint8', 'uint16', 'uint32', 'uint64', 'uint128', 'uint256', 'int8', 'int16', 'int32', 'int64', 'int128', 'int256', 'address', 'bool', 'string', 'bytes', 'bytes1', 'bytes2', 'bytes3', 'bytes4', 'bytes5', 'bytes6', 'bytes7', 'bytes8', 'bytes9', 'bytes10', 'bytes11', 'bytes12', 'bytes13', 'bytes14', 'bytes15', 'bytes16', 'bytes17', 'bytes18', 'bytes19', 'bytes20', 'bytes21', 'bytes22', 'bytes23', 'bytes24', 'bytes25', 'bytes26', 'bytes27', 'bytes28', 'bytes29', 'bytes30', 'bytes31', 'bytes32', 'array', 'tuple']): + raise ValueError("must be one of enum values ('uint8', 'uint16', 'uint32', 'uint64', 'uint128', 'uint256', 'int8', 'int16', 'int32', 'int64', 'int128', 'int256', 'address', 'bool', 'string', 'bytes', 'bytes1', 'bytes2', 'bytes3', 'bytes4', 'bytes5', 'bytes6', 'bytes7', 'bytes8', 'bytes9', 'bytes10', 'bytes11', 'bytes12', 'bytes13', 'bytes14', 'bytes15', 'bytes16', 'bytes17', 'bytes18', 'bytes19', 'bytes20', 'bytes21', 'bytes22', 'bytes23', 'bytes24', 'bytes25', 'bytes26', 'bytes27', 'bytes28', 'bytes29', 'bytes30', 'bytes31', 'bytes32', 'array', 'tuple')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of SolidityValue from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in values (list) + _items = [] + if self.values: + for _item_values in self.values: + if _item_values: + _items.append(_item_values.to_dict()) + _dict['values'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of SolidityValue from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "type": obj.get("type"), + "name": obj.get("name"), + "value": obj.get("value"), + "values": [SolidityValue.from_dict(_item) for _item in obj["values"]] if obj.get("values") is not None else None + }) + return _obj + +# TODO: Rewrite to not use raise_errors +SolidityValue.model_rebuild(raise_errors=False) + diff --git a/cdp/client/models/update_webhook_request.py b/cdp/client/models/update_webhook_request.py index 968bb1e..d7b6600 100644 --- a/cdp/client/models/update_webhook_request.py +++ b/cdp/client/models/update_webhook_request.py @@ -30,7 +30,7 @@ class UpdateWebhookRequest(BaseModel): """ # noqa: E501 event_type_filter: Optional[WebhookEventTypeFilter] = None event_filters: Optional[List[WebhookEventFilter]] = Field(default=None, description="Webhook will monitor all events that matches any one of the event filters.") - notification_uri: StrictStr = Field(description="The Webhook uri that updates to") + notification_uri: Optional[StrictStr] = Field(default=None, description="The Webhook uri that updates to") __properties: ClassVar[List[str]] = ["event_type_filter", "event_filters", "notification_uri"] model_config = ConfigDict( diff --git a/cdp/smart_contract.py b/cdp/smart_contract.py index 809793c..58b6e96 100644 --- a/cdp/smart_contract.py +++ b/cdp/smart_contract.py @@ -10,8 +10,10 @@ from cdp.client.models.deploy_smart_contract_request import DeploySmartContractRequest from cdp.client.models.multi_token_contract_options import MultiTokenContractOptions from cdp.client.models.nft_contract_options import NFTContractOptions +from cdp.client.models.read_contract_request import ReadContractRequest from cdp.client.models.smart_contract import SmartContract as SmartContractModel from cdp.client.models.smart_contract_options import SmartContractOptions +from cdp.client.models.solidity_value import SolidityValue from cdp.client.models.token_contract_options import TokenContractOptions from cdp.transaction import Transaction @@ -331,6 +333,88 @@ def create( return cls(model) + @classmethod + def read( + cls, + network_id: str, + contract_address: str, + method: str, + abi: list[dict] | None = None, + args: dict | None = None, + ) -> "SmartContract": + """Read data from a smart contract. + + Args: + network_id: The ID of the network. + contract_address: The address of the smart contract. + method: The method to call on the smart contract. + abi: The ABI of the smart contract. + args: The arguments to pass to the method. + + Returns: + The data read from the smart contract. + + """ + abi_json = None + + if abi: + abi_json = json.dumps(abi, separators=(",", ":")) + + read_contract_request = ReadContractRequest( + method=method, + abi=abi_json, + args=json.dumps(args or {}, separators=(",", ":")), + ) + + model = Cdp.api_clients.smart_contracts.read_contract( + network_id=network_id, + contract_address=contract_address, + read_contract_request=read_contract_request, + ) + return cls._convert_solidity_value(model) + + @classmethod + def _convert_solidity_value(cls, solidity_value: SolidityValue) -> Any: + type_ = solidity_value.type + value = getattr(solidity_value, "value", None) + values = getattr(solidity_value, "values", None) + + if type_ in [ + "uint8", + "uint16", + "uint32", + "uint64", + "uint128", + "uint256", + "int8", + "int16", + "int32", + "int64", + "int128", + "int256", + ]: + return int(value) if value is not None else None + elif type_ == "address": + return value + elif type_ == "bool": + return value == "true" if isinstance(value, str) else bool(value) + elif type_ == "string" or type_.startswith("bytes"): + return value + elif type_ == "array": + return [SmartContract._convert_solidity_value(v) for v in values] if values else [] + elif type_ == "tuple": + if values: + result = {} + for v in values: + if not hasattr(v, "name"): + raise ValueError("Error: Tuple value without a name") + result[v.name] = SmartContract._convert_solidity_value(v) + return result + else: + return {} + else: + raise ValueError(f"Unsupported Solidity type: {type_}") + def _update_transaction(self, model: SmartContractModel) -> None: """Update the transaction with the new model.""" if model.transaction is not None: diff --git a/docs/cdp.client.api.rst b/docs/cdp.client.api.rst index 7d27fa5..4a064c1 100644 --- a/docs/cdp.client.api.rst +++ b/docs/cdp.client.api.rst @@ -92,6 +92,14 @@ cdp.client.api.trades\_api module :undoc-members: :show-inheritance: +cdp.client.api.transaction\_history\_api module +----------------------------------------------- + +.. automodule:: cdp.client.api.transaction_history_api + :members: + :undoc-members: + :show-inheritance: + cdp.client.api.transfers\_api module ------------------------------------ diff --git a/docs/cdp.client.models.rst b/docs/cdp.client.models.rst index 4ff0b6f..1438528 100644 --- a/docs/cdp.client.models.rst +++ b/docs/cdp.client.models.rst @@ -212,6 +212,14 @@ cdp.client.models.create\_wallet\_request\_wallet module :undoc-members: :show-inheritance: +cdp.client.models.create\_wallet\_webhook\_request module +--------------------------------------------------------- + +.. automodule:: cdp.client.models.create_wallet_webhook_request + :members: + :undoc-members: + :show-inheritance: + cdp.client.models.create\_webhook\_request module ------------------------------------------------- @@ -348,6 +356,14 @@ cdp.client.models.historical\_balance module :undoc-members: :show-inheritance: +cdp.client.models.multi\_token\_contract\_options module +-------------------------------------------------------- + +.. automodule:: cdp.client.models.multi_token_contract_options + :members: + :undoc-members: + :show-inheritance: + cdp.client.models.network module -------------------------------- @@ -388,6 +404,14 @@ cdp.client.models.payload\_signature\_list module :undoc-members: :show-inheritance: +cdp.client.models.read\_contract\_request module +------------------------------------------------ + +.. automodule:: cdp.client.models.read_contract_request + :members: + :undoc-members: + :show-inheritance: + cdp.client.models.seed\_creation\_event module ---------------------------------------------- @@ -500,6 +524,14 @@ cdp.client.models.smart\_contract\_type module :undoc-members: :show-inheritance: +cdp.client.models.solidity\_value module +---------------------------------------- + +.. automodule:: cdp.client.models.solidity_value + :members: + :undoc-members: + :show-inheritance: + cdp.client.models.sponsored\_send module ---------------------------------------- diff --git a/docs/cdp.rst b/docs/cdp.rst index 2692f8f..ca117b5 100644 --- a/docs/cdp.rst +++ b/docs/cdp.rst @@ -92,6 +92,38 @@ cdp.faucet\_transaction module :undoc-members: :show-inheritance: +cdp.hash\_utils module +---------------------- + +.. automodule:: cdp.hash_utils + :members: + :undoc-members: + :show-inheritance: + +cdp.historical\_balance module +------------------------------ + +.. automodule:: cdp.historical_balance + :members: + :undoc-members: + :show-inheritance: + +cdp.payload\_signature module +----------------------------- + +.. automodule:: cdp.payload_signature + :members: + :undoc-members: + :show-inheritance: + +cdp.smart\_contract module +-------------------------- + +.. automodule:: cdp.smart_contract + :members: + :undoc-members: + :show-inheritance: + cdp.sponsored\_send module -------------------------- diff --git a/docs/conf.py b/docs/conf.py index c437b96..59a0c90 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -14,7 +14,7 @@ project = 'CDP SDK' author = 'Coinbase Developer Platform' -release = '0.0.5' +release = '0.0.6' # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration diff --git a/pyproject.toml b/pyproject.toml index 42b1a6a..32bcc20 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "cdp-sdk" -version = "0.0.5" +version = "0.0.6" description = "CDP Python SDK" readme = "README.md" authors = [{name = "John Peterson", email = "john.peterson@coinbase.com"}] diff --git a/tests/factories/smart_contract_factory.py b/tests/factories/smart_contract_factory.py index 4350848..99bc4da 100644 --- a/tests/factories/smart_contract_factory.py +++ b/tests/factories/smart_contract_factory.py @@ -38,3 +38,803 @@ def _create_smart_contract(status="complete"): return SmartContract(smart_contract_model) return _create_smart_contract + + +@pytest.fixture +def all_read_types_abi(): + """Return the ABI containing read functions for all types for testing.""" + return [ + { + "type": "function", + "name": "exampleFunction", + "inputs": [ + { + "name": "z", + "type": "uint256", + "internalType": "uint256", + }, + ], + "outputs": [ + { + "name": "", + "type": "bool", + "internalType": "bool", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureAddress", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "address", + "internalType": "address", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureArray", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "uint256[]", + "internalType": "uint256[]", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBool", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bool", + "internalType": "bool", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureFunctionSelector", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes4", + "internalType": "bytes4", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureInt128", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "int128", + "internalType": "int128", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureInt16", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "int16", + "internalType": "int16", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureInt256", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "int256", + "internalType": "int256", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureInt32", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "int32", + "internalType": "int32", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureInt64", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "int64", + "internalType": "int64", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureInt8", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "int8", + "internalType": "int8", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureNestedStruct", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "tuple", + "internalType": "struct TestAllReadTypes.ExampleStruct", + "components": [ + { + "name": "a", + "type": "uint256", + "internalType": "uint256", + }, + { + "name": "nestedFields", + "type": "tuple", + "internalType": "struct TestAllReadTypes.NestedData", + "components": [ + { + "name": "nestedArray", + "type": "tuple", + "internalType": "struct TestAllReadTypes.ArrayData", + "components": [ + { + "name": "a", + "type": "uint256[]", + "internalType": "uint256[]", + }, + ], + }, + { + "name": "a", + "type": "uint256", + "internalType": "uint256", + }, + ], + }, + ], + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureString", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "string", + "internalType": "string", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureTuple", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "uint256", + "internalType": "uint256", + }, + { + "name": "", + "type": "uint256", + "internalType": "uint256", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureTupleMixedTypes", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "uint256", + "internalType": "uint256", + }, + { + "name": "", + "type": "address", + "internalType": "address", + }, + { + "name": "", + "type": "bool", + "internalType": "bool", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureUint128", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "uint128", + "internalType": "uint128", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureUint16", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "uint16", + "internalType": "uint16", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureUint256", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "uint256", + "internalType": "uint256", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureUint32", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "uint32", + "internalType": "uint32", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureUint64", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "uint64", + "internalType": "uint64", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureUint8", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "uint8", + "internalType": "uint8", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "returnFunction", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "function", + "internalType": "function (uint256) external returns (bool)", + }, + ], + "stateMutability": "view", + }, + { + "type": "function", + "name": "viewUint", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "uint256", + "internalType": "uint256", + }, + ], + "stateMutability": "view", + }, + { + "type": "function", + "name": "x", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "uint256", + "internalType": "uint256", + }, + ], + "stateMutability": "view", + }, + { + "type": "function", + "name": "pureBytes", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes", + "internalType": "bytes", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes1", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes1", + "internalType": "bytes1", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes2", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes2", + "internalType": "bytes2", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes3", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes3", + "internalType": "bytes3", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes4", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes4", + "internalType": "bytes4", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes5", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes5", + "internalType": "bytes5", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes6", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes6", + "internalType": "bytes6", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes7", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes7", + "internalType": "bytes7", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes8", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes8", + "internalType": "bytes8", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes9", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes9", + "internalType": "bytes9", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes10", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes10", + "internalType": "bytes10", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes11", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes11", + "internalType": "bytes11", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes12", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes12", + "internalType": "bytes12", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes13", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes13", + "internalType": "bytes13", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes14", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes14", + "internalType": "bytes14", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes15", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes15", + "internalType": "bytes15", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes16", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes16", + "internalType": "bytes16", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes17", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes17", + "internalType": "bytes17", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes18", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes18", + "internalType": "bytes18", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes19", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes19", + "internalType": "bytes19", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes20", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes20", + "internalType": "bytes20", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes21", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes21", + "internalType": "bytes21", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes22", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes22", + "internalType": "bytes22", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes23", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes23", + "internalType": "bytes23", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes24", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes24", + "internalType": "bytes24", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes25", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes25", + "internalType": "bytes25", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes26", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes26", + "internalType": "bytes26", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes27", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes27", + "internalType": "bytes27", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes28", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes28", + "internalType": "bytes28", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes29", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes29", + "internalType": "bytes29", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes30", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes30", + "internalType": "bytes30", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes31", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes31", + "internalType": "bytes31", + }, + ], + "stateMutability": "pure", + }, + { + "type": "function", + "name": "pureBytes32", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "bytes32", + "internalType": "bytes32", + }, + ], + "stateMutability": "pure", + }, + ] diff --git a/tests/test_smart_contract.py b/tests/test_smart_contract.py index 2c2876d..591aa42 100644 --- a/tests/test_smart_contract.py +++ b/tests/test_smart_contract.py @@ -2,6 +2,7 @@ import pytest +from cdp.client.models.solidity_value import SolidityValue from cdp.smart_contract import SmartContract @@ -174,3 +175,1385 @@ def test_smart_contract_repr(smart_contract_factory): """Test the representation of a SmartContract object.""" smart_contract = smart_contract_factory() assert repr(smart_contract) == str(smart_contract) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_string(mock_api_clients, all_read_types_abi): + """Test reading a string value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="string", value="Hello, World!") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureString", + abi=all_read_types_abi, + ) + + assert result == "Hello, World!" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes1(mock_api_clients, all_read_types_abi): + """Test reading a bytes1 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="bytes1", value="0x01") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes1", + abi=all_read_types_abi, + ) + + assert result == "0x01" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes2(mock_api_clients, all_read_types_abi): + """Test reading a bytes2 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="bytes2", value="0x0102") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes2", + abi=all_read_types_abi, + ) + + assert result == "0x0102" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes3(mock_api_clients, all_read_types_abi): + """Test reading a bytes3 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="bytes3", value="0x010203") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes3", + abi=all_read_types_abi, + ) + + assert result == "0x010203" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes4(mock_api_clients, all_read_types_abi): + """Test reading a bytes4 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="bytes4", value="0x01020304") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes4", + abi=all_read_types_abi, + ) + + assert result == "0x01020304" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes5(mock_api_clients, all_read_types_abi): + """Test reading a bytes5 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="bytes5", value="0x0102030405") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes5", + abi=all_read_types_abi, + ) + + assert result == "0x0102030405" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes6(mock_api_clients, all_read_types_abi): + """Test reading a bytes6 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="bytes6", value="0x010203040506") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes6", + abi=all_read_types_abi, + ) + + assert result == "0x010203040506" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes7(mock_api_clients, all_read_types_abi): + """Test reading a bytes7 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="bytes7", value="0x01020304050607") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes7", + abi=all_read_types_abi, + ) + + assert result == "0x01020304050607" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes8(mock_api_clients, all_read_types_abi): + """Test reading a bytes8 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="bytes8", value="0x0102030405060708") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes8", + abi=all_read_types_abi, + ) + + assert result == "0x0102030405060708" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes9(mock_api_clients, all_read_types_abi): + """Test reading a bytes9 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="bytes9", value="0x010203040506070809") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes9", + abi=all_read_types_abi, + ) + + assert result == "0x010203040506070809" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes10(mock_api_clients, all_read_types_abi): + """Test reading a bytes10 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="bytes10", value="0x01020304050607080910") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes10", + abi=all_read_types_abi, + ) + + assert result == "0x01020304050607080910" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes11(mock_api_clients, all_read_types_abi): + """Test reading a bytes11 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes11", value="0x0102030405060708091011" + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes11", + abi=all_read_types_abi, + ) + + assert result == "0x0102030405060708091011" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes12(mock_api_clients, all_read_types_abi): + """Test reading a bytes12 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes12", value="0x010203040506070809101112" + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes12", + abi=all_read_types_abi, + ) + + assert result == "0x010203040506070809101112" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes13(mock_api_clients, all_read_types_abi): + """Test reading a bytes13 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes13", value="0x01020304050607080910111213" + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes13", + abi=all_read_types_abi, + ) + + assert result == "0x01020304050607080910111213" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes14(mock_api_clients, all_read_types_abi): + """Test reading a bytes14 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes14", value="0x0102030405060708091011121314" + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes14", + abi=all_read_types_abi, + ) + + assert result == "0x0102030405060708091011121314" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes15(mock_api_clients, all_read_types_abi): + """Test reading a bytes15 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes15", value="0x010203040506070809101112131415" + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes15", + abi=all_read_types_abi, + ) + + assert result == "0x010203040506070809101112131415" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes16(mock_api_clients, all_read_types_abi): + """Test reading a bytes16 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes16", value="0x0102030405060708090a0b0c0d0e0f10" + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes16", + abi=all_read_types_abi, + ) + + assert result == "0x0102030405060708090a0b0c0d0e0f10" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes17(mock_api_clients, all_read_types_abi): + """Test reading a bytes17 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes17", value="0x0102030405060708090a0b0c0d0e0f1011" + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes17", + abi=all_read_types_abi, + ) + + assert result == "0x0102030405060708090a0b0c0d0e0f1011" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes18(mock_api_clients, all_read_types_abi): + """Test reading a bytes18 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes18", value="0x0102030405060708090a0b0c0d0e0f101112" + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes18", + abi=all_read_types_abi, + ) + + assert result == "0x0102030405060708090a0b0c0d0e0f101112" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes19(mock_api_clients, all_read_types_abi): + """Test reading a bytes19 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes19", value="0x0102030405060708090a0b0c0d0e0f10111213" + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes19", + abi=all_read_types_abi, + ) + + assert result == "0x0102030405060708090a0b0c0d0e0f10111213" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes20(mock_api_clients, all_read_types_abi): + """Test reading a bytes20 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes20", value="0x0102030405060708090a0b0c0d0e0f1011121314" + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes20", + abi=all_read_types_abi, + ) + + assert result == "0x0102030405060708090a0b0c0d0e0f1011121314" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes21(mock_api_clients, all_read_types_abi): + """Test reading a bytes21 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes21", value="0x0102030405060708090a0b0c0d0e0f10111213141516" + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes21", + abi=all_read_types_abi, + ) + + assert result == "0x0102030405060708090a0b0c0d0e0f10111213141516" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes22(mock_api_clients, all_read_types_abi): + """Test reading a bytes22 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes22", value="0x0102030405060708090a0b0c0d0e0f10111213141516171819" + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes22", + abi=all_read_types_abi, + ) + + assert result == "0x0102030405060708090a0b0c0d0e0f10111213141516171819" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes23(mock_api_clients, all_read_types_abi): + """Test reading a bytes23 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes23", value="0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f2021" + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes23", + abi=all_read_types_abi, + ) + + assert result == "0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f2021" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes24(mock_api_clients, all_read_types_abi): + """Test reading a bytes24 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes24", + value="0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122", + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes24", + abi=all_read_types_abi, + ) + + assert result == "0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes25(mock_api_clients, all_read_types_abi): + """Test reading a bytes25 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes25", + value="0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20212223", + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes25", + abi=all_read_types_abi, + ) + + assert result == "0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20212223" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes26(mock_api_clients, all_read_types_abi): + """Test reading a bytes26 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes26", + value="0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425", + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes26", + abi=all_read_types_abi, + ) + + assert result == "0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes27(mock_api_clients, all_read_types_abi): + """Test reading a bytes27 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes27", + value="0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f2021222324252627", + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes27", + abi=all_read_types_abi, + ) + + assert ( + result == "0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f2021222324252627" + ) + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes28(mock_api_clients, all_read_types_abi): + """Test reading a bytes28 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes28", value="0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c" + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes28", + abi=all_read_types_abi, + ) + + assert result == "0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes29(mock_api_clients, all_read_types_abi): + """Test reading a bytes29 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes29", value="0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d" + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes29", + abi=all_read_types_abi, + ) + + assert result == "0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes30(mock_api_clients, all_read_types_abi): + """Test reading a bytes30 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes30", value="0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e" + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes30", + abi=all_read_types_abi, + ) + + assert result == "0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes31(mock_api_clients, all_read_types_abi): + """Test reading a bytes31 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes31", value="0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes31", + abi=all_read_types_abi, + ) + + assert result == "0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes32(mock_api_clients, all_read_types_abi): + """Test reading a bytes32 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes32", value="0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20" + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes32", + abi=all_read_types_abi, + ) + + assert result == "0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bytes(mock_api_clients, all_read_types_abi): + """Test reading a bytes value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes", + value="0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20212223242526272829", + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBytes", + abi=all_read_types_abi, + ) + + assert ( + result + == "0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20212223242526272829" + ) + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_uint8(mock_api_clients, all_read_types_abi): + """Test reading a uint8 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="uint8", value="123") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureUint8", + abi=all_read_types_abi, + ) + + assert result == 123 + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_uint16(mock_api_clients, all_read_types_abi): + """Test reading a uint16 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="uint16", value="12345") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureUint16", + abi=all_read_types_abi, + ) + + assert result == 12345 + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_uint32(mock_api_clients, all_read_types_abi): + """Test reading a uint32 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="uint32", value="4294967295") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureUint32", + abi=all_read_types_abi, + ) + + assert result == 4294967295 + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_uint64(mock_api_clients, all_read_types_abi): + """Test reading a uint64 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="uint64", value="18446744073709551615") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureUint64", + abi=all_read_types_abi, + ) + + assert result == 18446744073709551615 + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_uint128(mock_api_clients, all_read_types_abi): + """Test reading a uint128 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="uint128", value="340282366920938463463374607431768211455" + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureUint128", + abi=all_read_types_abi, + ) + + assert result == 340282366920938463463374607431768211455 + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_uint256(mock_api_clients, all_read_types_abi): + """Test reading a uint256 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="uint256", + value="115792089237316195423570985008687907853269984665640564039457584007913129639935", + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureUint256", + abi=all_read_types_abi, + ) + + assert result == 115792089237316195423570985008687907853269984665640564039457584007913129639935 + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_int8(mock_api_clients, all_read_types_abi): + """Test reading an int8 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="int8", value="-128") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureInt8", + abi=all_read_types_abi, + ) + + assert result == -128 + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_int16(mock_api_clients, all_read_types_abi): + """Test reading an int16 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="int16", value="-32768") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureInt16", + abi=all_read_types_abi, + ) + + assert result == -32768 + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_int32(mock_api_clients, all_read_types_abi): + """Test reading an int32 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="int32", value="-2147483648") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureInt32", + abi=all_read_types_abi, + ) + + assert result == -2147483648 + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_int64(mock_api_clients, all_read_types_abi): + """Test reading an int64 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="int64", value="-9223372036854775808") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureInt64", + abi=all_read_types_abi, + ) + + assert result == -9223372036854775808 + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_int128(mock_api_clients, all_read_types_abi): + """Test reading an int128 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="int128", value="-170141183460469231731687303715884105728" + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureInt128", + abi=all_read_types_abi, + ) + + assert result == -170141183460469231731687303715884105728 + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_int256(mock_api_clients, all_read_types_abi): + """Test reading an int256 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="int256", + value="-57896044618658097711785492504343953926634992332820282019728792003956564819968", + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureInt256", + abi=all_read_types_abi, + ) + + assert result == -57896044618658097711785492504343953926634992332820282019728792003956564819968 + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_address(mock_api_clients, all_read_types_abi): + """Test reading an address value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="address", value="0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureAddress", + abi=all_read_types_abi, + ) + + assert result == "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bool(mock_api_clients, all_read_types_abi): + """Test reading a boolean value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="bool", value="true") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBool", + abi=all_read_types_abi, + ) + + assert result is True + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_array(mock_api_clients, all_read_types_abi): + """Test reading an array value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="array", + values=[ + SolidityValue(type="uint256", value="1"), + SolidityValue(type="uint256", value="2"), + SolidityValue(type="uint256", value="3"), + SolidityValue(type="uint256", value="4"), + SolidityValue(type="uint256", value="5"), + ], + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureArray", + abi=all_read_types_abi, + ) + + assert result == [1, 2, 3, 4, 5] # Note: In Python, we use regular integers, not BigInt + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_return_function(mock_api_clients, all_read_types_abi): + """Test reading a function type as bytes from a view function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes", value="0x12341234123412341234123400000000" + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="returnFunction", + abi=all_read_types_abi, + ) + + assert result == "0x12341234123412341234123400000000" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_tuple(mock_api_clients, all_read_types_abi): + """Test reading a tuple value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="tuple", + values=[ + SolidityValue(type="uint256", value="1", name="a"), + SolidityValue(type="uint256", value="2", name="b"), + ], + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureTuple", + abi=all_read_types_abi, + ) + + assert result == {"a": 1, "b": 2} # In Python, we use regular integers, not BigInt + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_tuple_mixed_types(mock_api_clients, all_read_types_abi): + """Test reading a tuple with mixed types from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="tuple", + values=[ + SolidityValue(type="uint256", value="1", name="a"), + SolidityValue( + type="address", value="0x1234567890123456789012345678901234567890", name="b" + ), + SolidityValue(type="bool", value="true", name="c"), + ], + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureTupleMixedTypes", + abi=all_read_types_abi, + ) + + assert result == {"a": 1, "b": "0x1234567890123456789012345678901234567890", "c": True} + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_function_type_as_bytes(mock_api_clients, all_read_types_abi): + """Test reading a function type as bytes.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="bytes", value="0x12341234123412341234123400000000" + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="returnFunction", + abi=all_read_types_abi, + ) + + assert result == "0x12341234123412341234123400000000" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_nested_struct(mock_api_clients, all_read_types_abi): + """Test reading a nested struct from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="tuple", + values=[ + SolidityValue(type="uint256", value="42", name="a"), + SolidityValue( + type="tuple", + name="nestedFields", + values=[ + SolidityValue( + type="tuple", + name="nestedArray", + values=[ + SolidityValue( + type="array", + name="a", + values=[ + SolidityValue(type="uint256", value="1"), + SolidityValue(type="uint256", value="2"), + SolidityValue(type="uint256", value="3"), + ], + ), + ], + ), + SolidityValue(type="uint256", value="123", name="a"), + ], + ), + ], + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureNestedStruct", + abi=all_read_types_abi, + ) + + assert result == { + "a": 42, + "nestedFields": { + "nestedArray": { + "a": [1, 2, 3], + }, + "a": 123, + }, + } + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_string_without_abi(mock_api_clients): + """Test reading a string value from a pure function without an ABI.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="string", value="Hello, World!") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureString", + ) + + assert result == "Hello, World!" + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_bool_without_abi(mock_api_clients): + """Test reading a boolean value from a pure function without an ABI.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="bool", value="true") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureBool", + ) + + assert result is True + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + +@patch("cdp.Cdp.api_clients") +def test_read_pure_int8_without_abi(mock_api_clients): + """Test reading an int8 value from a pure function without an ABI.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="int8", value="42") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureInt8", + ) + + assert result == 42 + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) From 5ad49e00c6e6644dc9f7f0ddb505768937cb275e Mon Sep 17 00:00:00 2001 From: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> Date: Fri, 25 Oct 2024 13:51:44 -0400 Subject: [PATCH 22/40] v0.0.7 Release (#34) * sync CDP transaction struct change (#33) * sync CDP yml file change * add changelog * list works * Update webhook.py * Update webhook.py * Update webhook.py * Update webhook.py * wallet webhook * Update wallet.py * wallet test * Create test_webhook.py * lint * lint * Update cdp/webhook.py Co-authored-by: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> * Update cdp/webhook.py Co-authored-by: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> * address comments * Update README.md Co-authored-by: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> * Update README.md Co-authored-by: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> * Update README.md Co-authored-by: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> * address comments * Update cdp/webhook.py Co-authored-by: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> * Prepare 0.0.7 Release --------- Co-authored-by: xinyu-li-cb <142266583+xinyu-li-cb@users.noreply.github.com> Co-authored-by: Howard Xie Co-authored-by: cb-howardatcb <86798563+howard-at-cb@users.noreply.github.com> --- .gitignore | 1 + CHANGELOG.md | 7 + README.md | 25 ++ cdp/__init__.py | 2 + cdp/__version__.py | 2 +- cdp/api_clients.py | 18 + cdp/client/__init__.py | 4 + cdp/client/api/__init__.py | 1 + cdp/client/api/onchain_identity_api.py | 346 ++++++++++++++++++ cdp/client/models/__init__.py | 3 + cdp/client/models/ethereum_token_transfer.py | 100 +++++ cdp/client/models/ethereum_transaction.py | 12 +- cdp/client/models/onchain_name.py | 109 ++++++ cdp/client/models/onchain_name_list.py | 101 +++++ .../models/onchain_name_text_records_inner.py | 89 +++++ .../models/read_smart_contract_request.py | 91 +++++ cdp/client/models/token_transfer_type.py | 39 ++ cdp/wallet.py | 22 ++ cdp/webhook.py | 201 ++++++++++ docs/conf.py | 2 +- pyproject.toml | 2 +- tests/factories/webhook_factory.py | 27 ++ tests/test_wallet.py | 31 ++ tests/test_webhook.py | 97 +++++ 24 files changed, 1328 insertions(+), 4 deletions(-) create mode 100644 cdp/client/api/onchain_identity_api.py create mode 100644 cdp/client/models/ethereum_token_transfer.py create mode 100644 cdp/client/models/onchain_name.py create mode 100644 cdp/client/models/onchain_name_list.py create mode 100644 cdp/client/models/onchain_name_text_records_inner.py create mode 100644 cdp/client/models/read_smart_contract_request.py create mode 100644 cdp/client/models/token_transfer_type.py create mode 100644 cdp/webhook.py create mode 100644 tests/factories/webhook_factory.py create mode 100644 tests/test_webhook.py diff --git a/.gitignore b/.gitignore index e42a270..dd7c4fc 100644 --- a/.gitignore +++ b/.gitignore @@ -29,3 +29,4 @@ env/ .\#* .projectile +.idea/ \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a92322..2c99534 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## Unreleased +## [0.0.7] - 2024-10-25 + +### Added + +- Include ERC20 and ERC721 token transfer information into transaction content. +- Support for wallet and address webhooks to trigger based on onchain activities. + ## [0.0.6] - 2024-10-17 ### Added diff --git a/README.md b/README.md index 1bf05fd..9fc8dae 100644 --- a/README.md +++ b/README.md @@ -169,6 +169,31 @@ print(f"Trade successfully completed: {trade}") list(address.trades()) ``` +## Creating a Webhook +A webhook is a way to provide other applications with real-time information from the blockchain. When an event occurs on a blockchain address, it can send a POST request to a URL you specify. You can create a webhook to receive notifications about events that occur in your wallet or crypto address, such as when a user makes a transfer. +```python +from cdp.client.models.webhook import WebhookEventType +from cdp.client.models.webhook import WebhookEventFilter + +wh1 = Webhook.create( + notification_uri="https://your-app.com/callback", + event_type=WebhookEventType.ERC20_TRANSFER, + event_filters=[WebhookEventFilter(from_address="0x71d4d7d5e9ce0f41e6a68bd3a9b43aa597dc0eb0")] +) +print(wh1) +``` + +## Creating a Webhook On A Wallet +A webhook can be attached to an existing wallet to monitor events that occur on the wallet, i.e. all addresses associated with this wallet. A list of supported blockchain events can be found [here](https://docs.cdp.coinbase.com/get-started/docs/webhooks/event-types). +```python +import cdp + +wallet1 = Wallet.create() +wh1 = wallet1.create_webhook("https://your-app.com/callback") +print(wh1) +``` + ## Contributing See [CONTRIBUTING.md](CONTRIBUTING.md) for more information. + diff --git a/cdp/__init__.py b/cdp/__init__.py index 33a4168..1473e30 100644 --- a/cdp/__init__.py +++ b/cdp/__init__.py @@ -16,6 +16,7 @@ from cdp.wallet import Wallet from cdp.wallet_address import WalletAddress from cdp.wallet_data import WalletData +from cdp.webhook import Webhook __all__ = [ "__version__", @@ -24,6 +25,7 @@ "Wallet", "WalletAddress", "WalletData", + "Webhook", "Asset", "Transfer", "Address", diff --git a/cdp/__version__.py b/cdp/__version__.py index 034f46c..6526deb 100644 --- a/cdp/__version__.py +++ b/cdp/__version__.py @@ -1 +1 @@ -__version__ = "0.0.6" +__version__ = "0.0.7" diff --git a/cdp/api_clients.py b/cdp/api_clients.py index b93c943..46c7532 100644 --- a/cdp/api_clients.py +++ b/cdp/api_clients.py @@ -10,6 +10,7 @@ from cdp.client.api.transaction_history_api import TransactionHistoryApi from cdp.client.api.transfers_api import TransfersApi from cdp.client.api.wallets_api import WalletsApi +from cdp.client.api.webhooks_api import WebhooksApi class ApiClients: @@ -21,6 +22,7 @@ class ApiClients: Attributes: _cdp_client (CdpApiClient): The CDP API client used to initialize individual API clients. _wallets (Optional[WalletsApi]): The WalletsApi client instance. + _webhooks (Optional[WebhooksApi]): The WebhooksApi client instance. _addresses (Optional[AddressesApi]): The AddressesApi client instance. _external_addresses (Optional[ExternalAddressesApi]): The ExternalAddressesApi client instance. _transfers (Optional[TransfersApi]): The TransfersApi client instance. @@ -40,6 +42,7 @@ def __init__(self, cdp_client: CdpApiClient) -> None: """ self._cdp_client: CdpApiClient = cdp_client self._wallets: WalletsApi | None = None + self._webhooks: WebhooksApi | None = None self._addresses: AddressesApi | None = None self._external_addresses: ExternalAddressesApi | None = None self._transfers: TransfersApi | None = None @@ -66,6 +69,21 @@ def wallets(self) -> WalletsApi: self._wallets = WalletsApi(api_client=self._cdp_client) return self._wallets + @property + def webhooks(self) -> WebhooksApi: + """Get the WebhooksApi client instance. + + Returns: + WebhooksApi: The WebhooksApi client instance. + + Note: + This property lazily initializes the WebhooksApi client on first access. + + """ + if self._webhooks is None: + self._webhooks = WebhooksApi(api_client=self._cdp_client) + return self._webhooks + @property def addresses(self) -> AddressesApi: """Get the AddressesApi client instance. diff --git a/cdp/client/__init__.py b/cdp/client/__init__.py index 018445d..4fbe28c 100644 --- a/cdp/client/__init__.py +++ b/cdp/client/__init__.py @@ -24,6 +24,7 @@ from cdp.client.api.contract_invocations_api import ContractInvocationsApi from cdp.client.api.external_addresses_api import ExternalAddressesApi from cdp.client.api.networks_api import NetworksApi +from cdp.client.api.onchain_identity_api import OnchainIdentityApi from cdp.client.api.server_signers_api import ServerSignersApi from cdp.client.api.smart_contracts_api import SmartContractsApi from cdp.client.api.stake_api import StakeApi @@ -96,6 +97,9 @@ from cdp.client.models.nft_contract_options import NFTContractOptions from cdp.client.models.network import Network from cdp.client.models.network_identifier import NetworkIdentifier +from cdp.client.models.onchain_name import OnchainName +from cdp.client.models.onchain_name_list import OnchainNameList +from cdp.client.models.onchain_name_text_records_inner import OnchainNameTextRecordsInner from cdp.client.models.payload_signature import PayloadSignature from cdp.client.models.payload_signature_list import PayloadSignatureList from cdp.client.models.read_contract_request import ReadContractRequest diff --git a/cdp/client/api/__init__.py b/cdp/client/api/__init__.py index 28574b9..221b4a3 100644 --- a/cdp/client/api/__init__.py +++ b/cdp/client/api/__init__.py @@ -8,6 +8,7 @@ from cdp.client.api.contract_invocations_api import ContractInvocationsApi from cdp.client.api.external_addresses_api import ExternalAddressesApi from cdp.client.api.networks_api import NetworksApi +from cdp.client.api.onchain_identity_api import OnchainIdentityApi from cdp.client.api.server_signers_api import ServerSignersApi from cdp.client.api.smart_contracts_api import SmartContractsApi from cdp.client.api.stake_api import StakeApi diff --git a/cdp/client/api/onchain_identity_api.py b/cdp/client/api/onchain_identity_api.py new file mode 100644 index 0000000..06b80ac --- /dev/null +++ b/cdp/client/api/onchain_identity_api.py @@ -0,0 +1,346 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from pydantic import Field, StrictInt, StrictStr +from typing import Optional +from typing_extensions import Annotated +from cdp.client.models.onchain_name_list import OnchainNameList + +from cdp.client.api_client import ApiClient, RequestSerialized +from cdp.client.api_response import ApiResponse +from cdp.client.rest import RESTResponseType + + +class OnchainIdentityApi: + """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) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def resolve_identity_by_address( + self, + network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the identity for")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> OnchainNameList: + """Obtains onchain identity for an address on a specific network + + Obtains onchain identity for an address on a specific network + + :param network_id: The ID of the blockchain network (required) + :type network_id: str + :param address_id: The ID of the address to fetch the identity for (required) + :type address_id: str + :param limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + :type limit: int + :param page: A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + :type page: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._resolve_identity_by_address_serialize( + network_id=network_id, + address_id=address_id, + limit=limit, + page=page, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "OnchainNameList", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def resolve_identity_by_address_with_http_info( + self, + network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the identity for")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[OnchainNameList]: + """Obtains onchain identity for an address on a specific network + + Obtains onchain identity for an address on a specific network + + :param network_id: The ID of the blockchain network (required) + :type network_id: str + :param address_id: The ID of the address to fetch the identity for (required) + :type address_id: str + :param limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + :type limit: int + :param page: A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + :type page: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._resolve_identity_by_address_serialize( + network_id=network_id, + address_id=address_id, + limit=limit, + page=page, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "OnchainNameList", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def resolve_identity_by_address_without_preload_content( + self, + network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the identity for")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Obtains onchain identity for an address on a specific network + + Obtains onchain identity for an address on a specific network + + :param network_id: The ID of the blockchain network (required) + :type network_id: str + :param address_id: The ID of the address to fetch the identity for (required) + :type address_id: str + :param limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + :type limit: int + :param page: A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + :type page: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._resolve_identity_by_address_serialize( + network_id=network_id, + address_id=address_id, + limit=limit, + page=page, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "OnchainNameList", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _resolve_identity_by_address_serialize( + self, + network_id, + address_id, + limit, + page, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if network_id is not None: + _path_params['network_id'] = network_id + if address_id is not None: + _path_params['address_id'] = address_id + # process the query parameters + if limit is not None: + + _query_params.append(('limit', limit)) + + if page is not None: + + _query_params.append(('page', page)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v1/networks/{network_id}/addresses/{address_id}/identity', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/cdp/client/models/__init__.py b/cdp/client/models/__init__.py index a342db7..6cda9a0 100644 --- a/cdp/client/models/__init__.py +++ b/cdp/client/models/__init__.py @@ -62,6 +62,9 @@ from cdp.client.models.nft_contract_options import NFTContractOptions from cdp.client.models.network import Network from cdp.client.models.network_identifier import NetworkIdentifier +from cdp.client.models.onchain_name import OnchainName +from cdp.client.models.onchain_name_list import OnchainNameList +from cdp.client.models.onchain_name_text_records_inner import OnchainNameTextRecordsInner from cdp.client.models.payload_signature import PayloadSignature from cdp.client.models.payload_signature_list import PayloadSignatureList from cdp.client.models.read_contract_request import ReadContractRequest diff --git a/cdp/client/models/ethereum_token_transfer.py b/cdp/client/models/ethereum_token_transfer.py new file mode 100644 index 0000000..414451e --- /dev/null +++ b/cdp/client/models/ethereum_token_transfer.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from cdp.client.models.token_transfer_type import TokenTransferType +from typing import Optional, Set +from typing_extensions import Self + +class EthereumTokenTransfer(BaseModel): + """ + EthereumTokenTransfer + """ # noqa: E501 + contract_address: StrictStr + from_address: StrictStr + to_address: StrictStr + value: Optional[StrictStr] = Field(default=None, description="The value of the transaction in atomic units of the token being transfer for ERC20 or ERC1155 contracts.") + token_id: Optional[StrictStr] = Field(default=None, description="The ID of ERC721 or ERC1155 token being transferred.") + log_index: StrictInt + token_transfer_type: TokenTransferType + __properties: ClassVar[List[str]] = ["contract_address", "from_address", "to_address", "value", "token_id", "log_index", "token_transfer_type"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of EthereumTokenTransfer from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of EthereumTokenTransfer from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "contract_address": obj.get("contract_address"), + "from_address": obj.get("from_address"), + "to_address": obj.get("to_address"), + "value": obj.get("value"), + "token_id": obj.get("token_id"), + "log_index": obj.get("log_index"), + "token_transfer_type": obj.get("token_transfer_type") + }) + return _obj + + diff --git a/cdp/client/models/ethereum_transaction.py b/cdp/client/models/ethereum_transaction.py index c81e8f8..4ce2d4b 100644 --- a/cdp/client/models/ethereum_transaction.py +++ b/cdp/client/models/ethereum_transaction.py @@ -20,6 +20,7 @@ from datetime import datetime from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional +from cdp.client.models.ethereum_token_transfer import EthereumTokenTransfer from cdp.client.models.ethereum_transaction_access_list import EthereumTransactionAccessList from cdp.client.models.ethereum_transaction_flattened_trace import EthereumTransactionFlattenedTrace from typing import Optional, Set @@ -43,10 +44,11 @@ class EthereumTransaction(BaseModel): max_priority_fee_per_gas: Optional[StrictInt] = Field(default=None, description="The max priority fee per gas as defined in EIP-1559. https://eips.ethereum.org/EIPS/eip-1559 for more details.") priority_fee_per_gas: Optional[StrictInt] = Field(default=None, description="The confirmed priority fee per gas as defined in EIP-1559. https://eips.ethereum.org/EIPS/eip-1559 for more details.") transaction_access_list: Optional[EthereumTransactionAccessList] = None + token_transfers: Optional[List[EthereumTokenTransfer]] = None flattened_traces: Optional[List[EthereumTransactionFlattenedTrace]] = None block_timestamp: Optional[datetime] = Field(default=None, description="The timestamp of the block in which the event was emitted") mint: Optional[StrictStr] = Field(default=None, description="This is for handling optimism rollup specific EIP-2718 transaction type field.") - __properties: ClassVar[List[str]] = ["from", "gas", "gas_price", "hash", "input", "nonce", "to", "index", "value", "type", "max_fee_per_gas", "max_priority_fee_per_gas", "priority_fee_per_gas", "transaction_access_list", "flattened_traces", "block_timestamp", "mint"] + __properties: ClassVar[List[str]] = ["from", "gas", "gas_price", "hash", "input", "nonce", "to", "index", "value", "type", "max_fee_per_gas", "max_priority_fee_per_gas", "priority_fee_per_gas", "transaction_access_list", "token_transfers", "flattened_traces", "block_timestamp", "mint"] model_config = ConfigDict( populate_by_name=True, @@ -90,6 +92,13 @@ def to_dict(self) -> Dict[str, Any]: # override the default output from pydantic by calling `to_dict()` of transaction_access_list if self.transaction_access_list: _dict['transaction_access_list'] = self.transaction_access_list.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in token_transfers (list) + _items = [] + if self.token_transfers: + for _item_token_transfers in self.token_transfers: + if _item_token_transfers: + _items.append(_item_token_transfers.to_dict()) + _dict['token_transfers'] = _items # override the default output from pydantic by calling `to_dict()` of each item in flattened_traces (list) _items = [] if self.flattened_traces: @@ -123,6 +132,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: "max_priority_fee_per_gas": obj.get("max_priority_fee_per_gas"), "priority_fee_per_gas": obj.get("priority_fee_per_gas"), "transaction_access_list": EthereumTransactionAccessList.from_dict(obj["transaction_access_list"]) if obj.get("transaction_access_list") is not None else None, + "token_transfers": [EthereumTokenTransfer.from_dict(_item) for _item in obj["token_transfers"]] if obj.get("token_transfers") is not None else None, "flattened_traces": [EthereumTransactionFlattenedTrace.from_dict(_item) for _item in obj["flattened_traces"]] if obj.get("flattened_traces") is not None else None, "block_timestamp": obj.get("block_timestamp"), "mint": obj.get("mint") diff --git a/cdp/client/models/onchain_name.py b/cdp/client/models/onchain_name.py new file mode 100644 index 0000000..08b5d4d --- /dev/null +++ b/cdp/client/models/onchain_name.py @@ -0,0 +1,109 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from cdp.client.models.onchain_name_text_records_inner import OnchainNameTextRecordsInner +from typing import Optional, Set +from typing_extensions import Self + +class OnchainName(BaseModel): + """ + A representation of an onchain stored name from name systems i.e. ENS or Basenames + """ # noqa: E501 + token_id: StrictStr = Field(description="The ID for the NFT related to this name") + owner_address: StrictStr = Field(description="The onchain address of the owner of the name") + manager_address: StrictStr = Field(description="The onchain address of the manager of the name") + primary_address: Optional[StrictStr] = Field(default=None, description="The primary onchain address of the name") + domain: StrictStr = Field(description="The readable format for the name in complete form") + avatar: Optional[StrictStr] = Field(default=None, description="The visual representation attached to this name") + network_id: StrictStr = Field(description="The ID of the blockchain network") + text_records: Optional[List[OnchainNameTextRecordsInner]] = Field(default=None, description="The metadata attached to this name") + __properties: ClassVar[List[str]] = ["token_id", "owner_address", "manager_address", "primary_address", "domain", "avatar", "network_id", "text_records"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of OnchainName from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in text_records (list) + _items = [] + if self.text_records: + for _item_text_records in self.text_records: + if _item_text_records: + _items.append(_item_text_records.to_dict()) + _dict['text_records'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of OnchainName from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "token_id": obj.get("token_id"), + "owner_address": obj.get("owner_address"), + "manager_address": obj.get("manager_address"), + "primary_address": obj.get("primary_address"), + "domain": obj.get("domain"), + "avatar": obj.get("avatar"), + "network_id": obj.get("network_id"), + "text_records": [OnchainNameTextRecordsInner.from_dict(_item) for _item in obj["text_records"]] if obj.get("text_records") is not None else None + }) + return _obj + + diff --git a/cdp/client/models/onchain_name_list.py b/cdp/client/models/onchain_name_list.py new file mode 100644 index 0000000..8d1629b --- /dev/null +++ b/cdp/client/models/onchain_name_list.py @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from cdp.client.models.onchain_name import OnchainName +from typing import Optional, Set +from typing_extensions import Self + +class OnchainNameList(BaseModel): + """ + A list of onchain events with pagination information + """ # noqa: E501 + data: List[OnchainName] = Field(description="A list of onchain name objects") + has_more: Optional[StrictBool] = Field(default=None, description="True if this list has another page of items after this one that can be fetched.") + next_page: StrictStr = Field(description="The page token to be used to fetch the next page.") + total_count: Optional[StrictInt] = Field(default=None, description="The total number of payload signatures for the address.") + __properties: ClassVar[List[str]] = ["data", "has_more", "next_page", "total_count"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of OnchainNameList from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item_data in self.data: + if _item_data: + _items.append(_item_data.to_dict()) + _dict['data'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of OnchainNameList from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "data": [OnchainName.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None, + "has_more": obj.get("has_more"), + "next_page": obj.get("next_page"), + "total_count": obj.get("total_count") + }) + return _obj + + diff --git a/cdp/client/models/onchain_name_text_records_inner.py b/cdp/client/models/onchain_name_text_records_inner.py new file mode 100644 index 0000000..e7779c2 --- /dev/null +++ b/cdp/client/models/onchain_name_text_records_inner.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class OnchainNameTextRecordsInner(BaseModel): + """ + OnchainNameTextRecordsInner + """ # noqa: E501 + key: Optional[StrictStr] = Field(default=None, description="The key for the text record") + value: Optional[StrictStr] = Field(default=None, description="The value for the text record") + __properties: ClassVar[List[str]] = ["key", "value"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of OnchainNameTextRecordsInner from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of OnchainNameTextRecordsInner from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "key": obj.get("key"), + "value": obj.get("value") + }) + return _obj + + diff --git a/cdp/client/models/read_smart_contract_request.py b/cdp/client/models/read_smart_contract_request.py new file mode 100644 index 0000000..a644db3 --- /dev/null +++ b/cdp/client/models/read_smart_contract_request.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class ReadSmartContractRequest(BaseModel): + """ + ReadSmartContractRequest + """ # noqa: E501 + method: StrictStr = Field(description="The name of the contract method to call") + args: List[StrictStr] = Field(description="The arguments to pass to the contract method") + abi: Optional[StrictStr] = Field(default=None, description="The JSON-encoded ABI of the contract method (optional, will use cached ABI if not provided)") + __properties: ClassVar[List[str]] = ["method", "args", "abi"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ReadSmartContractRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ReadSmartContractRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "method": obj.get("method"), + "args": obj.get("args"), + "abi": obj.get("abi") + }) + return _obj + + diff --git a/cdp/client/models/token_transfer_type.py b/cdp/client/models/token_transfer_type.py new file mode 100644 index 0000000..3a86948 --- /dev/null +++ b/cdp/client/models/token_transfer_type.py @@ -0,0 +1,39 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class TokenTransferType(str, Enum): + """ + The type of the token transfer. + """ + + """ + allowed enum values + """ + ERC20 = 'erc20' + ERC721 = 'erc721' + ERC1155 = 'erc1155' + UNKNOWN = 'unknown' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of TokenTransferType from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/cdp/wallet.py b/cdp/wallet.py index 4f37ba1..7624ef2 100644 --- a/cdp/wallet.py +++ b/cdp/wallet.py @@ -24,6 +24,7 @@ CreateWalletRequest, CreateWalletRequestWallet, ) +from cdp.client.models.create_wallet_webhook_request import CreateWalletWebhookRequest from cdp.client.models.wallet import Wallet as WalletModel from cdp.client.models.wallet_list import WalletList from cdp.contract_invocation import ContractInvocation @@ -33,6 +34,7 @@ from cdp.trade import Trade from cdp.wallet_address import WalletAddress from cdp.wallet_data import WalletData +from cdp.webhook import Webhook class Wallet: @@ -286,6 +288,26 @@ def create_address(self) -> "WalletAddress": return wallet_address + def create_webhook(self, notification_uri: str) -> "Webhook": + """Create a new webhook for the wallet. + + Args: + notification_uri (str): The notification URI of the webhook. + + Returns: + Webhook: The created webhook object. It can be used to monitor activities happening in the wallet. When they occur, webhook will make a request to the specified URI. + + Raises: + Exception: If there's an error creating the webhook. + + """ + create_wallet_webhook_request = CreateWalletWebhookRequest(notification_uri = notification_uri) + model = Cdp.api_clients.webhooks.create_wallet_webhook( + wallet_id=self.id, create_wallet_webhook_request=create_wallet_webhook_request + ) + + return Webhook(model) + def faucet(self, asset_id: str | None = None) -> FaucetTransaction: """Request faucet funds. diff --git a/cdp/webhook.py b/cdp/webhook.py new file mode 100644 index 0000000..7640490 --- /dev/null +++ b/cdp/webhook.py @@ -0,0 +1,201 @@ +from collections.abc import Iterator + +from cdp.cdp import Cdp +from cdp.client.models.create_webhook_request import CreateWebhookRequest +from cdp.client.models.update_webhook_request import UpdateWebhookRequest +from cdp.client.models.webhook import Webhook as WebhookModel +from cdp.client.models.webhook import WebhookEventFilter, WebhookEventType, WebhookEventTypeFilter +from cdp.client.models.webhook_list import WebhookList + + +class Webhook: + """A class representing a webhook.""" + + def __init__(self, model: WebhookModel) -> None: + """Initialize the Webhook class. + + Args: + model (WebhookModel): The WebhookModel object representing the Webhook. + + """ + self._model = model + + @property + def id(self) -> str: + """Get the ID of the webhook. + + Returns: + str: The ID of the webhook. + + """ + return self._model.id + + @property + def network_id(self) -> str: + """Get the network ID of the webhook. + + Returns: + str: The network ID of the webhook. + + """ + return self._model.network_id + + @property + def notification_uri(self) -> str: + """Get the notification URI of the webhook. + + Returns: + str: The notification URI of the webhook. + + """ + return self._model.notification_uri + + @property + def event_type(self) -> WebhookEventType: + """Get the event type of the webhook. + + Returns: + str: The event type of the webhook. + + """ + return self._model.event_type + + @property + def event_type_filter(self) -> WebhookEventTypeFilter: + """Get the event type filter of the webhook. + + Returns: + str: The event type filter of the webhook. + + """ + return self._model.event_type_filter + + @property + def event_filters(self) -> list[WebhookEventFilter]: + """Get the event filters of the webhook. + + Returns: + str: The event filters of the webhook. + + """ + return self._model.event_filters + + @classmethod + def create( + cls, + notification_uri: str, + event_type: WebhookEventType, + event_type_filter: WebhookEventTypeFilter | None = None, + event_filters: list[WebhookEventFilter] | None = None, + network_id: str = "base-sepolia", + ) -> "Webhook": + """Create a new webhook. + + Args: + notification_uri (str): The URI where notifications should be sent. + event_type (WebhookEventType): The type of event that the webhook listens to. + event_type_filter (WebhookEventTypeFilter): Filter specifically for wallet activity event type. + event_filters (List[WebhookEventTypeFilter]): Filters applied to the events that determine which specific address(es) trigger. + network_id (str): The network ID of the wallet. Defaults to "base-sepolia". + + Returns: + Webhook: The created webhook object. + + """ + create_webhook_request = CreateWebhookRequest( + network_id=network_id, + event_type=event_type, + event_type_filter=event_type_filter, + event_filters=event_filters, + notification_uri=notification_uri, + ) + + model = Cdp.api_clients.webhooks.create_webhook(create_webhook_request) + webhook = cls(model) + + return webhook + + @classmethod + def list(cls) -> Iterator["Webhook"]: + """List webhooks. + + Returns: + Iterator[Webhook]: An iterator of webhook objects. + + """ + while True: + page = None + + response: WebhookList = Cdp.api_clients.webhooks.list_webhooks(limit=100, page=page) + + for webhook_model in response.data: + yield cls(webhook_model) + + if not response.has_more: + break + + page = response.next_page + + @staticmethod + def delete(webhook_id: str) -> None: + """Delete a webhook by its ID. + + Args: + webhook_id (str): The ID of the webhook to delete. + + """ + Cdp.api_clients.webhooks.delete_webhook(webhook_id) + + def update( + self, + notification_uri: str | None = None, + event_type_filter: WebhookEventTypeFilter | None = None + ) -> "Webhook": + """Update the webhook with a new notification URI, and/or a new list of addresses to monitor. + + Args: + notification_uri (str): The new URI for webhook notifications. + event_type_filter (WebhookEventTypeFilter): The new eventTypeFilter that contains a new list (replacement) of addresses to monitor for the webhook. + + Returns: + Webhook: The updated webhook object. + + """ + # Fallback to current properties if no new values are provided + final_notification_uri = notification_uri or self.notification_uri + final_event_type_filter = event_type_filter or self.event_type_filter + + update_webhook_request = UpdateWebhookRequest( + event_type_filter=final_event_type_filter, + event_filters=self.event_filters, + notification_uri=final_notification_uri, + ) + + # Update the webhook via the API client + result = Cdp.api_clients.webhooks.update_webhook( + self.id, + update_webhook_request, + ) + + # Update the internal model with the API response + self._model = result + + return self + + def __str__(self) -> str: + """Return a string representation of the Webhook object. + + Returns: + str: A string representation of the Webhook. + + """ + return f"Webhook: (id: {self.id}, network_id: {self.network_id}, notification_uri: {self.notification_uri}, event_type: {self.event_type}, event_type_filter: {self.event_type_filter}, event_filters: {self.event_filters})" + + def __repr__(self) -> str: + """Return a detailed string representation of the Webhook object. + + Returns: + str: A string that represents the Webhook object. + + """ + return str(self) diff --git a/docs/conf.py b/docs/conf.py index 59a0c90..f6d927c 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -14,7 +14,7 @@ project = 'CDP SDK' author = 'Coinbase Developer Platform' -release = '0.0.6' +release = '0.0.7' # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration diff --git a/pyproject.toml b/pyproject.toml index 32bcc20..4445cc8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "cdp-sdk" -version = "0.0.6" +version = "0.0.7" description = "CDP Python SDK" readme = "README.md" authors = [{name = "John Peterson", email = "john.peterson@coinbase.com"}] diff --git a/tests/factories/webhook_factory.py b/tests/factories/webhook_factory.py new file mode 100644 index 0000000..8c75150 --- /dev/null +++ b/tests/factories/webhook_factory.py @@ -0,0 +1,27 @@ +import pytest + +from cdp.webhook import Webhook, WebhookEventType, WebhookModel + + +@pytest.fixture +def webhook_factory(): + """Create and return a factory for Webhook fixtures.""" + def _create_webhook( + webhook_id="webhook-123", + network_id="base-sepolia", + notification_uri="https://example.com/webhook", + event_type=WebhookEventType.WALLET_ACTIVITY, + event_type_filter=None, + event_filters=None + ): + model = WebhookModel( + id=webhook_id, + network_id=network_id, + notification_uri=notification_uri, + event_type=event_type, + event_type_filter=event_type_filter, + event_filters=event_filters or [] + ) + return Webhook(model) + + return _create_webhook diff --git a/tests/test_wallet.py b/tests/test_wallet.py index 41ff3a3..c783ac3 100644 --- a/tests/test_wallet.py +++ b/tests/test_wallet.py @@ -7,6 +7,7 @@ from cdp.client.models.create_address_request import CreateAddressRequest from cdp.client.models.create_wallet_request import CreateWalletRequest, CreateWalletRequestWallet +from cdp.client.models.create_wallet_webhook_request import CreateWalletWebhookRequest from cdp.contract_invocation import ContractInvocation from cdp.payload_signature import PayloadSignature from cdp.smart_contract import SmartContract @@ -14,6 +15,7 @@ from cdp.transfer import Transfer from cdp.wallet import Wallet from cdp.wallet_address import WalletAddress +from cdp.webhook import Webhook @patch("cdp.Cdp.use_server_signer", False) @@ -614,3 +616,32 @@ def test_wallet_deploy_multi_token_with_server_signer(wallet_factory): mock_default_address.deploy_multi_token.assert_called_once_with( "https://example.com/multi-token/{id}.json" ) + +@patch("cdp.Cdp.api_clients") +def test_create_webhook(mock_api_clients, wallet_factory, webhook_factory): + """Test Wallet create_webhook method.""" + mock_api_clients.webhooks.create_wallet_webhook.return_value = webhook_factory() + + # Create a wallet instance using the factory + wallet = wallet_factory() + + # Define the notification URI to pass into the create_webhook method + notification_uri = "https://example.com/webhook" + + # Call the create_webhook method + webhook = wallet.create_webhook(notification_uri) + + # Create the expected request object + expected_request = CreateWalletWebhookRequest(notification_uri=notification_uri) + + # Assert that the API client was called with the correct parameters + mock_api_clients.webhooks.create_wallet_webhook.assert_called_once_with( + wallet_id=wallet.id, + create_wallet_webhook_request=expected_request + ) + + # Assert that the returned webhook is an instance of Webhook + assert isinstance(webhook, Webhook) + + # Additional assertions to check the returned webhook object + assert webhook.notification_uri == notification_uri diff --git a/tests/test_webhook.py b/tests/test_webhook.py new file mode 100644 index 0000000..4bf5272 --- /dev/null +++ b/tests/test_webhook.py @@ -0,0 +1,97 @@ +from unittest.mock import patch + +from cdp.client.models.create_webhook_request import CreateWebhookRequest +from cdp.client.models.update_webhook_request import UpdateWebhookRequest +from cdp.client.models.webhook import WebhookEventFilter, WebhookEventType, WebhookEventTypeFilter +from cdp.webhook import Webhook, WebhookModel + + +@patch("cdp.Cdp.api_clients") +def test_webhook_creation(mock_api_clients, webhook_factory): + """Test Webhook creation method.""" + mock_api_clients.webhooks.create_webhook.return_value = webhook_factory() + + # Define input parameters for the webhook creation + notification_uri = "https://example.com/webhook" + event_type = WebhookEventType.WALLET_ACTIVITY + event_type_filter = WebhookEventTypeFilter() + event_filters = [WebhookEventFilter()] + + expected_request = CreateWebhookRequest( + network_id="base-sepolia", + event_type=event_type, + event_type_filter=event_type_filter, + event_filters=event_filters, + notification_uri=notification_uri + ) + + webhook = Webhook.create( + notification_uri=notification_uri, + event_type=event_type, + event_type_filter=event_type_filter, + event_filters=event_filters, + network_id="base-sepolia" + ) + + mock_api_clients.webhooks.create_webhook.assert_called_once_with(expected_request) + + # Check that the returned object is a Webhook instance + assert isinstance(webhook, Webhook) + assert webhook.notification_uri == notification_uri + assert webhook.event_type == event_type + + +@patch("cdp.Cdp.api_clients") +def test_webhook_delete(mock_api_clients): + """Test Webhook delete method.""" + webhook_id = "webhook-123" + + Webhook.delete(webhook_id) + + mock_api_clients.webhooks.delete_webhook.assert_called_once_with(webhook_id) + + +@patch("cdp.Cdp.api_clients") +def test_webhook_update(mock_api_clients, webhook_factory): + """Test Webhook update method.""" + webhook_model = webhook_factory() + + # Create a Webhook instance + webhook = Webhook(model=webhook_model) + + assert webhook.notification_uri == "https://example.com/webhook" + + # Define new values for the update + new_notification_uri = "https://new.example.com/webhook" + + # Mock the API response for update + mock_api_clients.webhooks.update_webhook.return_value = WebhookModel( + id=webhook.id, + network_id=webhook.network_id, + notification_uri=new_notification_uri, + event_type=webhook.event_type, + event_type_filter=webhook.event_type_filter, + event_filters=webhook.event_filters + ) + + expected_request = UpdateWebhookRequest( + event_type_filter=webhook.event_type_filter, + event_filters=webhook.event_filters, + notification_uri=new_notification_uri + ) + + updated_webhook_model = webhook.update( + notification_uri=new_notification_uri, + ) + + updated_webhook = Webhook(model=updated_webhook_model) + + # Verify that the API client was called with the correct arguments + mock_api_clients.webhooks.update_webhook.assert_called_once_with( + webhook.id, expected_request + ) + + # Assert that the returned object is the updated webhook + assert isinstance(updated_webhook, Webhook) + assert updated_webhook.notification_uri == new_notification_uri + assert updated_webhook.id == webhook.id From 020d2453233dbc9a9d8878e3758a56efd0c206c9 Mon Sep 17 00:00:00 2001 From: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> Date: Mon, 28 Oct 2024 11:45:34 -0400 Subject: [PATCH 23/40] chore: Add Correlation ID to API Error Response (#35) * chore: Add Correlation ID to API Error Response * release 0.0.8 * changelog --- CHANGELOG.md | 6 +++++ cdp/__version__.py | 2 +- cdp/errors.py | 25 +++++++++++++++++---- cdp/wallet.py | 4 +++- cdp/webhook.py | 24 ++++++++++---------- docs/conf.py | 2 +- pyproject.toml | 2 +- tests/factories/webhook_factory.py | 5 +++-- tests/test_errors.py | 35 +++++++++++++++++++++++++----- tests/test_wallet.py | 4 ++-- tests/test_webhook.py | 24 ++++++++++---------- 11 files changed, 90 insertions(+), 43 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c99534..5570aec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +## [0.0.8] - 2024-10-28 + +### Added + +- Include correlation ID in API Errors. + ## [0.0.7] - 2024-10-25 ### Added diff --git a/cdp/__version__.py b/cdp/__version__.py index 6526deb..a73339b 100644 --- a/cdp/__version__.py +++ b/cdp/__version__.py @@ -1 +1 @@ -__version__ = "0.0.7" +__version__ = "0.0.8" diff --git a/cdp/errors.py b/cdp/errors.py index 99ba444..03670f0 100644 --- a/cdp/errors.py +++ b/cdp/errors.py @@ -12,11 +12,13 @@ def __init__( err: ApiException, code: str | None = None, message: str | None = None, + correlation_id: str | None = None, unhandled: bool = False, ) -> None: self._http_code = err.status self._api_code = code self._api_message = message + self._correlation_id = correlation_id self._handled = bool(code and message and not unhandled) super().__init__(str(err)) @@ -47,11 +49,16 @@ def from_error(cls, err: ApiException) -> "ApiError": message = body.get("message") code = body.get("code") + correlation_id = body.get("correlation_id") if code in ERROR_CODE_TO_ERROR_CLASS: - return ERROR_CODE_TO_ERROR_CLASS[code](err, code=code, message=message) + return ERROR_CODE_TO_ERROR_CLASS[code]( + err, code=code, message=message, correlation_id=correlation_id + ) else: - return cls(err, code=code, message=message, unhandled=True) + return cls( + err, code=code, message=message, correlation_id=correlation_id, unhandled=True + ) @property def http_code(self) -> int: @@ -83,6 +90,16 @@ def api_message(self) -> str | None: """ return self._api_message + @property + def correlation_id(self) -> str | None: + """Get the correlation ID. + + Returns: + str | None: The correlation ID. + + """ + return self._correlation_id + @property def handled(self) -> bool: """Get whether the error is handled. @@ -101,9 +118,9 @@ def __str__(self) -> str: """ if self.handled: - return f"ApiError(http_code={self.http_code}, api_code={self.api_code}, api_message={self.api_message})" + return f"ApiError(http_code={self.http_code}, api_code={self.api_code}, api_message={self.api_message}, correlation_id={self.correlation_id})" else: - return f"ApiError(http_code={self.http_code}, api_code={self.api_code}, api_message={self.api_message}, unhandled=True)" + return f"ApiError(http_code={self.http_code}, api_code={self.api_code}, api_message={self.api_message}, correlation_id={self.correlation_id}, unhandled={self.handled})" class InvalidConfigurationError(Exception): diff --git a/cdp/wallet.py b/cdp/wallet.py index 7624ef2..a35a22e 100644 --- a/cdp/wallet.py +++ b/cdp/wallet.py @@ -301,7 +301,9 @@ def create_webhook(self, notification_uri: str) -> "Webhook": Exception: If there's an error creating the webhook. """ - create_wallet_webhook_request = CreateWalletWebhookRequest(notification_uri = notification_uri) + create_wallet_webhook_request = CreateWalletWebhookRequest( + notification_uri=notification_uri + ) model = Cdp.api_clients.webhooks.create_wallet_webhook( wallet_id=self.id, create_wallet_webhook_request=create_wallet_webhook_request ) diff --git a/cdp/webhook.py b/cdp/webhook.py index 7640490..4f26318 100644 --- a/cdp/webhook.py +++ b/cdp/webhook.py @@ -82,12 +82,12 @@ def event_filters(self) -> list[WebhookEventFilter]: @classmethod def create( - cls, - notification_uri: str, - event_type: WebhookEventType, - event_type_filter: WebhookEventTypeFilter | None = None, - event_filters: list[WebhookEventFilter] | None = None, - network_id: str = "base-sepolia", + cls, + notification_uri: str, + event_type: WebhookEventType, + event_type_filter: WebhookEventTypeFilter | None = None, + event_filters: list[WebhookEventFilter] | None = None, + network_id: str = "base-sepolia", ) -> "Webhook": """Create a new webhook. @@ -103,11 +103,11 @@ def create( """ create_webhook_request = CreateWebhookRequest( - network_id=network_id, - event_type=event_type, - event_type_filter=event_type_filter, - event_filters=event_filters, - notification_uri=notification_uri, + network_id=network_id, + event_type=event_type, + event_type_filter=event_type_filter, + event_filters=event_filters, + notification_uri=notification_uri, ) model = Cdp.api_clients.webhooks.create_webhook(create_webhook_request) @@ -149,7 +149,7 @@ def delete(webhook_id: str) -> None: def update( self, notification_uri: str | None = None, - event_type_filter: WebhookEventTypeFilter | None = None + event_type_filter: WebhookEventTypeFilter | None = None, ) -> "Webhook": """Update the webhook with a new notification URI, and/or a new list of addresses to monitor. diff --git a/docs/conf.py b/docs/conf.py index f6d927c..28690e1 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -14,7 +14,7 @@ project = 'CDP SDK' author = 'Coinbase Developer Platform' -release = '0.0.7' +release = '0.0.8' # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration diff --git a/pyproject.toml b/pyproject.toml index 4445cc8..fc2d190 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "cdp-sdk" -version = "0.0.7" +version = "0.0.8" description = "CDP Python SDK" readme = "README.md" authors = [{name = "John Peterson", email = "john.peterson@coinbase.com"}] diff --git a/tests/factories/webhook_factory.py b/tests/factories/webhook_factory.py index 8c75150..d15d5cb 100644 --- a/tests/factories/webhook_factory.py +++ b/tests/factories/webhook_factory.py @@ -6,13 +6,14 @@ @pytest.fixture def webhook_factory(): """Create and return a factory for Webhook fixtures.""" + def _create_webhook( webhook_id="webhook-123", network_id="base-sepolia", notification_uri="https://example.com/webhook", event_type=WebhookEventType.WALLET_ACTIVITY, event_type_filter=None, - event_filters=None + event_filters=None, ): model = WebhookModel( id=webhook_id, @@ -20,7 +21,7 @@ def _create_webhook( notification_uri=notification_uri, event_type=event_type, event_type_filter=event_type_filter, - event_filters=event_filters or [] + event_filters=event_filters or [], ) return Webhook(model) diff --git a/tests/test_errors.py b/tests/test_errors.py index 8b7d2bd..4fc13de 100644 --- a/tests/test_errors.py +++ b/tests/test_errors.py @@ -19,23 +19,33 @@ def test_api_error_init(): """Test API error initialization.""" err = ApiException(400, "Bad Request") - api_error = ApiError(err, code="test_code", message="Test message") + api_error = ApiError( + err, code="test_code", message="Test message", correlation_id="test-correlation-id" + ) assert api_error.http_code == 400 assert api_error.api_code == "test_code" assert api_error.api_message == "Test message" + assert api_error.correlation_id == "test-correlation-id" assert api_error.handled is True def test_api_error_from_error_with_valid_json(): """Test API error from error with valid JSON.""" err = ApiException(400, "Bad Request") - err.body = json.dumps({"code": "invalid_wallet_id", "message": "Invalid wallet ID"}) + err.body = json.dumps( + { + "code": "invalid_wallet_id", + "message": "Invalid wallet ID", + "correlation_id": "test-correlation-id", + } + ) api_error = ApiError.from_error(err) assert isinstance(api_error, ERROR_CODE_TO_ERROR_CLASS["invalid_wallet_id"]) assert api_error.api_code == "invalid_wallet_id" assert api_error.api_message == "Invalid wallet ID" + assert api_error.correlation_id == "test-correlation-id" def test_api_error_from_error_with_invalid_json(): @@ -47,26 +57,39 @@ def test_api_error_from_error_with_invalid_json(): assert isinstance(api_error, ApiError) assert api_error.api_code is None assert api_error.api_message is None + assert api_error.correlation_id is None def test_api_error_from_error_with_unknown_code(): """Test API error from error with unknown code.""" err = ApiException(400, "Bad Request") - err.body = json.dumps({"code": "unknown_code", "message": "Unknown error"}) + err.body = json.dumps( + { + "code": "unknown_code", + "message": "Unknown error", + "correlation_id": "test-correlation-id", + } + ) api_error = ApiError.from_error(err) assert isinstance(api_error, ApiError) assert api_error.api_code == "unknown_code" assert api_error.api_message == "Unknown error" + assert api_error.correlation_id == "test-correlation-id" assert api_error.handled is False def test_api_error_str_representation(): """Test API error string representation.""" err = ApiException(400, "Bad Request") - api_error = ApiError(err, code="test_code", message="Test message") - - assert str(api_error) == "ApiError(http_code=400, api_code=test_code, api_message=Test message)" + api_error = ApiError( + err, code="test_code", message="Test message", correlation_id="test-correlation-id" + ) + + assert ( + str(api_error) + == "ApiError(http_code=400, api_code=test_code, api_message=Test message, correlation_id=test-correlation-id)" + ) def test_invalid_configuration_error(): diff --git a/tests/test_wallet.py b/tests/test_wallet.py index c783ac3..292397a 100644 --- a/tests/test_wallet.py +++ b/tests/test_wallet.py @@ -617,6 +617,7 @@ def test_wallet_deploy_multi_token_with_server_signer(wallet_factory): "https://example.com/multi-token/{id}.json" ) + @patch("cdp.Cdp.api_clients") def test_create_webhook(mock_api_clients, wallet_factory, webhook_factory): """Test Wallet create_webhook method.""" @@ -636,8 +637,7 @@ def test_create_webhook(mock_api_clients, wallet_factory, webhook_factory): # Assert that the API client was called with the correct parameters mock_api_clients.webhooks.create_wallet_webhook.assert_called_once_with( - wallet_id=wallet.id, - create_wallet_webhook_request=expected_request + wallet_id=wallet.id, create_wallet_webhook_request=expected_request ) # Assert that the returned webhook is an instance of Webhook diff --git a/tests/test_webhook.py b/tests/test_webhook.py index 4bf5272..b347767 100644 --- a/tests/test_webhook.py +++ b/tests/test_webhook.py @@ -22,7 +22,7 @@ def test_webhook_creation(mock_api_clients, webhook_factory): event_type=event_type, event_type_filter=event_type_filter, event_filters=event_filters, - notification_uri=notification_uri + notification_uri=notification_uri, ) webhook = Webhook.create( @@ -30,7 +30,7 @@ def test_webhook_creation(mock_api_clients, webhook_factory): event_type=event_type, event_type_filter=event_type_filter, event_filters=event_filters, - network_id="base-sepolia" + network_id="base-sepolia", ) mock_api_clients.webhooks.create_webhook.assert_called_once_with(expected_request) @@ -66,18 +66,18 @@ def test_webhook_update(mock_api_clients, webhook_factory): # Mock the API response for update mock_api_clients.webhooks.update_webhook.return_value = WebhookModel( - id=webhook.id, - network_id=webhook.network_id, - notification_uri=new_notification_uri, - event_type=webhook.event_type, - event_type_filter=webhook.event_type_filter, - event_filters=webhook.event_filters - ) + id=webhook.id, + network_id=webhook.network_id, + notification_uri=new_notification_uri, + event_type=webhook.event_type, + event_type_filter=webhook.event_type_filter, + event_filters=webhook.event_filters, + ) expected_request = UpdateWebhookRequest( event_type_filter=webhook.event_type_filter, event_filters=webhook.event_filters, - notification_uri=new_notification_uri + notification_uri=new_notification_uri, ) updated_webhook_model = webhook.update( @@ -87,9 +87,7 @@ def test_webhook_update(mock_api_clients, webhook_factory): updated_webhook = Webhook(model=updated_webhook_model) # Verify that the API client was called with the correct arguments - mock_api_clients.webhooks.update_webhook.assert_called_once_with( - webhook.id, expected_request - ) + mock_api_clients.webhooks.update_webhook.assert_called_once_with(webhook.id, expected_request) # Assert that the returned object is the updated webhook assert isinstance(updated_webhook, Webhook) From 0b10f03f821f15142ed6555c848f73d8abf9f14c Mon Sep 17 00:00:00 2001 From: riflecode <141154005+riflecode@users.noreply.github.com> Date: Wed, 30 Oct 2024 03:27:44 +0800 Subject: [PATCH 24/40] fix: transfer amount less than or equal to the balance. (#36) * fix: transfer amount less than or equal to the balance. * feat: perform a test to ensure the balance is sufficient for the full amount. * feat: fix code style --- cdp/wallet_address.py | 2 +- tests/test_wallet_address.py | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/cdp/wallet_address.py b/cdp/wallet_address.py index 389012f..98f0a8a 100644 --- a/cdp/wallet_address.py +++ b/cdp/wallet_address.py @@ -336,7 +336,7 @@ def _ensure_sufficient_balance(self, amount: Decimal, asset_id: str) -> None: """ current_balance = self.balance(asset_id) - if amount < current_balance: + if amount <= current_balance: return raise InsufficientFundsError(expected=amount, exact=current_balance) diff --git a/tests/test_wallet_address.py b/tests/test_wallet_address.py index 7e522f8..a04d6f2 100644 --- a/tests/test_wallet_address.py +++ b/tests/test_wallet_address.py @@ -999,3 +999,24 @@ def test_deploy_multi_token_broadcast_api_error(mock_smart_contract, wallet_addr mock_smart_contract.create.assert_called_once() mock_smart_contract_instance.sign.assert_called_once_with(wallet_address_with_key.key) mock_smart_contract_instance.broadcast.assert_called_once() + + +@patch("cdp.Cdp.api_clients") +def test_ensure_sufficient_balance_sufficient_full_amount( + mock_api_clients, wallet_address_factory, balance_model_factory +): + """Test the ensure_sufficient_balance method with sufficient full amount balance.""" + wallet_address = wallet_address_factory() + balance_model = balance_model_factory( + amount="1500000000000000000", network_id="base-sepolia", asset_id="eth", decimals=18 + ) + + mock_get_balance = Mock() + mock_get_balance.return_value = balance_model + mock_api_clients.external_addresses.get_external_address_balance = mock_get_balance + + wallet_address._ensure_sufficient_balance(Decimal("1.5"), "eth") + + mock_get_balance.assert_called_once_with( + network_id=wallet_address.network_id, address_id=wallet_address.address_id, asset_id="eth" + ) From 3e06f370fba66356059a00dd2a3470ad2b79999c Mon Sep 17 00:00:00 2001 From: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> Date: Tue, 29 Oct 2024 15:57:25 -0400 Subject: [PATCH 25/40] chore: Release 0.0.9 (#37) --- CHANGELOG.md | 6 ++++++ cdp/__version__.py | 2 +- docs/conf.py | 2 +- pyproject.toml | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5570aec..c7e0caa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +## [0.0.9] - 2024-10-29 + +### Fixed + +- Fixed bug in gasless transfer that blocked sending the full asset balance. + ## [0.0.8] - 2024-10-28 ### Added diff --git a/cdp/__version__.py b/cdp/__version__.py index a73339b..00ec2dc 100644 --- a/cdp/__version__.py +++ b/cdp/__version__.py @@ -1 +1 @@ -__version__ = "0.0.8" +__version__ = "0.0.9" diff --git a/docs/conf.py b/docs/conf.py index 28690e1..0ef199d 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -14,7 +14,7 @@ project = 'CDP SDK' author = 'Coinbase Developer Platform' -release = '0.0.8' +release = '0.0.9' # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration diff --git a/pyproject.toml b/pyproject.toml index fc2d190..0d01c46 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "cdp-sdk" -version = "0.0.8" +version = "0.0.9" description = "CDP Python SDK" readme = "README.md" authors = [{name = "John Peterson", email = "john.peterson@coinbase.com"}] From 7c1024f61f7e619039636f1a3da3ba42caa8b6f1 Mon Sep 17 00:00:00 2001 From: Alexander Stone Date: Thu, 31 Oct 2024 10:30:36 -0700 Subject: [PATCH 26/40] chore: Release V0.10.0 (#39) * feat: Support waiting for faucet transactions (#38) * chore: Bump OpenAPI client * chore: Add network_id to Transaction resource * chore: Update faucet transaction payload This updates the faucet transaction payload to reflect what our API now returns. * feat: Support fetching faucet transaction status * chore: Add status and network to faucet transaction string * chore: Fix typos * chore: Prepare v0.10.0 release --- CHANGELOG.md | 6 + README.md | 6 + cdp/__version__.py | 2 +- cdp/address.py | 5 +- cdp/client/__init__.py | 12 +- cdp/client/api/__init__.py | 1 + cdp/client/api/addresses_api.py | 9 +- cdp/client/api/external_addresses_api.py | 307 +++- cdp/client/api/fund_api.py | 1240 +++++++++++++++++ cdp/client/api/onchain_identity_api.py | 22 +- cdp/client/models/__init__.py | 11 +- .../models/create_fund_operation_request.py | 91 ++ .../models/create_fund_quote_request.py | 89 ++ cdp/client/models/crypto_amount.py | 93 ++ cdp/client/models/faucet_transaction.py | 10 +- cdp/client/models/fiat_amount.py | 89 ++ cdp/client/models/fund_operation.py | 120 ++ cdp/client/models/fund_operation_fees.py | 97 ++ cdp/client/models/fund_operation_list.py | 101 ++ cdp/client/models/fund_quote.py | 114 ++ cdp/client/models/onchain_name.py | 21 +- cdp/faucet_transaction.py | 96 +- cdp/transaction.py | 5 + docs/conf.py | 2 +- pyproject.toml | 2 +- tests/factories/faucet_transaction_factory.py | 37 + tests/factories/transaction_factory.py | 2 +- tests/test_address.py | 18 +- tests/test_faucet_transaction.py | 105 ++ tests/test_transaction.py | 1 + 30 files changed, 2678 insertions(+), 36 deletions(-) create mode 100644 cdp/client/api/fund_api.py create mode 100644 cdp/client/models/create_fund_operation_request.py create mode 100644 cdp/client/models/create_fund_quote_request.py create mode 100644 cdp/client/models/crypto_amount.py create mode 100644 cdp/client/models/fiat_amount.py create mode 100644 cdp/client/models/fund_operation.py create mode 100644 cdp/client/models/fund_operation_fees.py create mode 100644 cdp/client/models/fund_operation_list.py create mode 100644 cdp/client/models/fund_quote.py create mode 100644 tests/factories/faucet_transaction_factory.py create mode 100644 tests/test_faucet_transaction.py diff --git a/CHANGELOG.md b/CHANGELOG.md index c7e0caa..0847e2d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +## [0.10.0] - 2024-10-31 + +### Changed +- Make faucet transactions async i.e. using `faucet_tx.wait()` to wait for the transaction to be confirmed. + - This will make the SDK more consistent and make faucet transactions more reliable. + ## [0.0.9] - 2024-10-29 ### Fixed diff --git a/README.md b/README.md index 9fc8dae..f46bd48 100644 --- a/README.md +++ b/README.md @@ -100,6 +100,9 @@ testnet ETH. You are allowed one faucet claim per 24-hour window. # Fund the wallet with a faucet transaction. faucet_tx = wallet1.faucet() +# Wait for the faucet transaction to complete. +faucet_tx.wait() + print(f"Faucet transaction successfully completed: {faucet_tx}") ``` @@ -135,6 +138,9 @@ print(f"Wallet successfully created: {wallet3}") # Fund the wallet with USDC with a faucet transaction. usdc_faucet_tx = wallet1.faucet("usdc") +# Wait for the faucet transaction to complete. +usdc_faucet_tx.wait() + print(f"Faucet transaction successfully completed: {usdc_faucet_tx}") transfer = wallet1.transfer(0.00001, "usdc", wallet3, gasless=True).wait() diff --git a/cdp/__version__.py b/cdp/__version__.py index 00ec2dc..61fb31c 100644 --- a/cdp/__version__.py +++ b/cdp/__version__.py @@ -1 +1 @@ -__version__ = "0.0.9" +__version__ = "0.10.0" diff --git a/cdp/address.py b/cdp/address.py index da5a652..e8a24a9 100644 --- a/cdp/address.py +++ b/cdp/address.py @@ -65,7 +65,10 @@ def faucet(self, asset_id=None) -> FaucetTransaction: """ model = Cdp.api_clients.external_addresses.request_external_faucet_funds( - network_id=self.network_id, address_id=self.address_id, asset_id=asset_id + network_id=self.network_id, + address_id=self.address_id, + asset_id=asset_id, + skip_wait=True ) return FaucetTransaction(model) diff --git a/cdp/client/__init__.py b/cdp/client/__init__.py index 4fbe28c..317f584 100644 --- a/cdp/client/__init__.py +++ b/cdp/client/__init__.py @@ -23,6 +23,7 @@ from cdp.client.api.contract_events_api import ContractEventsApi from cdp.client.api.contract_invocations_api import ContractInvocationsApi from cdp.client.api.external_addresses_api import ExternalAddressesApi +from cdp.client.api.fund_api import FundApi from cdp.client.api.networks_api import NetworksApi from cdp.client.api.onchain_identity_api import OnchainIdentityApi from cdp.client.api.server_signers_api import ServerSignersApi @@ -67,6 +68,8 @@ from cdp.client.models.contract_invocation_list import ContractInvocationList from cdp.client.models.create_address_request import CreateAddressRequest from cdp.client.models.create_contract_invocation_request import CreateContractInvocationRequest +from cdp.client.models.create_fund_operation_request import CreateFundOperationRequest +from cdp.client.models.create_fund_quote_request import CreateFundQuoteRequest from cdp.client.models.create_payload_signature_request import CreatePayloadSignatureRequest from cdp.client.models.create_server_signer_request import CreateServerSignerRequest from cdp.client.models.create_smart_contract_request import CreateSmartContractRequest @@ -77,10 +80,12 @@ from cdp.client.models.create_wallet_request_wallet import CreateWalletRequestWallet from cdp.client.models.create_wallet_webhook_request import CreateWalletWebhookRequest from cdp.client.models.create_webhook_request import CreateWebhookRequest +from cdp.client.models.crypto_amount import CryptoAmount from cdp.client.models.deploy_smart_contract_request import DeploySmartContractRequest from cdp.client.models.erc20_transfer_event import ERC20TransferEvent from cdp.client.models.erc721_transfer_event import ERC721TransferEvent from cdp.client.models.error import Error +from cdp.client.models.ethereum_token_transfer import EthereumTokenTransfer from cdp.client.models.ethereum_transaction import EthereumTransaction from cdp.client.models.ethereum_transaction_access import EthereumTransactionAccess from cdp.client.models.ethereum_transaction_access_list import EthereumTransactionAccessList @@ -91,6 +96,11 @@ from cdp.client.models.fetch_historical_staking_balances200_response import FetchHistoricalStakingBalances200Response from cdp.client.models.fetch_staking_rewards200_response import FetchStakingRewards200Response from cdp.client.models.fetch_staking_rewards_request import FetchStakingRewardsRequest +from cdp.client.models.fiat_amount import FiatAmount +from cdp.client.models.fund_operation import FundOperation +from cdp.client.models.fund_operation_fees import FundOperationFees +from cdp.client.models.fund_operation_list import FundOperationList +from cdp.client.models.fund_quote import FundQuote from cdp.client.models.get_staking_context_request import GetStakingContextRequest from cdp.client.models.historical_balance import HistoricalBalance from cdp.client.models.multi_token_contract_options import MultiTokenContractOptions @@ -99,7 +109,6 @@ from cdp.client.models.network_identifier import NetworkIdentifier from cdp.client.models.onchain_name import OnchainName from cdp.client.models.onchain_name_list import OnchainNameList -from cdp.client.models.onchain_name_text_records_inner import OnchainNameTextRecordsInner from cdp.client.models.payload_signature import PayloadSignature from cdp.client.models.payload_signature_list import PayloadSignatureList from cdp.client.models.read_contract_request import ReadContractRequest @@ -128,6 +137,7 @@ from cdp.client.models.staking_reward_format import StakingRewardFormat from cdp.client.models.staking_reward_usd_value import StakingRewardUSDValue from cdp.client.models.token_contract_options import TokenContractOptions +from cdp.client.models.token_transfer_type import TokenTransferType from cdp.client.models.trade import Trade from cdp.client.models.trade_list import TradeList from cdp.client.models.transaction import Transaction diff --git a/cdp/client/api/__init__.py b/cdp/client/api/__init__.py index 221b4a3..ce5dea3 100644 --- a/cdp/client/api/__init__.py +++ b/cdp/client/api/__init__.py @@ -7,6 +7,7 @@ from cdp.client.api.contract_events_api import ContractEventsApi from cdp.client.api.contract_invocations_api import ContractInvocationsApi from cdp.client.api.external_addresses_api import ExternalAddressesApi +from cdp.client.api.fund_api import FundApi from cdp.client.api.networks_api import NetworksApi from cdp.client.api.onchain_identity_api import OnchainIdentityApi from cdp.client.api.server_signers_api import ServerSignersApi diff --git a/cdp/client/api/addresses_api.py b/cdp/client/api/addresses_api.py index 3c6fedd..dca4fb9 100644 --- a/cdp/client/api/addresses_api.py +++ b/cdp/client/api/addresses_api.py @@ -2391,7 +2391,7 @@ def request_faucet_funds( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> FaucetTransaction: - """Request faucet funds for onchain address. + """(Deprecated) Request faucet funds for onchain address. Request faucet funds to be sent to onchain address. @@ -2422,6 +2422,7 @@ def request_faucet_funds( :type _host_index: int, optional :return: Returns the result object. """ # noqa: E501 + warnings.warn("POST /v1/wallets/{wallet_id}/addresses/{address_id}/faucet is deprecated.", DeprecationWarning) _param = self._request_faucet_funds_serialize( wallet_id=wallet_id, @@ -2466,7 +2467,7 @@ def request_faucet_funds_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[FaucetTransaction]: - """Request faucet funds for onchain address. + """(Deprecated) Request faucet funds for onchain address. Request faucet funds to be sent to onchain address. @@ -2497,6 +2498,7 @@ def request_faucet_funds_with_http_info( :type _host_index: int, optional :return: Returns the result object. """ # noqa: E501 + warnings.warn("POST /v1/wallets/{wallet_id}/addresses/{address_id}/faucet is deprecated.", DeprecationWarning) _param = self._request_faucet_funds_serialize( wallet_id=wallet_id, @@ -2541,7 +2543,7 @@ def request_faucet_funds_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """Request faucet funds for onchain address. + """(Deprecated) Request faucet funds for onchain address. Request faucet funds to be sent to onchain address. @@ -2572,6 +2574,7 @@ def request_faucet_funds_without_preload_content( :type _host_index: int, optional :return: Returns the result object. """ # noqa: E501 + warnings.warn("POST /v1/wallets/{wallet_id}/addresses/{address_id}/faucet is deprecated.", DeprecationWarning) _param = self._request_faucet_funds_serialize( wallet_id=wallet_id, diff --git a/cdp/client/api/external_addresses_api.py b/cdp/client/api/external_addresses_api.py index 197bf46..1975530 100644 --- a/cdp/client/api/external_addresses_api.py +++ b/cdp/client/api/external_addresses_api.py @@ -16,7 +16,7 @@ from typing import Any, Dict, List, Optional, Tuple, Union from typing_extensions import Annotated -from pydantic import Field, StrictStr +from pydantic import Field, StrictBool, StrictStr from typing import Optional from typing_extensions import Annotated from cdp.client.models.address_balance_list import AddressBalanceList @@ -329,6 +329,294 @@ def _get_external_address_balance_serialize( + @validate_call + def get_faucet_transaction( + self, + network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the faucet transaction for")], + tx_hash: Annotated[StrictStr, Field(description="The hash of the faucet transaction")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> FaucetTransaction: + """Get the status of a faucet transaction + + Get the status of a faucet transaction + + :param network_id: The ID of the blockchain network (required) + :type network_id: str + :param address_id: The ID of the address to fetch the faucet transaction for (required) + :type address_id: str + :param tx_hash: The hash of the faucet transaction (required) + :type tx_hash: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_faucet_transaction_serialize( + network_id=network_id, + address_id=address_id, + tx_hash=tx_hash, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "FaucetTransaction", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_faucet_transaction_with_http_info( + self, + network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the faucet transaction for")], + tx_hash: Annotated[StrictStr, Field(description="The hash of the faucet transaction")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[FaucetTransaction]: + """Get the status of a faucet transaction + + Get the status of a faucet transaction + + :param network_id: The ID of the blockchain network (required) + :type network_id: str + :param address_id: The ID of the address to fetch the faucet transaction for (required) + :type address_id: str + :param tx_hash: The hash of the faucet transaction (required) + :type tx_hash: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_faucet_transaction_serialize( + network_id=network_id, + address_id=address_id, + tx_hash=tx_hash, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "FaucetTransaction", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_faucet_transaction_without_preload_content( + self, + network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the faucet transaction for")], + tx_hash: Annotated[StrictStr, Field(description="The hash of the faucet transaction")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get the status of a faucet transaction + + Get the status of a faucet transaction + + :param network_id: The ID of the blockchain network (required) + :type network_id: str + :param address_id: The ID of the address to fetch the faucet transaction for (required) + :type address_id: str + :param tx_hash: The hash of the faucet transaction (required) + :type tx_hash: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_faucet_transaction_serialize( + network_id=network_id, + address_id=address_id, + tx_hash=tx_hash, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "FaucetTransaction", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_faucet_transaction_serialize( + self, + network_id, + address_id, + tx_hash, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if network_id is not None: + _path_params['network_id'] = network_id + if address_id is not None: + _path_params['address_id'] = address_id + if tx_hash is not None: + _path_params['tx_hash'] = tx_hash + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v1/networks/{network_id}/addresses/{address_id}/faucet/{tx_hash}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + @validate_call def list_external_address_balances( self, @@ -625,6 +913,7 @@ def request_external_faucet_funds( network_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], address_id: Annotated[StrictStr, Field(description="The onchain address of the address that is being fetched.")], asset_id: Annotated[Optional[StrictStr], Field(description="The ID of the asset to transfer from the faucet.")] = None, + skip_wait: Annotated[Optional[StrictBool], Field(description="Whether to skip waiting for the transaction to be mined. This will become the default behavior in the future.")] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -648,6 +937,8 @@ def request_external_faucet_funds( :type address_id: str :param asset_id: The ID of the asset to transfer from the faucet. :type asset_id: str + :param skip_wait: Whether to skip waiting for the transaction to be mined. This will become the default behavior in the future. + :type skip_wait: bool :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 @@ -674,6 +965,7 @@ def request_external_faucet_funds( network_id=network_id, address_id=address_id, asset_id=asset_id, + skip_wait=skip_wait, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -700,6 +992,7 @@ def request_external_faucet_funds_with_http_info( network_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], address_id: Annotated[StrictStr, Field(description="The onchain address of the address that is being fetched.")], asset_id: Annotated[Optional[StrictStr], Field(description="The ID of the asset to transfer from the faucet.")] = None, + skip_wait: Annotated[Optional[StrictBool], Field(description="Whether to skip waiting for the transaction to be mined. This will become the default behavior in the future.")] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -723,6 +1016,8 @@ def request_external_faucet_funds_with_http_info( :type address_id: str :param asset_id: The ID of the asset to transfer from the faucet. :type asset_id: str + :param skip_wait: Whether to skip waiting for the transaction to be mined. This will become the default behavior in the future. + :type skip_wait: bool :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 @@ -749,6 +1044,7 @@ def request_external_faucet_funds_with_http_info( network_id=network_id, address_id=address_id, asset_id=asset_id, + skip_wait=skip_wait, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -775,6 +1071,7 @@ def request_external_faucet_funds_without_preload_content( network_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], address_id: Annotated[StrictStr, Field(description="The onchain address of the address that is being fetched.")], asset_id: Annotated[Optional[StrictStr], Field(description="The ID of the asset to transfer from the faucet.")] = None, + skip_wait: Annotated[Optional[StrictBool], Field(description="Whether to skip waiting for the transaction to be mined. This will become the default behavior in the future.")] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -798,6 +1095,8 @@ def request_external_faucet_funds_without_preload_content( :type address_id: str :param asset_id: The ID of the asset to transfer from the faucet. :type asset_id: str + :param skip_wait: Whether to skip waiting for the transaction to be mined. This will become the default behavior in the future. + :type skip_wait: bool :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 @@ -824,6 +1123,7 @@ def request_external_faucet_funds_without_preload_content( network_id=network_id, address_id=address_id, asset_id=asset_id, + skip_wait=skip_wait, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -845,6 +1145,7 @@ def _request_external_faucet_funds_serialize( network_id, address_id, asset_id, + skip_wait, _request_auth, _content_type, _headers, @@ -873,6 +1174,10 @@ def _request_external_faucet_funds_serialize( _query_params.append(('asset_id', asset_id)) + if skip_wait is not None: + + _query_params.append(('skip_wait', skip_wait)) + # process the header parameters # process the form parameters # process the body parameter diff --git a/cdp/client/api/fund_api.py b/cdp/client/api/fund_api.py new file mode 100644 index 0000000..1c62f38 --- /dev/null +++ b/cdp/client/api/fund_api.py @@ -0,0 +1,1240 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from pydantic import Field, StrictInt, StrictStr +from typing import Optional +from typing_extensions import Annotated +from cdp.client.models.create_fund_operation_request import CreateFundOperationRequest +from cdp.client.models.create_fund_quote_request import CreateFundQuoteRequest +from cdp.client.models.fund_operation import FundOperation +from cdp.client.models.fund_operation_list import FundOperationList +from cdp.client.models.fund_quote import FundQuote + +from cdp.client.api_client import ApiClient, RequestSerialized +from cdp.client.api_response import ApiResponse +from cdp.client.rest import RESTResponseType + + +class FundApi: + """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) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def create_fund_operation( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address to be funded.")], + create_fund_operation_request: CreateFundOperationRequest, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> FundOperation: + """Create a new fund operation. + + Create a new fund operation with an address. + + :param wallet_id: The ID of the wallet the address belongs to. (required) + :type wallet_id: str + :param address_id: The onchain address to be funded. (required) + :type address_id: str + :param create_fund_operation_request: (required) + :type create_fund_operation_request: CreateFundOperationRequest + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_fund_operation_serialize( + wallet_id=wallet_id, + address_id=address_id, + create_fund_operation_request=create_fund_operation_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "FundOperation", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def create_fund_operation_with_http_info( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address to be funded.")], + create_fund_operation_request: CreateFundOperationRequest, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[FundOperation]: + """Create a new fund operation. + + Create a new fund operation with an address. + + :param wallet_id: The ID of the wallet the address belongs to. (required) + :type wallet_id: str + :param address_id: The onchain address to be funded. (required) + :type address_id: str + :param create_fund_operation_request: (required) + :type create_fund_operation_request: CreateFundOperationRequest + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_fund_operation_serialize( + wallet_id=wallet_id, + address_id=address_id, + create_fund_operation_request=create_fund_operation_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "FundOperation", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def create_fund_operation_without_preload_content( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address to be funded.")], + create_fund_operation_request: CreateFundOperationRequest, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Create a new fund operation. + + Create a new fund operation with an address. + + :param wallet_id: The ID of the wallet the address belongs to. (required) + :type wallet_id: str + :param address_id: The onchain address to be funded. (required) + :type address_id: str + :param create_fund_operation_request: (required) + :type create_fund_operation_request: CreateFundOperationRequest + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_fund_operation_serialize( + wallet_id=wallet_id, + address_id=address_id, + create_fund_operation_request=create_fund_operation_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "FundOperation", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _create_fund_operation_serialize( + self, + wallet_id, + address_id, + create_fund_operation_request, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if wallet_id is not None: + _path_params['wallet_id'] = wallet_id + if address_id is not None: + _path_params['address_id'] = address_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if create_fund_operation_request is not None: + _body_params = create_fund_operation_request + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/fund_operations', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def create_fund_quote( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address to be funded.")], + create_fund_quote_request: CreateFundQuoteRequest, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> FundQuote: + """Create a Fund Operation quote. + + Create a new fund operation with an address. + + :param wallet_id: The ID of the wallet the address belongs to. (required) + :type wallet_id: str + :param address_id: The onchain address to be funded. (required) + :type address_id: str + :param create_fund_quote_request: (required) + :type create_fund_quote_request: CreateFundQuoteRequest + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_fund_quote_serialize( + wallet_id=wallet_id, + address_id=address_id, + create_fund_quote_request=create_fund_quote_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "FundQuote", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def create_fund_quote_with_http_info( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address to be funded.")], + create_fund_quote_request: CreateFundQuoteRequest, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[FundQuote]: + """Create a Fund Operation quote. + + Create a new fund operation with an address. + + :param wallet_id: The ID of the wallet the address belongs to. (required) + :type wallet_id: str + :param address_id: The onchain address to be funded. (required) + :type address_id: str + :param create_fund_quote_request: (required) + :type create_fund_quote_request: CreateFundQuoteRequest + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_fund_quote_serialize( + wallet_id=wallet_id, + address_id=address_id, + create_fund_quote_request=create_fund_quote_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "FundQuote", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def create_fund_quote_without_preload_content( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address to be funded.")], + create_fund_quote_request: CreateFundQuoteRequest, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Create a Fund Operation quote. + + Create a new fund operation with an address. + + :param wallet_id: The ID of the wallet the address belongs to. (required) + :type wallet_id: str + :param address_id: The onchain address to be funded. (required) + :type address_id: str + :param create_fund_quote_request: (required) + :type create_fund_quote_request: CreateFundQuoteRequest + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_fund_quote_serialize( + wallet_id=wallet_id, + address_id=address_id, + create_fund_quote_request=create_fund_quote_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "FundQuote", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _create_fund_quote_serialize( + self, + wallet_id, + address_id, + create_fund_quote_request, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if wallet_id is not None: + _path_params['wallet_id'] = wallet_id + if address_id is not None: + _path_params['address_id'] = address_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if create_fund_quote_request is not None: + _body_params = create_fund_quote_request + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/fund_operations/quote', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_fund_operation( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address that created the fund operation.")], + fund_operation_id: Annotated[StrictStr, Field(description="The ID of the fund operation to fetch.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> FundOperation: + """Get fund operation. + + Get fund operation. + + :param wallet_id: The ID of the wallet the address belongs to. (required) + :type wallet_id: str + :param address_id: The onchain address of the address that created the fund operation. (required) + :type address_id: str + :param fund_operation_id: The ID of the fund operation to fetch. (required) + :type fund_operation_id: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_fund_operation_serialize( + wallet_id=wallet_id, + address_id=address_id, + fund_operation_id=fund_operation_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "FundOperation", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_fund_operation_with_http_info( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address that created the fund operation.")], + fund_operation_id: Annotated[StrictStr, Field(description="The ID of the fund operation to fetch.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[FundOperation]: + """Get fund operation. + + Get fund operation. + + :param wallet_id: The ID of the wallet the address belongs to. (required) + :type wallet_id: str + :param address_id: The onchain address of the address that created the fund operation. (required) + :type address_id: str + :param fund_operation_id: The ID of the fund operation to fetch. (required) + :type fund_operation_id: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_fund_operation_serialize( + wallet_id=wallet_id, + address_id=address_id, + fund_operation_id=fund_operation_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "FundOperation", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_fund_operation_without_preload_content( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address that created the fund operation.")], + fund_operation_id: Annotated[StrictStr, Field(description="The ID of the fund operation to fetch.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get fund operation. + + Get fund operation. + + :param wallet_id: The ID of the wallet the address belongs to. (required) + :type wallet_id: str + :param address_id: The onchain address of the address that created the fund operation. (required) + :type address_id: str + :param fund_operation_id: The ID of the fund operation to fetch. (required) + :type fund_operation_id: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_fund_operation_serialize( + wallet_id=wallet_id, + address_id=address_id, + fund_operation_id=fund_operation_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "FundOperation", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_fund_operation_serialize( + self, + wallet_id, + address_id, + fund_operation_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if wallet_id is not None: + _path_params['wallet_id'] = wallet_id + if address_id is not None: + _path_params['address_id'] = address_id + if fund_operation_id is not None: + _path_params['fund_operation_id'] = fund_operation_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/fund_operations/{fund_operation_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def list_fund_operations( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address to list fund operations for.")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> FundOperationList: + """List fund operations for an address. + + List fund operations for an address. + + :param wallet_id: The ID of the wallet the address belongs to. (required) + :type wallet_id: str + :param address_id: The onchain address of the address to list fund operations for. (required) + :type address_id: str + :param limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + :type limit: int + :param page: A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + :type page: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_fund_operations_serialize( + wallet_id=wallet_id, + address_id=address_id, + limit=limit, + page=page, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "FundOperationList", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def list_fund_operations_with_http_info( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address to list fund operations for.")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[FundOperationList]: + """List fund operations for an address. + + List fund operations for an address. + + :param wallet_id: The ID of the wallet the address belongs to. (required) + :type wallet_id: str + :param address_id: The onchain address of the address to list fund operations for. (required) + :type address_id: str + :param limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + :type limit: int + :param page: A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + :type page: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_fund_operations_serialize( + wallet_id=wallet_id, + address_id=address_id, + limit=limit, + page=page, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "FundOperationList", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def list_fund_operations_without_preload_content( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The onchain address of the address to list fund operations for.")], + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List fund operations for an address. + + List fund operations for an address. + + :param wallet_id: The ID of the wallet the address belongs to. (required) + :type wallet_id: str + :param address_id: The onchain address of the address to list fund operations for. (required) + :type address_id: str + :param limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + :type limit: int + :param page: A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + :type page: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_fund_operations_serialize( + wallet_id=wallet_id, + address_id=address_id, + limit=limit, + page=page, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "FundOperationList", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _list_fund_operations_serialize( + self, + wallet_id, + address_id, + limit, + page, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, Union[str, bytes]] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if wallet_id is not None: + _path_params['wallet_id'] = wallet_id + if address_id is not None: + _path_params['address_id'] = address_id + # process the query parameters + if limit is not None: + + _query_params.append(('limit', limit)) + + if page is not None: + + _query_params.append(('page', page)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/fund_operations', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/cdp/client/api/onchain_identity_api.py b/cdp/client/api/onchain_identity_api.py index 06b80ac..757d351 100644 --- a/cdp/client/api/onchain_identity_api.py +++ b/cdp/client/api/onchain_identity_api.py @@ -16,8 +16,8 @@ from typing import Any, Dict, List, Optional, Tuple, Union from typing_extensions import Annotated -from pydantic import Field, StrictInt, StrictStr -from typing import Optional +from pydantic import Field, StrictInt, StrictStr, field_validator +from typing import List, Optional from typing_extensions import Annotated from cdp.client.models.onchain_name_list import OnchainNameList @@ -44,6 +44,7 @@ def resolve_identity_by_address( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the identity for")], + roles: Annotated[Optional[List[StrictStr]], Field(description="A filter by role of the names related to this address (managed or owned)")] = None, limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, _request_timeout: Union[ @@ -67,6 +68,8 @@ def resolve_identity_by_address( :type network_id: str :param address_id: The ID of the address to fetch the identity for (required) :type address_id: str + :param roles: A filter by role of the names related to this address (managed or owned) + :type roles: List[str] :param limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. :type limit: int :param page: A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. @@ -96,6 +99,7 @@ def resolve_identity_by_address( _param = self._resolve_identity_by_address_serialize( network_id=network_id, address_id=address_id, + roles=roles, limit=limit, page=page, _request_auth=_request_auth, @@ -123,6 +127,7 @@ def resolve_identity_by_address_with_http_info( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the identity for")], + roles: Annotated[Optional[List[StrictStr]], Field(description="A filter by role of the names related to this address (managed or owned)")] = None, limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, _request_timeout: Union[ @@ -146,6 +151,8 @@ def resolve_identity_by_address_with_http_info( :type network_id: str :param address_id: The ID of the address to fetch the identity for (required) :type address_id: str + :param roles: A filter by role of the names related to this address (managed or owned) + :type roles: List[str] :param limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. :type limit: int :param page: A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. @@ -175,6 +182,7 @@ def resolve_identity_by_address_with_http_info( _param = self._resolve_identity_by_address_serialize( network_id=network_id, address_id=address_id, + roles=roles, limit=limit, page=page, _request_auth=_request_auth, @@ -202,6 +210,7 @@ def resolve_identity_by_address_without_preload_content( self, network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network")], address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the identity for")], + roles: Annotated[Optional[List[StrictStr]], Field(description="A filter by role of the names related to this address (managed or owned)")] = None, limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.")] = None, page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, _request_timeout: Union[ @@ -225,6 +234,8 @@ def resolve_identity_by_address_without_preload_content( :type network_id: str :param address_id: The ID of the address to fetch the identity for (required) :type address_id: str + :param roles: A filter by role of the names related to this address (managed or owned) + :type roles: List[str] :param limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. :type limit: int :param page: A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. @@ -254,6 +265,7 @@ def resolve_identity_by_address_without_preload_content( _param = self._resolve_identity_by_address_serialize( network_id=network_id, address_id=address_id, + roles=roles, limit=limit, page=page, _request_auth=_request_auth, @@ -276,6 +288,7 @@ def _resolve_identity_by_address_serialize( self, network_id, address_id, + roles, limit, page, _request_auth, @@ -287,6 +300,7 @@ def _resolve_identity_by_address_serialize( _host = None _collection_formats: Dict[str, str] = { + 'roles': 'csv', } _path_params: Dict[str, str] = {} @@ -302,6 +316,10 @@ def _resolve_identity_by_address_serialize( if address_id is not None: _path_params['address_id'] = address_id # process the query parameters + if roles is not None: + + _query_params.append(('roles', roles)) + if limit is not None: _query_params.append(('limit', limit)) diff --git a/cdp/client/models/__init__.py b/cdp/client/models/__init__.py index 6cda9a0..188df88 100644 --- a/cdp/client/models/__init__.py +++ b/cdp/client/models/__init__.py @@ -32,6 +32,8 @@ from cdp.client.models.contract_invocation_list import ContractInvocationList from cdp.client.models.create_address_request import CreateAddressRequest from cdp.client.models.create_contract_invocation_request import CreateContractInvocationRequest +from cdp.client.models.create_fund_operation_request import CreateFundOperationRequest +from cdp.client.models.create_fund_quote_request import CreateFundQuoteRequest from cdp.client.models.create_payload_signature_request import CreatePayloadSignatureRequest from cdp.client.models.create_server_signer_request import CreateServerSignerRequest from cdp.client.models.create_smart_contract_request import CreateSmartContractRequest @@ -42,10 +44,12 @@ from cdp.client.models.create_wallet_request_wallet import CreateWalletRequestWallet from cdp.client.models.create_wallet_webhook_request import CreateWalletWebhookRequest from cdp.client.models.create_webhook_request import CreateWebhookRequest +from cdp.client.models.crypto_amount import CryptoAmount from cdp.client.models.deploy_smart_contract_request import DeploySmartContractRequest from cdp.client.models.erc20_transfer_event import ERC20TransferEvent from cdp.client.models.erc721_transfer_event import ERC721TransferEvent from cdp.client.models.error import Error +from cdp.client.models.ethereum_token_transfer import EthereumTokenTransfer from cdp.client.models.ethereum_transaction import EthereumTransaction from cdp.client.models.ethereum_transaction_access import EthereumTransactionAccess from cdp.client.models.ethereum_transaction_access_list import EthereumTransactionAccessList @@ -56,6 +60,11 @@ from cdp.client.models.fetch_historical_staking_balances200_response import FetchHistoricalStakingBalances200Response from cdp.client.models.fetch_staking_rewards200_response import FetchStakingRewards200Response from cdp.client.models.fetch_staking_rewards_request import FetchStakingRewardsRequest +from cdp.client.models.fiat_amount import FiatAmount +from cdp.client.models.fund_operation import FundOperation +from cdp.client.models.fund_operation_fees import FundOperationFees +from cdp.client.models.fund_operation_list import FundOperationList +from cdp.client.models.fund_quote import FundQuote from cdp.client.models.get_staking_context_request import GetStakingContextRequest from cdp.client.models.historical_balance import HistoricalBalance from cdp.client.models.multi_token_contract_options import MultiTokenContractOptions @@ -64,7 +73,6 @@ from cdp.client.models.network_identifier import NetworkIdentifier from cdp.client.models.onchain_name import OnchainName from cdp.client.models.onchain_name_list import OnchainNameList -from cdp.client.models.onchain_name_text_records_inner import OnchainNameTextRecordsInner from cdp.client.models.payload_signature import PayloadSignature from cdp.client.models.payload_signature_list import PayloadSignatureList from cdp.client.models.read_contract_request import ReadContractRequest @@ -93,6 +101,7 @@ from cdp.client.models.staking_reward_format import StakingRewardFormat from cdp.client.models.staking_reward_usd_value import StakingRewardUSDValue from cdp.client.models.token_contract_options import TokenContractOptions +from cdp.client.models.token_transfer_type import TokenTransferType from cdp.client.models.trade import Trade from cdp.client.models.trade_list import TradeList from cdp.client.models.transaction import Transaction diff --git a/cdp/client/models/create_fund_operation_request.py b/cdp/client/models/create_fund_operation_request.py new file mode 100644 index 0000000..adebe8c --- /dev/null +++ b/cdp/client/models/create_fund_operation_request.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class CreateFundOperationRequest(BaseModel): + """ + CreateFundOperationRequest + """ # noqa: E501 + amount: StrictStr = Field(description="The amount of the asset to fund the address with in atomic units.") + asset_id: StrictStr = Field(description="The ID of the asset to fund the address with.") + fund_quote_id: Optional[StrictStr] = Field(default=None, description="The Optional ID of the fund quote to fund the address with. If omitted we will generate a quote and immediately execute it.") + __properties: ClassVar[List[str]] = ["amount", "asset_id", "fund_quote_id"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CreateFundOperationRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CreateFundOperationRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "amount": obj.get("amount"), + "asset_id": obj.get("asset_id"), + "fund_quote_id": obj.get("fund_quote_id") + }) + return _obj + + diff --git a/cdp/client/models/create_fund_quote_request.py b/cdp/client/models/create_fund_quote_request.py new file mode 100644 index 0000000..e7f7bda --- /dev/null +++ b/cdp/client/models/create_fund_quote_request.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class CreateFundQuoteRequest(BaseModel): + """ + CreateFundQuoteRequest + """ # noqa: E501 + amount: StrictStr = Field(description="The amount of the asset to fund the address with in atomic units.") + asset_id: StrictStr = Field(description="The ID of the asset to fund the address with.") + __properties: ClassVar[List[str]] = ["amount", "asset_id"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CreateFundQuoteRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CreateFundQuoteRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "amount": obj.get("amount"), + "asset_id": obj.get("asset_id") + }) + return _obj + + diff --git a/cdp/client/models/crypto_amount.py b/cdp/client/models/crypto_amount.py new file mode 100644 index 0000000..9409e43 --- /dev/null +++ b/cdp/client/models/crypto_amount.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from cdp.client.models.asset import Asset +from typing import Optional, Set +from typing_extensions import Self + +class CryptoAmount(BaseModel): + """ + An amount in cryptocurrency + """ # noqa: E501 + amount: StrictStr = Field(description="The amount of the crypto in atomic units") + asset: Asset + __properties: ClassVar[List[str]] = ["amount", "asset"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CryptoAmount from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of asset + if self.asset: + _dict['asset'] = self.asset.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CryptoAmount from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "amount": obj.get("amount"), + "asset": Asset.from_dict(obj["asset"]) if obj.get("asset") is not None else None + }) + return _obj + + diff --git a/cdp/client/models/faucet_transaction.py b/cdp/client/models/faucet_transaction.py index cfad1a9..848ffa6 100644 --- a/cdp/client/models/faucet_transaction.py +++ b/cdp/client/models/faucet_transaction.py @@ -19,6 +19,7 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List +from cdp.client.models.transaction import Transaction from typing import Optional, Set from typing_extensions import Self @@ -28,7 +29,8 @@ class FaucetTransaction(BaseModel): """ # noqa: E501 transaction_hash: StrictStr = Field(description="The transaction hash of the transaction the faucet created.") transaction_link: StrictStr = Field(description="Link to the transaction on the blockchain explorer.") - __properties: ClassVar[List[str]] = ["transaction_hash", "transaction_link"] + transaction: Transaction + __properties: ClassVar[List[str]] = ["transaction_hash", "transaction_link", "transaction"] model_config = ConfigDict( populate_by_name=True, @@ -69,6 +71,9 @@ def to_dict(self) -> Dict[str, Any]: exclude=excluded_fields, exclude_none=True, ) + # override the default output from pydantic by calling `to_dict()` of transaction + if self.transaction: + _dict['transaction'] = self.transaction.to_dict() return _dict @classmethod @@ -82,7 +87,8 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: _obj = cls.model_validate({ "transaction_hash": obj.get("transaction_hash"), - "transaction_link": obj.get("transaction_link") + "transaction_link": obj.get("transaction_link"), + "transaction": Transaction.from_dict(obj["transaction"]) if obj.get("transaction") is not None else None }) return _obj diff --git a/cdp/client/models/fiat_amount.py b/cdp/client/models/fiat_amount.py new file mode 100644 index 0000000..3997da7 --- /dev/null +++ b/cdp/client/models/fiat_amount.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class FiatAmount(BaseModel): + """ + An amount in fiat currency + """ # noqa: E501 + amount: StrictStr = Field(description="The amount of the fiat in whole units.") + currency: StrictStr = Field(description="The currency of the fiat") + __properties: ClassVar[List[str]] = ["amount", "currency"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of FiatAmount from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of FiatAmount from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "amount": obj.get("amount"), + "currency": obj.get("currency") + }) + return _obj + + diff --git a/cdp/client/models/fund_operation.py b/cdp/client/models/fund_operation.py new file mode 100644 index 0000000..ead6042 --- /dev/null +++ b/cdp/client/models/fund_operation.py @@ -0,0 +1,120 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List +from cdp.client.models.crypto_amount import CryptoAmount +from cdp.client.models.fiat_amount import FiatAmount +from cdp.client.models.fund_operation_fees import FundOperationFees +from typing import Optional, Set +from typing_extensions import Self + +class FundOperation(BaseModel): + """ + An operation to fund a wallet with crypto + """ # noqa: E501 + fund_operation_id: StrictStr = Field(description="The ID of the fund operation") + network_id: StrictStr = Field(description="The ID of the blockchain network") + wallet_id: StrictStr = Field(description="The ID of the wallet that will receive the crypto") + address_id: StrictStr = Field(description="The ID of the address that will receive the crypto") + crypto_amount: CryptoAmount + fiat_amount: FiatAmount + fees: FundOperationFees + status: StrictStr = Field(description="The status of the fund operation") + __properties: ClassVar[List[str]] = ["fund_operation_id", "network_id", "wallet_id", "address_id", "crypto_amount", "fiat_amount", "fees", "status"] + + @field_validator('status') + def status_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['pending', 'complete', 'failed']): + raise ValueError("must be one of enum values ('pending', 'complete', 'failed')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of FundOperation from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of crypto_amount + if self.crypto_amount: + _dict['crypto_amount'] = self.crypto_amount.to_dict() + # override the default output from pydantic by calling `to_dict()` of fiat_amount + if self.fiat_amount: + _dict['fiat_amount'] = self.fiat_amount.to_dict() + # override the default output from pydantic by calling `to_dict()` of fees + if self.fees: + _dict['fees'] = self.fees.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of FundOperation from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "fund_operation_id": obj.get("fund_operation_id"), + "network_id": obj.get("network_id"), + "wallet_id": obj.get("wallet_id"), + "address_id": obj.get("address_id"), + "crypto_amount": CryptoAmount.from_dict(obj["crypto_amount"]) if obj.get("crypto_amount") is not None else None, + "fiat_amount": FiatAmount.from_dict(obj["fiat_amount"]) if obj.get("fiat_amount") is not None else None, + "fees": FundOperationFees.from_dict(obj["fees"]) if obj.get("fees") is not None else None, + "status": obj.get("status") + }) + return _obj + + diff --git a/cdp/client/models/fund_operation_fees.py b/cdp/client/models/fund_operation_fees.py new file mode 100644 index 0000000..7601e7e --- /dev/null +++ b/cdp/client/models/fund_operation_fees.py @@ -0,0 +1,97 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict +from typing import Any, ClassVar, Dict, List +from cdp.client.models.crypto_amount import CryptoAmount +from cdp.client.models.fiat_amount import FiatAmount +from typing import Optional, Set +from typing_extensions import Self + +class FundOperationFees(BaseModel): + """ + The fees for a fund operation. + """ # noqa: E501 + buy_fee: FiatAmount + transfer_fee: CryptoAmount + __properties: ClassVar[List[str]] = ["buy_fee", "transfer_fee"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of FundOperationFees from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of buy_fee + if self.buy_fee: + _dict['buy_fee'] = self.buy_fee.to_dict() + # override the default output from pydantic by calling `to_dict()` of transfer_fee + if self.transfer_fee: + _dict['transfer_fee'] = self.transfer_fee.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of FundOperationFees from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "buy_fee": FiatAmount.from_dict(obj["buy_fee"]) if obj.get("buy_fee") is not None else None, + "transfer_fee": CryptoAmount.from_dict(obj["transfer_fee"]) if obj.get("transfer_fee") is not None else None + }) + return _obj + + diff --git a/cdp/client/models/fund_operation_list.py b/cdp/client/models/fund_operation_list.py new file mode 100644 index 0000000..3284f65 --- /dev/null +++ b/cdp/client/models/fund_operation_list.py @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List +from cdp.client.models.fund_operation import FundOperation +from typing import Optional, Set +from typing_extensions import Self + +class FundOperationList(BaseModel): + """ + Paginated list of fund operations + """ # noqa: E501 + data: List[FundOperation] + has_more: StrictBool = Field(description="True if this list has another page of items after this one that can be fetched.") + next_page: StrictStr = Field(description="The page token to be used to fetch the next page.") + total_count: StrictInt = Field(description="The total number of fund operations") + __properties: ClassVar[List[str]] = ["data", "has_more", "next_page", "total_count"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of FundOperationList from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item_data in self.data: + if _item_data: + _items.append(_item_data.to_dict()) + _dict['data'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of FundOperationList from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "data": [FundOperation.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None, + "has_more": obj.get("has_more"), + "next_page": obj.get("next_page"), + "total_count": obj.get("total_count") + }) + return _obj + + diff --git a/cdp/client/models/fund_quote.py b/cdp/client/models/fund_quote.py new file mode 100644 index 0000000..2a768d6 --- /dev/null +++ b/cdp/client/models/fund_quote.py @@ -0,0 +1,114 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from cdp.client.models.crypto_amount import CryptoAmount +from cdp.client.models.fiat_amount import FiatAmount +from cdp.client.models.fund_operation_fees import FundOperationFees +from typing import Optional, Set +from typing_extensions import Self + +class FundQuote(BaseModel): + """ + A quote for a fund operation + """ # noqa: E501 + fund_quote_id: StrictStr = Field(description="The ID of the fund quote") + network_id: StrictStr = Field(description="The ID of the blockchain network") + wallet_id: StrictStr = Field(description="The ID of the wallet that will receive the crypto") + address_id: StrictStr = Field(description="The ID of the address that will receive the crypto") + crypto_amount: CryptoAmount + fiat_amount: FiatAmount + expires_at: datetime = Field(description="The time at which the quote expires") + fees: FundOperationFees + __properties: ClassVar[List[str]] = ["fund_quote_id", "network_id", "wallet_id", "address_id", "crypto_amount", "fiat_amount", "expires_at", "fees"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of FundQuote from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of crypto_amount + if self.crypto_amount: + _dict['crypto_amount'] = self.crypto_amount.to_dict() + # override the default output from pydantic by calling `to_dict()` of fiat_amount + if self.fiat_amount: + _dict['fiat_amount'] = self.fiat_amount.to_dict() + # override the default output from pydantic by calling `to_dict()` of fees + if self.fees: + _dict['fees'] = self.fees.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of FundQuote from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "fund_quote_id": obj.get("fund_quote_id"), + "network_id": obj.get("network_id"), + "wallet_id": obj.get("wallet_id"), + "address_id": obj.get("address_id"), + "crypto_amount": CryptoAmount.from_dict(obj["crypto_amount"]) if obj.get("crypto_amount") is not None else None, + "fiat_amount": FiatAmount.from_dict(obj["fiat_amount"]) if obj.get("fiat_amount") is not None else None, + "expires_at": obj.get("expires_at"), + "fees": FundOperationFees.from_dict(obj["fees"]) if obj.get("fees") is not None else None + }) + return _obj + + diff --git a/cdp/client/models/onchain_name.py b/cdp/client/models/onchain_name.py index 08b5d4d..c03897a 100644 --- a/cdp/client/models/onchain_name.py +++ b/cdp/client/models/onchain_name.py @@ -17,9 +17,9 @@ import re # noqa: F401 import json -from pydantic import BaseModel, ConfigDict, Field, StrictStr +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr from typing import Any, ClassVar, Dict, List, Optional -from cdp.client.models.onchain_name_text_records_inner import OnchainNameTextRecordsInner from typing import Optional, Set from typing_extensions import Self @@ -34,8 +34,10 @@ class OnchainName(BaseModel): domain: StrictStr = Field(description="The readable format for the name in complete form") avatar: Optional[StrictStr] = Field(default=None, description="The visual representation attached to this name") network_id: StrictStr = Field(description="The ID of the blockchain network") - text_records: Optional[List[OnchainNameTextRecordsInner]] = Field(default=None, description="The metadata attached to this name") - __properties: ClassVar[List[str]] = ["token_id", "owner_address", "manager_address", "primary_address", "domain", "avatar", "network_id", "text_records"] + expires_at: datetime = Field(description="The expiration date for this name's ownership") + text_records: Optional[Dict[str, StrictStr]] = Field(default=None, description="The metadata attached to this name") + is_primary: StrictBool = Field(description="Whether this name is the primary name for the owner (This is when the ETH coin address for this name is equal to the primary_address. More info here https://docs.ens.domains/ensip/19)") + __properties: ClassVar[List[str]] = ["token_id", "owner_address", "manager_address", "primary_address", "domain", "avatar", "network_id", "expires_at", "text_records", "is_primary"] model_config = ConfigDict( populate_by_name=True, @@ -76,13 +78,6 @@ def to_dict(self) -> Dict[str, Any]: exclude=excluded_fields, exclude_none=True, ) - # override the default output from pydantic by calling `to_dict()` of each item in text_records (list) - _items = [] - if self.text_records: - for _item_text_records in self.text_records: - if _item_text_records: - _items.append(_item_text_records.to_dict()) - _dict['text_records'] = _items return _dict @classmethod @@ -102,7 +97,9 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: "domain": obj.get("domain"), "avatar": obj.get("avatar"), "network_id": obj.get("network_id"), - "text_records": [OnchainNameTextRecordsInner.from_dict(_item) for _item in obj["text_records"]] if obj.get("text_records") is not None else None + "expires_at": obj.get("expires_at"), + "text_records": obj.get("text_records"), + "is_primary": obj.get("is_primary") }) return _obj diff --git a/cdp/faucet_transaction.py b/cdp/faucet_transaction.py index 72b03dc..8fe56ea 100644 --- a/cdp/faucet_transaction.py +++ b/cdp/faucet_transaction.py @@ -1,6 +1,10 @@ +import time + +from cdp.cdp import Cdp from cdp.client.models.faucet_transaction import ( FaucetTransaction as FaucetTransactionModel, ) +from cdp.transaction import Transaction class FaucetTransaction: @@ -15,6 +19,36 @@ def __init__(self, model: FaucetTransactionModel) -> None: """ self._model = model + if self._model.transaction is None: + raise ValueError("Faucet transaction is required.") + + self._transaction = Transaction(self._model.transaction) + + @property + def transaction(self) -> Transaction: + """Get the Faucet transaction.""" + return self._transaction + + @property + def network_id(self) -> str: + """Get the network ID. + + Returns: + str: The network ID. + + """ + return self.transaction.network_id + + @property + def address_id(self) -> str: + """Get the address. + + Returns: + str: The address. + + """ + return self.transaction.to_address_id + @property def transaction_hash(self) -> str: """Get the transaction hash. @@ -23,7 +57,7 @@ def transaction_hash(self) -> str: str: The transaction hash. """ - return self._model.transaction_hash + return self.transaction.transaction_hash @property def transaction_link(self) -> str: @@ -33,11 +67,67 @@ def transaction_link(self) -> str: str: The transaction link. """ - return self._model.transaction_link + return self.transaction.transaction_hash + + @property + def status(self) -> str: + """Get the faucet transaction status. + + Returns: + str: The faucet transaction status. + + """ + return self.transaction.status + + def wait(self, interval_seconds: float = 0.2, timeout_seconds: float = 20) -> "FaucetTransaction": + """Wait for the faucet transaction to complete. + + Args: + interval_seconds (float): The interval seconds. + timeout_seconds (float): The timeout seconds. + + Returns: + FaucetTransaction: The faucet transaction. + + """ + start_time = time.time() + + while not self.transaction.terminal_state: + self.reload() + + if time.time() - start_time > timeout_seconds: + raise TimeoutError("Timed out waiting for FaucetTransaction to land onchain") + + time.sleep(interval_seconds) + + return self + + + def reload(self) -> "FaucetTransaction": + """Reload the faucet transaction. + + Returns: + None + + """ + model = Cdp.api_clients.external_addresses.get_faucet_transaction( + self.network_id, + self.address_id, + self.transaction_hash + ) + self._model = model + + if model.transaction is None: + raise ValueError("Faucet transaction is required.") + + # Update the transaction + self._transaction = Transaction(model.transaction) + + return self def __str__(self) -> str: """Return a string representation of the FaucetTransaction.""" - return f"FaucetTransaction: (transaction_hash: {self.transaction_hash}, transaction_link: {self.transaction_link})" + return f"FaucetTransaction: (transaction_hash: {self.transaction_hash}, transaction_link: {self.transaction_link}, status: {self.status}, network_id: {self.network_id})" def __repr__(self) -> str: """Return a string representation of the FaucetTransaction.""" diff --git a/cdp/transaction.py b/cdp/transaction.py index adab0c7..3f0e451 100644 --- a/cdp/transaction.py +++ b/cdp/transaction.py @@ -104,6 +104,11 @@ def transaction_hash(self) -> str: """Get the transaction hash.""" return self._model.transaction_hash + @property + def network_id(self) -> str: + """Get the Network ID of the Transaction.""" + return self._model.network_id + @property def status(self) -> Status: """Get the status.""" diff --git a/docs/conf.py b/docs/conf.py index 0ef199d..2a89824 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -14,7 +14,7 @@ project = 'CDP SDK' author = 'Coinbase Developer Platform' -release = '0.0.9' +release = '0.10.0' # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration diff --git a/pyproject.toml b/pyproject.toml index 0d01c46..35321fe 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "cdp-sdk" -version = "0.0.9" +version = "0.10.0" description = "CDP Python SDK" readme = "README.md" authors = [{name = "John Peterson", email = "john.peterson@coinbase.com"}] diff --git a/tests/factories/faucet_transaction_factory.py b/tests/factories/faucet_transaction_factory.py new file mode 100644 index 0000000..fcb2875 --- /dev/null +++ b/tests/factories/faucet_transaction_factory.py @@ -0,0 +1,37 @@ +import pytest + +from cdp.client.models.faucet_transaction import FaucetTransaction as FaucetTransactionModel +from cdp.faucet_transaction import FaucetTransaction + + +@pytest.fixture +def faucet_transaction_model_factory(transaction_model_factory): + """Create and return a factory for creating FaucetTransactionModel fixtures.""" + + def _create_faucet_tx_model(status="complete"): + transaction_model = transaction_model_factory(status) + + if transaction_model.transaction_hash is None: + raise ValueError("Faucet transaction must have a hash.") + + if transaction_model.transaction_link is None: + raise ValueError("Faucet transaction must have a link.") + + return FaucetTransactionModel( + transaction=transaction_model, + transaction_hash=transaction_model.transaction_hash, + transaction_link=transaction_model.transaction_link, + ) + + return _create_faucet_tx_model + + +@pytest.fixture +def faucet_transaction_factory(faucet_transaction_model_factory): + """Create and return a factory for creating FaucetTransaction fixtures.""" + + def _create_faucet_transaction(status="complete"): + faucet_tx_model = faucet_transaction_model_factory(status) + return FaucetTransaction(faucet_tx_model) + + return _create_faucet_transaction diff --git a/tests/factories/transaction_factory.py b/tests/factories/transaction_factory.py index 5fd9712..51ac3a5 100644 --- a/tests/factories/transaction_factory.py +++ b/tests/factories/transaction_factory.py @@ -20,7 +20,7 @@ def _create_transaction_model(status="complete"): else None, status=status, transaction_link="https://sepolia.basescan.org/tx/0xtransactionlink" - if status == "complete" + if status in ["broadcast", "complete"] else None, block_hash="0xblockhash" if status == "complete" else None, block_height="123456" if status == "complete" else None, diff --git a/tests/test_address.py b/tests/test_address.py index c605bd8..a6241f8 100644 --- a/tests/test_address.py +++ b/tests/test_address.py @@ -29,36 +29,42 @@ def test_address_can_sign(address_factory): @patch("cdp.Cdp.api_clients") -def test_address_faucet(mock_api_clients, address_factory): +def test_address_faucet(mock_api_clients, address_factory, faucet_transaction_model_factory): """Test the faucet method of an Address.""" address = address_factory() mock_request_faucet = Mock() - mock_request_faucet.return_value = Mock(spec=FaucetTransaction) + mock_request_faucet.return_value = faucet_transaction_model_factory() mock_api_clients.external_addresses.request_external_faucet_funds = mock_request_faucet faucet_tx = address.faucet() assert isinstance(faucet_tx, FaucetTransaction) mock_request_faucet.assert_called_once_with( - network_id=address.network_id, address_id=address.address_id, asset_id=None + network_id=address.network_id, + address_id=address.address_id, + asset_id=None, + skip_wait=True ) @patch("cdp.Cdp.api_clients") -def test_address_faucet_with_asset_id(mock_api_clients, address_factory): +def test_address_faucet_with_asset_id(mock_api_clients, address_factory, faucet_transaction_model_factory): """Test the faucet method of an Address with an asset_id.""" address = address_factory() mock_request_faucet = Mock() - mock_request_faucet.return_value = Mock(spec=FaucetTransaction) + mock_request_faucet.return_value = faucet_transaction_model_factory() mock_api_clients.external_addresses.request_external_faucet_funds = mock_request_faucet faucet_tx = address.faucet(asset_id="usdc") assert isinstance(faucet_tx, FaucetTransaction) mock_request_faucet.assert_called_once_with( - network_id=address.network_id, address_id=address.address_id, asset_id="usdc" + network_id=address.network_id, + address_id=address.address_id, + asset_id="usdc", + skip_wait=True ) diff --git a/tests/test_faucet_transaction.py b/tests/test_faucet_transaction.py new file mode 100644 index 0000000..341ccab --- /dev/null +++ b/tests/test_faucet_transaction.py @@ -0,0 +1,105 @@ +from unittest.mock import Mock, call, patch + +import pytest + +from cdp.faucet_transaction import FaucetTransaction + + +def test_faucet_tx_initialization(faucet_transaction_factory): + """Test the initialization of a FaucetTransaction.""" + faucet_transaction = faucet_transaction_factory() + + assert isinstance(faucet_transaction, FaucetTransaction) + assert faucet_transaction.transaction_hash == "0xtransactionhash" + assert faucet_transaction.network_id == "base-sepolia" + assert faucet_transaction.address_id == "0xdestination" + assert faucet_transaction.status.value == "complete" + +@patch("cdp.Cdp.api_clients") +def test_reload_faucet_tx(mock_api_clients, faucet_transaction_factory): + """Test the reloading of a FaucetTransaction object.""" + faucet_tx = faucet_transaction_factory(status="broadcast") + complete_faucet_tx = faucet_transaction_factory(status="complete") + + # Mock the GetFaucetTransaction API returning a complete faucet transaction. + mock_get_faucet_tx = Mock() + mock_get_faucet_tx.return_value = complete_faucet_tx._model + mock_api_clients.external_addresses.get_faucet_transaction = mock_get_faucet_tx + + reloaded_faucet_tx = faucet_tx.reload() + + mock_get_faucet_tx.assert_called_once_with( + "base-sepolia", + "0xdestination", + "0xtransactionhash" + ) + assert faucet_tx.status.value == "complete" + assert reloaded_faucet_tx.status.value == "complete" + + +@patch("cdp.Cdp.api_clients") +@patch("cdp.faucet_transaction.time.sleep") +@patch("cdp.faucet_transaction.time.time") +def test_wait_for_faucet_transaction( + mock_time, + mock_sleep, + mock_api_clients, + faucet_transaction_factory +): + """Test the waiting for a FaucetTransaction object to complete.""" + faucet_tx = faucet_transaction_factory(status="broadcast") + complete_faucet_tx = faucet_transaction_factory(status="complete") + + # Mock GetFaucetTransaction returning a `broadcast` and then a `complete` + # faucet transaction. + mock_get_faucet_tx = Mock() + mock_api_clients.external_addresses.get_faucet_transaction = mock_get_faucet_tx + mock_get_faucet_tx.side_effect = [faucet_tx._model, complete_faucet_tx._model] + + mock_time.side_effect = [0, 0.2, 0.4] + + result = faucet_tx.wait(interval_seconds=0.2, timeout_seconds=1) + + assert result.status.value == "complete" + + mock_get_faucet_tx.assert_called_with( + "base-sepolia", + "0xdestination", + "0xtransactionhash" + ) + assert mock_get_faucet_tx.call_count == 2 + mock_sleep.assert_has_calls([call(0.2)] * 2) + assert mock_time.call_count == 3 + + +@patch("cdp.Cdp.api_clients") +@patch("cdp.faucet_transaction.time.sleep") +@patch("cdp.faucet_transaction.time.time") +def test_wait_for_faucet_transaction_timeout( + mock_time, + mock_sleep, + mock_api_clients, + faucet_transaction_factory +): + """Test the waiting for a FaucetTransaction object to complete with a timeout.""" + faucet_tx = faucet_transaction_factory(status="broadcast") + + mock_get_faucet_tx = Mock() + mock_get_faucet_tx.return_value = faucet_tx._model + mock_api_clients.external_addresses.get_faucet_transaction = mock_get_faucet_tx + + mock_time.side_effect = [0, 0.5, 1.0, 1.5, 2.0, 2.5] + + with pytest.raises(TimeoutError, match="Timed out waiting for FaucetTransaction to land onchain"): + faucet_tx.wait(interval_seconds=0.5, timeout_seconds=2) + + mock_get_faucet_tx.assert_called_with( + "base-sepolia", + "0xdestination", + "0xtransactionhash" + ) + + assert mock_get_faucet_tx.call_count == 5 + mock_sleep.assert_has_calls([call(0.5)] * 4) + assert mock_time.call_count == 6 + diff --git a/tests/test_transaction.py b/tests/test_transaction.py index ea8b58b..bc0fd98 100644 --- a/tests/test_transaction.py +++ b/tests/test_transaction.py @@ -16,6 +16,7 @@ def test_transaction_initialization(transaction_factory): assert isinstance(transaction._model, TransactionModel) assert transaction._raw is None assert transaction._signature == "0xsignedpayload" + assert transaction.network_id == "base-sepolia" def test_transaction_initialization_invalid_model(): From be5d376f068f0be59350d56bf04ef643674834bd Mon Sep 17 00:00:00 2001 From: Alexander Stone Date: Thu, 31 Oct 2024 13:32:34 -0700 Subject: [PATCH 27/40] fix(v0.10.1): Fix faucet transaction link (#40) This fixes the faucet transaction method `transaction_link` to return the transaction link instead of the transaction hash. This adds a unit test to ensure this is set properly. --- CHANGELOG.md | 3 +++ cdp/__version__.py | 2 +- cdp/faucet_transaction.py | 2 +- docs/conf.py | 2 +- pyproject.toml | 4 ++-- tests/test_faucet_transaction.py | 1 + 6 files changed, 9 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0847e2d..6a67e64 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +## [0.10.1] - 2024-10-31 +- Fix Faucet transaction_link to return the correct transaction link instead of transaction hash. + ## [0.10.0] - 2024-10-31 ### Changed diff --git a/cdp/__version__.py b/cdp/__version__.py index 61fb31c..1f4c4d4 100644 --- a/cdp/__version__.py +++ b/cdp/__version__.py @@ -1 +1 @@ -__version__ = "0.10.0" +__version__ = "0.10.1" diff --git a/cdp/faucet_transaction.py b/cdp/faucet_transaction.py index 8fe56ea..c93e1fa 100644 --- a/cdp/faucet_transaction.py +++ b/cdp/faucet_transaction.py @@ -67,7 +67,7 @@ def transaction_link(self) -> str: str: The transaction link. """ - return self.transaction.transaction_hash + return self.transaction.transaction_link @property def status(self) -> str: diff --git a/docs/conf.py b/docs/conf.py index 2a89824..d6ca70e 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -14,7 +14,7 @@ project = 'CDP SDK' author = 'Coinbase Developer Platform' -release = '0.10.0' +release = '0.10.1' # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration diff --git a/pyproject.toml b/pyproject.toml index 35321fe..88a38ec 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "cdp-sdk" -version = "0.10.0" +version = "0.10.1" description = "CDP Python SDK" readme = "README.md" authors = [{name = "John Peterson", email = "john.peterson@coinbase.com"}] @@ -141,4 +141,4 @@ line-ending = "auto" known-first-party = ["cdp"] [tool.coverage.run] -omit = ["cdp/client/*"] \ No newline at end of file +omit = ["cdp/client/*"] diff --git a/tests/test_faucet_transaction.py b/tests/test_faucet_transaction.py index 341ccab..4cab5d7 100644 --- a/tests/test_faucet_transaction.py +++ b/tests/test_faucet_transaction.py @@ -11,6 +11,7 @@ def test_faucet_tx_initialization(faucet_transaction_factory): assert isinstance(faucet_transaction, FaucetTransaction) assert faucet_transaction.transaction_hash == "0xtransactionhash" + assert faucet_transaction.transaction_link == "https://sepolia.basescan.org/tx/0xtransactionlink" assert faucet_transaction.network_id == "base-sepolia" assert faucet_transaction.address_id == "0xdestination" assert faucet_transaction.status.value == "complete" From 92a19c4a779d2eab47dc6eaf5c2a2688fe5ef20a Mon Sep 17 00:00:00 2001 From: rohan-agarwal-coinbase Date: Wed, 6 Nov 2024 19:44:38 -0500 Subject: [PATCH 28/40] Fix for additional uint and int types (#41) --- cdp/address.py | 2 +- cdp/client/__init__.py | 3 +- cdp/client/api/__init__.py | 3 +- cdp/client/api/addresses_api.py | 36 +- cdp/client/api/assets_api.py | 4 +- cdp/client/api/balance_history_api.py | 4 +- cdp/client/api/contract_events_api.py | 4 +- cdp/client/api/contract_invocations_api.py | 16 +- cdp/client/api/external_addresses_api.py | 16 +- cdp/client/api/fund_api.py | 16 +- cdp/client/api/mpc_wallet_stake_api.py | 951 ++++++++++++++++++ cdp/client/api/networks_api.py | 4 +- cdp/client/api/onchain_identity_api.py | 4 +- cdp/client/api/server_signers_api.py | 24 +- cdp/client/api/smart_contracts_api.py | 20 +- cdp/client/api/stake_api.py | 639 +++++++++++- cdp/client/api/trades_api.py | 16 +- cdp/client/api/transaction_history_api.py | 4 +- cdp/client/api/transfers_api.py | 16 +- cdp/client/api/users_api.py | 4 +- cdp/client/api/wallets_api.py | 20 +- cdp/client/api/webhooks_api.py | 20 +- cdp/client/api_client.py | 15 +- .../models/build_staking_operation_request.py | 2 +- .../create_staking_operation_request.py | 2 +- .../models/get_staking_context_request.py | 2 +- cdp/client/models/solidity_value.py | 4 +- cdp/client/rest.py | 2 +- cdp/faucet_transaction.py | 9 +- cdp/smart_contract.py | 3 + tests/factories/smart_contract_factory.py | 39 + tests/test_address.py | 11 +- tests/test_faucet_transaction.py | 38 +- tests/test_smart_contract.py | 69 ++ 34 files changed, 1909 insertions(+), 113 deletions(-) create mode 100644 cdp/client/api/mpc_wallet_stake_api.py diff --git a/cdp/address.py b/cdp/address.py index e8a24a9..abe7002 100644 --- a/cdp/address.py +++ b/cdp/address.py @@ -68,7 +68,7 @@ def faucet(self, asset_id=None) -> FaucetTransaction: network_id=self.network_id, address_id=self.address_id, asset_id=asset_id, - skip_wait=True + skip_wait=True, ) return FaucetTransaction(model) diff --git a/cdp/client/__init__.py b/cdp/client/__init__.py index 317f584..b0a5107 100644 --- a/cdp/client/__init__.py +++ b/cdp/client/__init__.py @@ -24,6 +24,7 @@ from cdp.client.api.contract_invocations_api import ContractInvocationsApi from cdp.client.api.external_addresses_api import ExternalAddressesApi from cdp.client.api.fund_api import FundApi +from cdp.client.api.mpc_wallet_stake_api import MPCWalletStakeApi from cdp.client.api.networks_api import NetworksApi from cdp.client.api.onchain_identity_api import OnchainIdentityApi from cdp.client.api.server_signers_api import ServerSignersApi @@ -33,8 +34,6 @@ from cdp.client.api.transaction_history_api import TransactionHistoryApi from cdp.client.api.transfers_api import TransfersApi from cdp.client.api.users_api import UsersApi -from cdp.client.api.validators_api import ValidatorsApi -from cdp.client.api.wallet_stake_api import WalletStakeApi from cdp.client.api.wallets_api import WalletsApi from cdp.client.api.webhooks_api import WebhooksApi diff --git a/cdp/client/api/__init__.py b/cdp/client/api/__init__.py index ce5dea3..f70084c 100644 --- a/cdp/client/api/__init__.py +++ b/cdp/client/api/__init__.py @@ -8,6 +8,7 @@ from cdp.client.api.contract_invocations_api import ContractInvocationsApi from cdp.client.api.external_addresses_api import ExternalAddressesApi from cdp.client.api.fund_api import FundApi +from cdp.client.api.mpc_wallet_stake_api import MPCWalletStakeApi from cdp.client.api.networks_api import NetworksApi from cdp.client.api.onchain_identity_api import OnchainIdentityApi from cdp.client.api.server_signers_api import ServerSignersApi @@ -17,8 +18,6 @@ from cdp.client.api.transaction_history_api import TransactionHistoryApi from cdp.client.api.transfers_api import TransfersApi from cdp.client.api.users_api import UsersApi -from cdp.client.api.validators_api import ValidatorsApi -from cdp.client.api.wallet_stake_api import WalletStakeApi from cdp.client.api.wallets_api import WalletsApi from cdp.client.api.webhooks_api import WebhooksApi diff --git a/cdp/client/api/addresses_api.py b/cdp/client/api/addresses_api.py index dca4fb9..4ec0209 100644 --- a/cdp/client/api/addresses_api.py +++ b/cdp/client/api/addresses_api.py @@ -275,7 +275,9 @@ def _create_address_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -574,7 +576,9 @@ def _create_payload_signature_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -862,7 +866,9 @@ def _get_address_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -1148,7 +1154,9 @@ def _get_address_balance_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -1436,7 +1444,9 @@ def _get_payload_signature_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -1724,7 +1734,9 @@ def _list_address_balances_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -2014,7 +2026,9 @@ def _list_addresses_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -2319,7 +2333,9 @@ def _list_payload_signatures_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -2616,7 +2632,9 @@ def _request_faucet_funds_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters diff --git a/cdp/client/api/assets_api.py b/cdp/client/api/assets_api.py index 874b2dc..8d82e45 100644 --- a/cdp/client/api/assets_api.py +++ b/cdp/client/api/assets_api.py @@ -266,7 +266,9 @@ def _get_asset_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters diff --git a/cdp/client/api/balance_history_api.py b/cdp/client/api/balance_history_api.py index c0eaf82..9bd47f5 100644 --- a/cdp/client/api/balance_history_api.py +++ b/cdp/client/api/balance_history_api.py @@ -306,7 +306,9 @@ def _list_address_historical_balance_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters diff --git a/cdp/client/api/contract_events_api.py b/cdp/client/api/contract_events_api.py index a9b88d4..c425a7b 100644 --- a/cdp/client/api/contract_events_api.py +++ b/cdp/client/api/contract_events_api.py @@ -345,7 +345,9 @@ def _list_contract_events_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters diff --git a/cdp/client/api/contract_invocations_api.py b/cdp/client/api/contract_invocations_api.py index d4330fa..8082d7b 100644 --- a/cdp/client/api/contract_invocations_api.py +++ b/cdp/client/api/contract_invocations_api.py @@ -296,7 +296,9 @@ def _broadcast_contract_invocation_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -599,7 +601,9 @@ def _create_contract_invocation_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -900,7 +904,9 @@ def _get_contract_invocation_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -1201,7 +1207,9 @@ def _list_contract_invocations_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters diff --git a/cdp/client/api/external_addresses_api.py b/cdp/client/api/external_addresses_api.py index 1975530..6fd201f 100644 --- a/cdp/client/api/external_addresses_api.py +++ b/cdp/client/api/external_addresses_api.py @@ -282,7 +282,9 @@ def _get_external_address_balance_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -570,7 +572,9 @@ def _get_faucet_transaction_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -858,7 +862,9 @@ def _list_external_address_balances_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -1161,7 +1167,9 @@ def _request_external_faucet_funds_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters diff --git a/cdp/client/api/fund_api.py b/cdp/client/api/fund_api.py index 1c62f38..9dd56c1 100644 --- a/cdp/client/api/fund_api.py +++ b/cdp/client/api/fund_api.py @@ -284,7 +284,9 @@ def _create_fund_operation_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -585,7 +587,9 @@ def _create_fund_quote_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -886,7 +890,9 @@ def _get_fund_operation_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -1187,7 +1193,9 @@ def _list_fund_operations_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters diff --git a/cdp/client/api/mpc_wallet_stake_api.py b/cdp/client/api/mpc_wallet_stake_api.py new file mode 100644 index 0000000..1d309e2 --- /dev/null +++ b/cdp/client/api/mpc_wallet_stake_api.py @@ -0,0 +1,951 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from pydantic import Field, StrictStr +from typing_extensions import Annotated +from cdp.client.models.broadcast_staking_operation_request import BroadcastStakingOperationRequest +from cdp.client.models.create_staking_operation_request import CreateStakingOperationRequest +from cdp.client.models.staking_operation import StakingOperation + +from cdp.client.api_client import ApiClient, RequestSerialized +from cdp.client.api_response import ApiResponse +from cdp.client.rest import RESTResponseType + + +class MPCWalletStakeApi: + """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) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def broadcast_staking_operation( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the staking operation belongs to.")], + staking_operation_id: Annotated[StrictStr, Field(description="The ID of the staking operation to broadcast.")], + broadcast_staking_operation_request: BroadcastStakingOperationRequest, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> StakingOperation: + """Broadcast a staking operation + + Broadcast a staking operation. + + :param wallet_id: The ID of the wallet the address belongs to. (required) + :type wallet_id: str + :param address_id: The ID of the address the staking operation belongs to. (required) + :type address_id: str + :param staking_operation_id: The ID of the staking operation to broadcast. (required) + :type staking_operation_id: str + :param broadcast_staking_operation_request: (required) + :type broadcast_staking_operation_request: BroadcastStakingOperationRequest + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._broadcast_staking_operation_serialize( + wallet_id=wallet_id, + address_id=address_id, + staking_operation_id=staking_operation_id, + broadcast_staking_operation_request=broadcast_staking_operation_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def broadcast_staking_operation_with_http_info( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the staking operation belongs to.")], + staking_operation_id: Annotated[StrictStr, Field(description="The ID of the staking operation to broadcast.")], + broadcast_staking_operation_request: BroadcastStakingOperationRequest, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[StakingOperation]: + """Broadcast a staking operation + + Broadcast a staking operation. + + :param wallet_id: The ID of the wallet the address belongs to. (required) + :type wallet_id: str + :param address_id: The ID of the address the staking operation belongs to. (required) + :type address_id: str + :param staking_operation_id: The ID of the staking operation to broadcast. (required) + :type staking_operation_id: str + :param broadcast_staking_operation_request: (required) + :type broadcast_staking_operation_request: BroadcastStakingOperationRequest + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._broadcast_staking_operation_serialize( + wallet_id=wallet_id, + address_id=address_id, + staking_operation_id=staking_operation_id, + broadcast_staking_operation_request=broadcast_staking_operation_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def broadcast_staking_operation_without_preload_content( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address the staking operation belongs to.")], + staking_operation_id: Annotated[StrictStr, Field(description="The ID of the staking operation to broadcast.")], + broadcast_staking_operation_request: BroadcastStakingOperationRequest, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Broadcast a staking operation + + Broadcast a staking operation. + + :param wallet_id: The ID of the wallet the address belongs to. (required) + :type wallet_id: str + :param address_id: The ID of the address the staking operation belongs to. (required) + :type address_id: str + :param staking_operation_id: The ID of the staking operation to broadcast. (required) + :type staking_operation_id: str + :param broadcast_staking_operation_request: (required) + :type broadcast_staking_operation_request: BroadcastStakingOperationRequest + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._broadcast_staking_operation_serialize( + wallet_id=wallet_id, + address_id=address_id, + staking_operation_id=staking_operation_id, + broadcast_staking_operation_request=broadcast_staking_operation_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _broadcast_staking_operation_serialize( + self, + wallet_id, + address_id, + staking_operation_id, + broadcast_staking_operation_request, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if wallet_id is not None: + _path_params['wallet_id'] = wallet_id + if address_id is not None: + _path_params['address_id'] = address_id + if staking_operation_id is not None: + _path_params['staking_operation_id'] = staking_operation_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if broadcast_staking_operation_request is not None: + _body_params = broadcast_staking_operation_request + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/staking_operations/{staking_operation_id}/broadcast', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def create_staking_operation( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to create the staking operation for.")], + create_staking_operation_request: CreateStakingOperationRequest, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> StakingOperation: + """Create a new staking operation for an address + + Create a new staking operation. + + :param wallet_id: The ID of the wallet the address belongs to. (required) + :type wallet_id: str + :param address_id: The ID of the address to create the staking operation for. (required) + :type address_id: str + :param create_staking_operation_request: (required) + :type create_staking_operation_request: CreateStakingOperationRequest + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_staking_operation_serialize( + wallet_id=wallet_id, + address_id=address_id, + create_staking_operation_request=create_staking_operation_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def create_staking_operation_with_http_info( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to create the staking operation for.")], + create_staking_operation_request: CreateStakingOperationRequest, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[StakingOperation]: + """Create a new staking operation for an address + + Create a new staking operation. + + :param wallet_id: The ID of the wallet the address belongs to. (required) + :type wallet_id: str + :param address_id: The ID of the address to create the staking operation for. (required) + :type address_id: str + :param create_staking_operation_request: (required) + :type create_staking_operation_request: CreateStakingOperationRequest + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_staking_operation_serialize( + wallet_id=wallet_id, + address_id=address_id, + create_staking_operation_request=create_staking_operation_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def create_staking_operation_without_preload_content( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to create the staking operation for.")], + create_staking_operation_request: CreateStakingOperationRequest, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Create a new staking operation for an address + + Create a new staking operation. + + :param wallet_id: The ID of the wallet the address belongs to. (required) + :type wallet_id: str + :param address_id: The ID of the address to create the staking operation for. (required) + :type address_id: str + :param create_staking_operation_request: (required) + :type create_staking_operation_request: CreateStakingOperationRequest + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_staking_operation_serialize( + wallet_id=wallet_id, + address_id=address_id, + create_staking_operation_request=create_staking_operation_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _create_staking_operation_serialize( + self, + wallet_id, + address_id, + create_staking_operation_request, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if wallet_id is not None: + _path_params['wallet_id'] = wallet_id + if address_id is not None: + _path_params['address_id'] = address_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if create_staking_operation_request is not None: + _body_params = create_staking_operation_request + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/staking_operations', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_staking_operation( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the staking operation for.")], + staking_operation_id: Annotated[StrictStr, Field(description="The ID of the staking operation.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> StakingOperation: + """Get the latest state of a staking operation + + Get the latest state of a staking operation. + + :param wallet_id: The ID of the wallet the address belongs to (required) + :type wallet_id: str + :param address_id: The ID of the address to fetch the staking operation for. (required) + :type address_id: str + :param staking_operation_id: The ID of the staking operation. (required) + :type staking_operation_id: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_staking_operation_serialize( + wallet_id=wallet_id, + address_id=address_id, + staking_operation_id=staking_operation_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_staking_operation_with_http_info( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the staking operation for.")], + staking_operation_id: Annotated[StrictStr, Field(description="The ID of the staking operation.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[StakingOperation]: + """Get the latest state of a staking operation + + Get the latest state of a staking operation. + + :param wallet_id: The ID of the wallet the address belongs to (required) + :type wallet_id: str + :param address_id: The ID of the address to fetch the staking operation for. (required) + :type address_id: str + :param staking_operation_id: The ID of the staking operation. (required) + :type staking_operation_id: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_staking_operation_serialize( + wallet_id=wallet_id, + address_id=address_id, + staking_operation_id=staking_operation_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_staking_operation_without_preload_content( + self, + wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the staking operation for.")], + staking_operation_id: Annotated[StrictStr, Field(description="The ID of the staking operation.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get the latest state of a staking operation + + Get the latest state of a staking operation. + + :param wallet_id: The ID of the wallet the address belongs to (required) + :type wallet_id: str + :param address_id: The ID of the address to fetch the staking operation for. (required) + :type address_id: str + :param staking_operation_id: The ID of the staking operation. (required) + :type staking_operation_id: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_staking_operation_serialize( + wallet_id=wallet_id, + address_id=address_id, + staking_operation_id=staking_operation_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "StakingOperation", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_staking_operation_serialize( + self, + wallet_id, + address_id, + staking_operation_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if wallet_id is not None: + _path_params['wallet_id'] = wallet_id + if address_id is not None: + _path_params['address_id'] = address_id + if staking_operation_id is not None: + _path_params['staking_operation_id'] = staking_operation_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/staking_operations/{staking_operation_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/cdp/client/api/networks_api.py b/cdp/client/api/networks_api.py index 954fc20..de7dd00 100644 --- a/cdp/client/api/networks_api.py +++ b/cdp/client/api/networks_api.py @@ -253,7 +253,9 @@ def _get_network_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters diff --git a/cdp/client/api/onchain_identity_api.py b/cdp/client/api/onchain_identity_api.py index 757d351..e09fdf8 100644 --- a/cdp/client/api/onchain_identity_api.py +++ b/cdp/client/api/onchain_identity_api.py @@ -307,7 +307,9 @@ def _resolve_identity_by_address_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters diff --git a/cdp/client/api/server_signers_api.py b/cdp/client/api/server_signers_api.py index 7c570c2..84e3e82 100644 --- a/cdp/client/api/server_signers_api.py +++ b/cdp/client/api/server_signers_api.py @@ -259,7 +259,9 @@ def _create_server_signer_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -530,7 +532,9 @@ def _get_server_signer_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -817,7 +821,9 @@ def _list_server_signer_events_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -1096,7 +1102,9 @@ def _list_server_signers_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -1373,7 +1381,9 @@ def _submit_server_signer_seed_event_result_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -1659,7 +1669,9 @@ def _submit_server_signer_signature_event_result_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters diff --git a/cdp/client/api/smart_contracts_api.py b/cdp/client/api/smart_contracts_api.py index db0c90f..6d59210 100644 --- a/cdp/client/api/smart_contracts_api.py +++ b/cdp/client/api/smart_contracts_api.py @@ -284,7 +284,9 @@ def _create_smart_contract_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -598,7 +600,9 @@ def _deploy_smart_contract_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -901,7 +905,9 @@ def _get_smart_contract_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -1176,7 +1182,9 @@ def _list_smart_contracts_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -1462,7 +1470,9 @@ def _read_contract_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters diff --git a/cdp/client/api/stake_api.py b/cdp/client/api/stake_api.py index ff3f4f8..f2790f3 100644 --- a/cdp/client/api/stake_api.py +++ b/cdp/client/api/stake_api.py @@ -27,6 +27,9 @@ from cdp.client.models.get_staking_context_request import GetStakingContextRequest from cdp.client.models.staking_context import StakingContext from cdp.client.models.staking_operation import StakingOperation +from cdp.client.models.validator import Validator +from cdp.client.models.validator_list import ValidatorList +from cdp.client.models.validator_status import ValidatorStatus from cdp.client.api_client import ApiClient, RequestSerialized from cdp.client.api_response import ApiResponse @@ -261,7 +264,9 @@ def _build_staking_operation_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -610,7 +615,9 @@ def _fetch_historical_staking_balances_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -934,7 +941,9 @@ def _fetch_staking_rewards_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -1239,7 +1248,9 @@ def _get_external_staking_operation_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -1501,7 +1512,9 @@ def _get_staking_context_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -1555,3 +1568,619 @@ def _get_staking_context_serialize( ) + + + @validate_call + def get_validator( + self, + network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network.")], + asset_id: Annotated[StrictStr, Field(description="The symbol of the asset to get the validator for.")], + validator_id: Annotated[StrictStr, Field(description="The unique id of the validator to fetch details for.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Validator: + """Get a validator belonging to the CDP project + + Get a validator belonging to the user for a given network, asset and id. + + :param network_id: The ID of the blockchain network. (required) + :type network_id: str + :param asset_id: The symbol of the asset to get the validator for. (required) + :type asset_id: str + :param validator_id: The unique id of the validator to fetch details for. (required) + :type validator_id: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_validator_serialize( + network_id=network_id, + asset_id=asset_id, + validator_id=validator_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Validator", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_validator_with_http_info( + self, + network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network.")], + asset_id: Annotated[StrictStr, Field(description="The symbol of the asset to get the validator for.")], + validator_id: Annotated[StrictStr, Field(description="The unique id of the validator to fetch details for.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Validator]: + """Get a validator belonging to the CDP project + + Get a validator belonging to the user for a given network, asset and id. + + :param network_id: The ID of the blockchain network. (required) + :type network_id: str + :param asset_id: The symbol of the asset to get the validator for. (required) + :type asset_id: str + :param validator_id: The unique id of the validator to fetch details for. (required) + :type validator_id: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_validator_serialize( + network_id=network_id, + asset_id=asset_id, + validator_id=validator_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Validator", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_validator_without_preload_content( + self, + network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network.")], + asset_id: Annotated[StrictStr, Field(description="The symbol of the asset to get the validator for.")], + validator_id: Annotated[StrictStr, Field(description="The unique id of the validator to fetch details for.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a validator belonging to the CDP project + + Get a validator belonging to the user for a given network, asset and id. + + :param network_id: The ID of the blockchain network. (required) + :type network_id: str + :param asset_id: The symbol of the asset to get the validator for. (required) + :type asset_id: str + :param validator_id: The unique id of the validator to fetch details for. (required) + :type validator_id: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_validator_serialize( + network_id=network_id, + asset_id=asset_id, + validator_id=validator_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Validator", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_validator_serialize( + self, + network_id, + asset_id, + validator_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if network_id is not None: + _path_params['network_id'] = network_id + if asset_id is not None: + _path_params['asset_id'] = asset_id + if validator_id is not None: + _path_params['validator_id'] = validator_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v1/networks/{network_id}/assets/{asset_id}/validators/{validator_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def list_validators( + self, + network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network.")], + asset_id: Annotated[StrictStr, Field(description="The symbol of the asset to get the validators for.")], + status: Annotated[Optional[ValidatorStatus], Field(description="A filter to list validators based on a status.")] = None, + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ValidatorList: + """List validators belonging to the CDP project + + List validators belonging to the user for a given network and asset. + + :param network_id: The ID of the blockchain network. (required) + :type network_id: str + :param asset_id: The symbol of the asset to get the validators for. (required) + :type asset_id: str + :param status: A filter to list validators based on a status. + :type status: ValidatorStatus + :param limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50. + :type limit: int + :param page: A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + :type page: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_validators_serialize( + network_id=network_id, + asset_id=asset_id, + status=status, + limit=limit, + page=page, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ValidatorList", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def list_validators_with_http_info( + self, + network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network.")], + asset_id: Annotated[StrictStr, Field(description="The symbol of the asset to get the validators for.")], + status: Annotated[Optional[ValidatorStatus], Field(description="A filter to list validators based on a status.")] = None, + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ValidatorList]: + """List validators belonging to the CDP project + + List validators belonging to the user for a given network and asset. + + :param network_id: The ID of the blockchain network. (required) + :type network_id: str + :param asset_id: The symbol of the asset to get the validators for. (required) + :type asset_id: str + :param status: A filter to list validators based on a status. + :type status: ValidatorStatus + :param limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50. + :type limit: int + :param page: A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + :type page: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_validators_serialize( + network_id=network_id, + asset_id=asset_id, + status=status, + limit=limit, + page=page, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ValidatorList", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def list_validators_without_preload_content( + self, + network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network.")], + asset_id: Annotated[StrictStr, Field(description="The symbol of the asset to get the validators for.")], + status: Annotated[Optional[ValidatorStatus], Field(description="A filter to list validators based on a status.")] = None, + limit: Annotated[Optional[StrictInt], Field(description="A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50.")] = None, + page: Annotated[Optional[Annotated[str, Field(strict=True, max_length=5000)]], Field(description="A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List validators belonging to the CDP project + + List validators belonging to the user for a given network and asset. + + :param network_id: The ID of the blockchain network. (required) + :type network_id: str + :param asset_id: The symbol of the asset to get the validators for. (required) + :type asset_id: str + :param status: A filter to list validators based on a status. + :type status: ValidatorStatus + :param limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 50. + :type limit: int + :param page: A cursor for pagination across multiple pages of results. Don't include this parameter on the first call. Use the next_page value returned in a previous response to request subsequent results. + :type page: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_validators_serialize( + network_id=network_id, + asset_id=asset_id, + status=status, + limit=limit, + page=page, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ValidatorList", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _list_validators_serialize( + self, + network_id, + asset_id, + status, + limit, + page, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if network_id is not None: + _path_params['network_id'] = network_id + if asset_id is not None: + _path_params['asset_id'] = asset_id + # process the query parameters + if status is not None: + + _query_params.append(('status', status.value)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if page is not None: + + _query_params.append(('page', page)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v1/networks/{network_id}/assets/{asset_id}/validators', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/cdp/client/api/trades_api.py b/cdp/client/api/trades_api.py index fd58ed4..1e010cb 100644 --- a/cdp/client/api/trades_api.py +++ b/cdp/client/api/trades_api.py @@ -296,7 +296,9 @@ def _broadcast_trade_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -599,7 +601,9 @@ def _create_trade_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -900,7 +904,9 @@ def _get_trade_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -1201,7 +1207,9 @@ def _list_trades_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters diff --git a/cdp/client/api/transaction_history_api.py b/cdp/client/api/transaction_history_api.py index 785824a..02b6ea7 100644 --- a/cdp/client/api/transaction_history_api.py +++ b/cdp/client/api/transaction_history_api.py @@ -293,7 +293,9 @@ def _list_address_transactions_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters diff --git a/cdp/client/api/transfers_api.py b/cdp/client/api/transfers_api.py index 0ed5523..a7be92c 100644 --- a/cdp/client/api/transfers_api.py +++ b/cdp/client/api/transfers_api.py @@ -296,7 +296,9 @@ def _broadcast_transfer_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -599,7 +601,9 @@ def _create_transfer_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -900,7 +904,9 @@ def _get_transfer_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -1201,7 +1207,9 @@ def _list_transfers_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters diff --git a/cdp/client/api/users_api.py b/cdp/client/api/users_api.py index 8afc9b9..0d59f56 100644 --- a/cdp/client/api/users_api.py +++ b/cdp/client/api/users_api.py @@ -238,7 +238,9 @@ def _get_current_user_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters diff --git a/cdp/client/api/wallets_api.py b/cdp/client/api/wallets_api.py index 86cd94b..66eaa59 100644 --- a/cdp/client/api/wallets_api.py +++ b/cdp/client/api/wallets_api.py @@ -258,7 +258,9 @@ def _create_wallet_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -529,7 +531,9 @@ def _get_wallet_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -800,7 +804,9 @@ def _get_wallet_balance_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -1060,7 +1066,9 @@ def _list_wallet_balances_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -1331,7 +1339,9 @@ def _list_wallets_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters diff --git a/cdp/client/api/webhooks_api.py b/cdp/client/api/webhooks_api.py index 7e0f4c7..ba2844a 100644 --- a/cdp/client/api/webhooks_api.py +++ b/cdp/client/api/webhooks_api.py @@ -271,7 +271,9 @@ def _create_wallet_webhook_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -544,7 +546,9 @@ def _create_webhook_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -815,7 +819,9 @@ def _delete_webhook_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -1086,7 +1092,9 @@ def _list_webhooks_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters @@ -1363,7 +1371,9 @@ def _update_webhook_serialize( _query_params: List[Tuple[str, str]] = [] _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, Union[str, bytes]] = {} + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} _body_params: Optional[bytes] = None # process the path parameters diff --git a/cdp/client/api_client.py b/cdp/client/api_client.py index 52369de..82d3c54 100644 --- a/cdp/client/api_client.py +++ b/cdp/client/api_client.py @@ -404,12 +404,12 @@ def deserialize(self, response_text: str, response_type: str, content_type: Opti data = json.loads(response_text) except ValueError: data = response_text - elif content_type.startswith("application/json"): + elif re.match(r'^application/(json|[\w!#$&.+-^_]+\+json)\s*(;|$)', content_type, re.IGNORECASE): if response_text == "": data = "" else: data = json.loads(response_text) - elif content_type.startswith("text/plain"): + elif re.match(r'^text\/[a-z.+-]+\s*(;|$)', content_type, re.IGNORECASE): data = response_text else: raise ApiException( @@ -535,7 +535,10 @@ def parameters_to_url_query(self, params, collection_formats): return "&".join(["=".join(map(str, item)) for item in new_params]) - def files_parameters(self, files: Dict[str, Union[str, bytes]]): + def files_parameters( + self, + files: Dict[str, Union[str, bytes, List[str], List[bytes], Tuple[str, bytes]]], + ): """Builds form parameters. :param files: File parameters. @@ -550,6 +553,12 @@ def files_parameters(self, files: Dict[str, Union[str, bytes]]): elif isinstance(v, bytes): filename = k filedata = v + elif isinstance(v, tuple): + filename, filedata = v + elif isinstance(v, list): + for file_param in v: + params.extend(self.files_parameters({k: file_param})) + continue else: raise ValueError("Unsupported file value") mimetype = ( diff --git a/cdp/client/models/build_staking_operation_request.py b/cdp/client/models/build_staking_operation_request.py index 7238168..b36fbb5 100644 --- a/cdp/client/models/build_staking_operation_request.py +++ b/cdp/client/models/build_staking_operation_request.py @@ -30,7 +30,7 @@ class BuildStakingOperationRequest(BaseModel): asset_id: StrictStr = Field(description="The ID of the asset being staked") address_id: StrictStr = Field(description="The onchain address from which the staking transaction originates and is responsible for signing the transaction.") action: StrictStr = Field(description="The type of staking operation") - options: Dict[str, StrictStr] + options: Dict[str, StrictStr] = Field(description="Additional options for the staking operation.") __properties: ClassVar[List[str]] = ["network_id", "asset_id", "address_id", "action", "options"] model_config = ConfigDict( diff --git a/cdp/client/models/create_staking_operation_request.py b/cdp/client/models/create_staking_operation_request.py index 677206b..a89b998 100644 --- a/cdp/client/models/create_staking_operation_request.py +++ b/cdp/client/models/create_staking_operation_request.py @@ -29,7 +29,7 @@ class CreateStakingOperationRequest(BaseModel): network_id: StrictStr = Field(description="The ID of the blockchain network.") asset_id: StrictStr = Field(description="The ID of the asset being staked.") action: StrictStr = Field(description="The type of staking operation.") - options: Dict[str, StrictStr] + options: Dict[str, StrictStr] = Field(description="Additional options for the staking operation.") __properties: ClassVar[List[str]] = ["network_id", "asset_id", "action", "options"] model_config = ConfigDict( diff --git a/cdp/client/models/get_staking_context_request.py b/cdp/client/models/get_staking_context_request.py index c2918e6..d755995 100644 --- a/cdp/client/models/get_staking_context_request.py +++ b/cdp/client/models/get_staking_context_request.py @@ -29,7 +29,7 @@ class GetStakingContextRequest(BaseModel): network_id: StrictStr = Field(description="The ID of the blockchain network") asset_id: StrictStr = Field(description="The ID of the asset being staked") address_id: StrictStr = Field(description="The onchain address for which the staking context is being fetched") - options: Dict[str, StrictStr] + options: Dict[str, StrictStr] = Field(description="Additional options for getting the staking context. This typically includes network specific fields.") __properties: ClassVar[List[str]] = ["network_id", "asset_id", "address_id", "options"] model_config = ConfigDict( diff --git a/cdp/client/models/solidity_value.py b/cdp/client/models/solidity_value.py index 0efcf21..54e4ea9 100644 --- a/cdp/client/models/solidity_value.py +++ b/cdp/client/models/solidity_value.py @@ -35,8 +35,8 @@ class SolidityValue(BaseModel): @field_validator('type') def type_validate_enum(cls, value): """Validates the enum""" - if value not in set(['uint8', 'uint16', 'uint32', 'uint64', 'uint128', 'uint256', 'int8', 'int16', 'int32', 'int64', 'int128', 'int256', 'address', 'bool', 'string', 'bytes', 'bytes1', 'bytes2', 'bytes3', 'bytes4', 'bytes5', 'bytes6', 'bytes7', 'bytes8', 'bytes9', 'bytes10', 'bytes11', 'bytes12', 'bytes13', 'bytes14', 'bytes15', 'bytes16', 'bytes17', 'bytes18', 'bytes19', 'bytes20', 'bytes21', 'bytes22', 'bytes23', 'bytes24', 'bytes25', 'bytes26', 'bytes27', 'bytes28', 'bytes29', 'bytes30', 'bytes31', 'bytes32', 'array', 'tuple']): - raise ValueError("must be one of enum values ('uint8', 'uint16', 'uint32', 'uint64', 'uint128', 'uint256', 'int8', 'int16', 'int32', 'int64', 'int128', 'int256', 'address', 'bool', 'string', 'bytes', 'bytes1', 'bytes2', 'bytes3', 'bytes4', 'bytes5', 'bytes6', 'bytes7', 'bytes8', 'bytes9', 'bytes10', 'bytes11', 'bytes12', 'bytes13', 'bytes14', 'bytes15', 'bytes16', 'bytes17', 'bytes18', 'bytes19', 'bytes20', 'bytes21', 'bytes22', 'bytes23', 'bytes24', 'bytes25', 'bytes26', 'bytes27', 'bytes28', 'bytes29', 'bytes30', 'bytes31', 'bytes32', 'array', 'tuple')") + if value not in set(['uint8', 'uint16', 'uint32', 'uint64', 'uint128', 'uint160', 'uint256', 'int8', 'int16', 'int24', 'int32', 'int56', 'int64', 'int128', 'int256', 'address', 'bool', 'string', 'bytes', 'bytes1', 'bytes2', 'bytes3', 'bytes4', 'bytes5', 'bytes6', 'bytes7', 'bytes8', 'bytes9', 'bytes10', 'bytes11', 'bytes12', 'bytes13', 'bytes14', 'bytes15', 'bytes16', 'bytes17', 'bytes18', 'bytes19', 'bytes20', 'bytes21', 'bytes22', 'bytes23', 'bytes24', 'bytes25', 'bytes26', 'bytes27', 'bytes28', 'bytes29', 'bytes30', 'bytes31', 'bytes32', 'array', 'tuple']): + raise ValueError("must be one of enum values ('uint8', 'uint16', 'uint32', 'uint64', 'uint128', 'uint160', 'uint256', 'int8', 'int16', 'int24', 'int32', 'int56', 'int64', 'int128', 'int256', 'address', 'bool', 'string', 'bytes', 'bytes1', 'bytes2', 'bytes3', 'bytes4', 'bytes5', 'bytes6', 'bytes7', 'bytes8', 'bytes9', 'bytes10', 'bytes11', 'bytes12', 'bytes13', 'bytes14', 'bytes15', 'bytes16', 'bytes17', 'bytes18', 'bytes19', 'bytes20', 'bytes21', 'bytes22', 'bytes23', 'bytes24', 'bytes25', 'bytes26', 'bytes27', 'bytes28', 'bytes29', 'bytes30', 'bytes31', 'bytes32', 'array', 'tuple')") return value model_config = ConfigDict( diff --git a/cdp/client/rest.py b/cdp/client/rest.py index 78c1966..77874d5 100644 --- a/cdp/client/rest.py +++ b/cdp/client/rest.py @@ -225,7 +225,7 @@ def request( headers=headers, preload_content=False ) - elif headers['Content-Type'] == 'text/plain' and isinstance(body, bool): + elif headers['Content-Type'].startswith('text/') and isinstance(body, bool): request_body = "true" if body else "false" r = self.pool_manager.request( method, diff --git a/cdp/faucet_transaction.py b/cdp/faucet_transaction.py index c93e1fa..d4a9e57 100644 --- a/cdp/faucet_transaction.py +++ b/cdp/faucet_transaction.py @@ -79,7 +79,9 @@ def status(self) -> str: """ return self.transaction.status - def wait(self, interval_seconds: float = 0.2, timeout_seconds: float = 20) -> "FaucetTransaction": + def wait( + self, interval_seconds: float = 0.2, timeout_seconds: float = 20 + ) -> "FaucetTransaction": """Wait for the faucet transaction to complete. Args: @@ -102,7 +104,6 @@ def wait(self, interval_seconds: float = 0.2, timeout_seconds: float = 20) -> "F return self - def reload(self) -> "FaucetTransaction": """Reload the faucet transaction. @@ -111,9 +112,7 @@ def reload(self) -> "FaucetTransaction": """ model = Cdp.api_clients.external_addresses.get_faucet_transaction( - self.network_id, - self.address_id, - self.transaction_hash + self.network_id, self.address_id, self.transaction_hash ) self._model = model diff --git a/cdp/smart_contract.py b/cdp/smart_contract.py index 58b6e96..a1b919c 100644 --- a/cdp/smart_contract.py +++ b/cdp/smart_contract.py @@ -385,10 +385,13 @@ def _convert_solidity_value(cls, solidity_value: SolidityValue) -> Any: "uint32", "uint64", "uint128", + "uint160", "uint256", "int8", "int16", + "int24", "int32", + "int56", "int64", "int128", "int256", diff --git a/tests/factories/smart_contract_factory.py b/tests/factories/smart_contract_factory.py index 99bc4da..e8d16d4 100644 --- a/tests/factories/smart_contract_factory.py +++ b/tests/factories/smart_contract_factory.py @@ -141,6 +141,19 @@ def all_read_types_abi(): ], "stateMutability": "pure", }, + { + "type": "function", + "name": "pureInt24", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "int24", + "internalType": "int24", + }, + ], + "stateMutability": "pure", + }, { "type": "function", "name": "pureInt256", @@ -167,6 +180,19 @@ def all_read_types_abi(): ], "stateMutability": "pure", }, + { + "type": "function", + "name": "pureInt56", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "int56", + "internalType": "int56", + }, + ], + "stateMutability": "pure", + }, { "type": "function", "name": "pureInt64", @@ -304,6 +330,19 @@ def all_read_types_abi(): ], "stateMutability": "pure", }, + { + "type": "function", + "name": "pureUint160", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "uint160", + "internalType": "uint160", + }, + ], + "stateMutability": "pure", + }, { "type": "function", "name": "pureUint16", diff --git a/tests/test_address.py b/tests/test_address.py index a6241f8..4c255cd 100644 --- a/tests/test_address.py +++ b/tests/test_address.py @@ -41,15 +41,14 @@ def test_address_faucet(mock_api_clients, address_factory, faucet_transaction_mo assert isinstance(faucet_tx, FaucetTransaction) mock_request_faucet.assert_called_once_with( - network_id=address.network_id, - address_id=address.address_id, - asset_id=None, - skip_wait=True + network_id=address.network_id, address_id=address.address_id, asset_id=None, skip_wait=True ) @patch("cdp.Cdp.api_clients") -def test_address_faucet_with_asset_id(mock_api_clients, address_factory, faucet_transaction_model_factory): +def test_address_faucet_with_asset_id( + mock_api_clients, address_factory, faucet_transaction_model_factory +): """Test the faucet method of an Address with an asset_id.""" address = address_factory() @@ -64,7 +63,7 @@ def test_address_faucet_with_asset_id(mock_api_clients, address_factory, faucet_ network_id=address.network_id, address_id=address.address_id, asset_id="usdc", - skip_wait=True + skip_wait=True, ) diff --git a/tests/test_faucet_transaction.py b/tests/test_faucet_transaction.py index 4cab5d7..b8afdb8 100644 --- a/tests/test_faucet_transaction.py +++ b/tests/test_faucet_transaction.py @@ -11,11 +11,14 @@ def test_faucet_tx_initialization(faucet_transaction_factory): assert isinstance(faucet_transaction, FaucetTransaction) assert faucet_transaction.transaction_hash == "0xtransactionhash" - assert faucet_transaction.transaction_link == "https://sepolia.basescan.org/tx/0xtransactionlink" + assert ( + faucet_transaction.transaction_link == "https://sepolia.basescan.org/tx/0xtransactionlink" + ) assert faucet_transaction.network_id == "base-sepolia" assert faucet_transaction.address_id == "0xdestination" assert faucet_transaction.status.value == "complete" + @patch("cdp.Cdp.api_clients") def test_reload_faucet_tx(mock_api_clients, faucet_transaction_factory): """Test the reloading of a FaucetTransaction object.""" @@ -29,11 +32,7 @@ def test_reload_faucet_tx(mock_api_clients, faucet_transaction_factory): reloaded_faucet_tx = faucet_tx.reload() - mock_get_faucet_tx.assert_called_once_with( - "base-sepolia", - "0xdestination", - "0xtransactionhash" - ) + mock_get_faucet_tx.assert_called_once_with("base-sepolia", "0xdestination", "0xtransactionhash") assert faucet_tx.status.value == "complete" assert reloaded_faucet_tx.status.value == "complete" @@ -42,10 +41,7 @@ def test_reload_faucet_tx(mock_api_clients, faucet_transaction_factory): @patch("cdp.faucet_transaction.time.sleep") @patch("cdp.faucet_transaction.time.time") def test_wait_for_faucet_transaction( - mock_time, - mock_sleep, - mock_api_clients, - faucet_transaction_factory + mock_time, mock_sleep, mock_api_clients, faucet_transaction_factory ): """Test the waiting for a FaucetTransaction object to complete.""" faucet_tx = faucet_transaction_factory(status="broadcast") @@ -63,11 +59,7 @@ def test_wait_for_faucet_transaction( assert result.status.value == "complete" - mock_get_faucet_tx.assert_called_with( - "base-sepolia", - "0xdestination", - "0xtransactionhash" - ) + mock_get_faucet_tx.assert_called_with("base-sepolia", "0xdestination", "0xtransactionhash") assert mock_get_faucet_tx.call_count == 2 mock_sleep.assert_has_calls([call(0.2)] * 2) assert mock_time.call_count == 3 @@ -77,10 +69,7 @@ def test_wait_for_faucet_transaction( @patch("cdp.faucet_transaction.time.sleep") @patch("cdp.faucet_transaction.time.time") def test_wait_for_faucet_transaction_timeout( - mock_time, - mock_sleep, - mock_api_clients, - faucet_transaction_factory + mock_time, mock_sleep, mock_api_clients, faucet_transaction_factory ): """Test the waiting for a FaucetTransaction object to complete with a timeout.""" faucet_tx = faucet_transaction_factory(status="broadcast") @@ -91,16 +80,13 @@ def test_wait_for_faucet_transaction_timeout( mock_time.side_effect = [0, 0.5, 1.0, 1.5, 2.0, 2.5] - with pytest.raises(TimeoutError, match="Timed out waiting for FaucetTransaction to land onchain"): + with pytest.raises( + TimeoutError, match="Timed out waiting for FaucetTransaction to land onchain" + ): faucet_tx.wait(interval_seconds=0.5, timeout_seconds=2) - mock_get_faucet_tx.assert_called_with( - "base-sepolia", - "0xdestination", - "0xtransactionhash" - ) + mock_get_faucet_tx.assert_called_with("base-sepolia", "0xdestination", "0xtransactionhash") assert mock_get_faucet_tx.call_count == 5 mock_sleep.assert_has_calls([call(0.5)] * 4) assert mock_time.call_count == 6 - diff --git a/tests/test_smart_contract.py b/tests/test_smart_contract.py index 591aa42..f07d5d4 100644 --- a/tests/test_smart_contract.py +++ b/tests/test_smart_contract.py @@ -1093,6 +1093,31 @@ def test_read_pure_uint128(mock_api_clients, all_read_types_abi): ) +@patch("cdp.Cdp.api_clients") +def test_read_pure_uint160(mock_api_clients, all_read_types_abi): + """Test reading a uint160 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue( + type="uint160", + value="115792089237316195423570985008687907853269984665640564039457584007913129639935", + ) + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureUint160", + abi=all_read_types_abi, + ) + + assert result == 115792089237316195423570985008687907853269984665640564039457584007913129639935 + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + @patch("cdp.Cdp.api_clients") def test_read_pure_uint256(mock_api_clients, all_read_types_abi): """Test reading a uint256 value from a pure function.""" @@ -1162,6 +1187,28 @@ def test_read_pure_int16(mock_api_clients, all_read_types_abi): ) +@patch("cdp.Cdp.api_clients") +def test_read_pure_int24(mock_api_clients, all_read_types_abi): + """Test reading an int24 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="int24", value="-8388608") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureInt24", + abi=all_read_types_abi, + ) + + assert result == -8388608 + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + @patch("cdp.Cdp.api_clients") def test_read_pure_int32(mock_api_clients, all_read_types_abi): """Test reading an int32 value from a pure function.""" @@ -1184,6 +1231,28 @@ def test_read_pure_int32(mock_api_clients, all_read_types_abi): ) +@patch("cdp.Cdp.api_clients") +def test_read_pure_int56(mock_api_clients, all_read_types_abi): + """Test reading an int56 value from a pure function.""" + mock_read_contract = Mock() + mock_read_contract.return_value = SolidityValue(type="int56", value="-72057594037927936") + mock_api_clients.smart_contracts.read_contract = mock_read_contract + + result = SmartContract.read( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + method="pureInt56", + abi=all_read_types_abi, + ) + + assert result == -72057594037927936 + mock_read_contract.assert_called_once_with( + network_id="1", + contract_address="0x1234567890123456789012345678901234567890", + read_contract_request=ANY, + ) + + @patch("cdp.Cdp.api_clients") def test_read_pure_int64(mock_api_clients, all_read_types_abi): """Test reading an int64 value from a pure function.""" From d8264a0ccb5913f881e1a55837a2cedc585c2d5e Mon Sep 17 00:00:00 2001 From: rohan-agarwal-coinbase Date: Wed, 6 Nov 2024 20:03:33 -0500 Subject: [PATCH 29/40] Bump to 0.10.2, updated changelog, updated docs (#42) --- CHANGELOG.md | 10 ++++ cdp/__version__.py | 2 +- docs/cdp.client.api.rst | 24 ++++++++ docs/cdp.client.models.rst | 112 +++++++++++++++++++++++++++++++++++++ docs/cdp.rst | 8 +++ docs/conf.py | 2 +- pyproject.toml | 2 +- 7 files changed, 157 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a67e64..b12d4e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,12 +2,22 @@ ## Unreleased +## [0.10.2] - 2024-11-06 + +### Added + +- Support for reading int24, int56, and uint160 values from smart contracts. + ## [0.10.1] - 2024-10-31 + +### Fixed + - Fix Faucet transaction_link to return the correct transaction link instead of transaction hash. ## [0.10.0] - 2024-10-31 ### Changed + - Make faucet transactions async i.e. using `faucet_tx.wait()` to wait for the transaction to be confirmed. - This will make the SDK more consistent and make faucet transactions more reliable. diff --git a/cdp/__version__.py b/cdp/__version__.py index 1f4c4d4..17c1a62 100644 --- a/cdp/__version__.py +++ b/cdp/__version__.py @@ -1 +1 @@ -__version__ = "0.10.1" +__version__ = "0.10.2" diff --git a/docs/cdp.client.api.rst b/docs/cdp.client.api.rst index 4a064c1..42d4bdd 100644 --- a/docs/cdp.client.api.rst +++ b/docs/cdp.client.api.rst @@ -52,6 +52,22 @@ cdp.client.api.external\_addresses\_api module :undoc-members: :show-inheritance: +cdp.client.api.fund\_api module +------------------------------- + +.. automodule:: cdp.client.api.fund_api + :members: + :undoc-members: + :show-inheritance: + +cdp.client.api.mpc\_wallet\_stake\_api module +--------------------------------------------- + +.. automodule:: cdp.client.api.mpc_wallet_stake_api + :members: + :undoc-members: + :show-inheritance: + cdp.client.api.networks\_api module ----------------------------------- @@ -60,6 +76,14 @@ cdp.client.api.networks\_api module :undoc-members: :show-inheritance: +cdp.client.api.onchain\_identity\_api module +-------------------------------------------- + +.. automodule:: cdp.client.api.onchain_identity_api + :members: + :undoc-members: + :show-inheritance: + cdp.client.api.server\_signers\_api module ------------------------------------------ diff --git a/docs/cdp.client.models.rst b/docs/cdp.client.models.rst index 1438528..f0c182e 100644 --- a/docs/cdp.client.models.rst +++ b/docs/cdp.client.models.rst @@ -148,6 +148,22 @@ cdp.client.models.create\_contract\_invocation\_request module :undoc-members: :show-inheritance: +cdp.client.models.create\_fund\_operation\_request module +--------------------------------------------------------- + +.. automodule:: cdp.client.models.create_fund_operation_request + :members: + :undoc-members: + :show-inheritance: + +cdp.client.models.create\_fund\_quote\_request module +----------------------------------------------------- + +.. automodule:: cdp.client.models.create_fund_quote_request + :members: + :undoc-members: + :show-inheritance: + cdp.client.models.create\_payload\_signature\_request module ------------------------------------------------------------ @@ -228,6 +244,14 @@ cdp.client.models.create\_webhook\_request module :undoc-members: :show-inheritance: +cdp.client.models.crypto\_amount module +--------------------------------------- + +.. automodule:: cdp.client.models.crypto_amount + :members: + :undoc-members: + :show-inheritance: + cdp.client.models.deploy\_smart\_contract\_request module --------------------------------------------------------- @@ -260,6 +284,14 @@ cdp.client.models.error module :undoc-members: :show-inheritance: +cdp.client.models.ethereum\_token\_transfer module +-------------------------------------------------- + +.. automodule:: cdp.client.models.ethereum_token_transfer + :members: + :undoc-members: + :show-inheritance: + cdp.client.models.ethereum\_transaction module ---------------------------------------------- @@ -340,6 +372,46 @@ cdp.client.models.fetch\_staking\_rewards\_request module :undoc-members: :show-inheritance: +cdp.client.models.fiat\_amount module +------------------------------------- + +.. automodule:: cdp.client.models.fiat_amount + :members: + :undoc-members: + :show-inheritance: + +cdp.client.models.fund\_operation module +---------------------------------------- + +.. automodule:: cdp.client.models.fund_operation + :members: + :undoc-members: + :show-inheritance: + +cdp.client.models.fund\_operation\_fees module +---------------------------------------------- + +.. automodule:: cdp.client.models.fund_operation_fees + :members: + :undoc-members: + :show-inheritance: + +cdp.client.models.fund\_operation\_list module +---------------------------------------------- + +.. automodule:: cdp.client.models.fund_operation_list + :members: + :undoc-members: + :show-inheritance: + +cdp.client.models.fund\_quote module +------------------------------------ + +.. automodule:: cdp.client.models.fund_quote + :members: + :undoc-members: + :show-inheritance: + cdp.client.models.get\_staking\_context\_request module ------------------------------------------------------- @@ -388,6 +460,30 @@ cdp.client.models.nft\_contract\_options module :undoc-members: :show-inheritance: +cdp.client.models.onchain\_name module +-------------------------------------- + +.. automodule:: cdp.client.models.onchain_name + :members: + :undoc-members: + :show-inheritance: + +cdp.client.models.onchain\_name\_list module +-------------------------------------------- + +.. automodule:: cdp.client.models.onchain_name_list + :members: + :undoc-members: + :show-inheritance: + +cdp.client.models.onchain\_name\_text\_records\_inner module +------------------------------------------------------------ + +.. automodule:: cdp.client.models.onchain_name_text_records_inner + :members: + :undoc-members: + :show-inheritance: + cdp.client.models.payload\_signature module ------------------------------------------- @@ -412,6 +508,14 @@ cdp.client.models.read\_contract\_request module :undoc-members: :show-inheritance: +cdp.client.models.read\_smart\_contract\_request module +------------------------------------------------------- + +.. automodule:: cdp.client.models.read_smart_contract_request + :members: + :undoc-members: + :show-inheritance: + cdp.client.models.seed\_creation\_event module ---------------------------------------------- @@ -612,6 +716,14 @@ cdp.client.models.token\_contract\_options module :undoc-members: :show-inheritance: +cdp.client.models.token\_transfer\_type module +---------------------------------------------- + +.. automodule:: cdp.client.models.token_transfer_type + :members: + :undoc-members: + :show-inheritance: + cdp.client.models.trade module ------------------------------ diff --git a/docs/cdp.rst b/docs/cdp.rst index ca117b5..02b6d26 100644 --- a/docs/cdp.rst +++ b/docs/cdp.rst @@ -180,6 +180,14 @@ cdp.wallet\_data module :undoc-members: :show-inheritance: +cdp.webhook module +------------------ + +.. automodule:: cdp.webhook + :members: + :undoc-members: + :show-inheritance: + Module contents --------------- diff --git a/docs/conf.py b/docs/conf.py index d6ca70e..249feb8 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -14,7 +14,7 @@ project = 'CDP SDK' author = 'Coinbase Developer Platform' -release = '0.10.1' +release = '0.10.2' # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration diff --git a/pyproject.toml b/pyproject.toml index 88a38ec..9610f45 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "cdp-sdk" -version = "0.10.1" +version = "0.10.2" description = "CDP Python SDK" readme = "README.md" authors = [{name = "John Peterson", email = "john.peterson@coinbase.com"}] From 06e33d5bc2bf3f8ca33158e32b4cd8c9684b4f92 Mon Sep 17 00:00:00 2001 From: Adrian Lopez <109683617+adriangomez24@users.noreply.github.com> Date: Thu, 7 Nov 2024 07:58:01 -0500 Subject: [PATCH 30/40] Adds source and source type for better usage monitoring (#43) * add source and source version to better monitor usage * improve docstring * address changes and add more tests * set defaults and add more tests --------- Co-authored-by: Adrian Lopez --- cdp/cdp.py | 21 +++++++++++++++++++-- cdp/cdp_api_client.py | 11 ++++++++++- cdp/constants.py | 4 ++++ tests/test_api_client.py | 34 ++++++++++++++++++++++++++++++++++ 4 files changed, 67 insertions(+), 3 deletions(-) create mode 100644 cdp/constants.py create mode 100644 tests/test_api_client.py diff --git a/cdp/cdp.py b/cdp/cdp.py index fba59ee..84c2416 100644 --- a/cdp/cdp.py +++ b/cdp/cdp.py @@ -1,8 +1,10 @@ import json import os +from cdp import __version__ from cdp.api_clients import ApiClients from cdp.cdp_api_client import CdpApiClient +from cdp.constants import SDK_DEFAULT_SOURCE from cdp.errors import InvalidConfigurationError @@ -54,6 +56,8 @@ def configure( debugging: bool = False, base_path: str = "https://api.cdp.coinbase.com/platform", max_network_retries: int = 3, + source: str = SDK_DEFAULT_SOURCE, + source_version: str = __version__, ) -> None: """Configure the CDP SDK. @@ -64,6 +68,8 @@ def configure( debugging (bool): Whether debugging is enabled. Defaults to False. base_path (str): The base URL for the CDP API. Defaults to "https://api.cdp.coinbase.com/platform". max_network_retries (int): The maximum number of network retries. Defaults to 3. + source (Optional[str]): Specifies whether the sdk is being used directly or if it's an Agentkit extension. + source_version (Optional[str]): The version of the source package. """ cls.api_key_name = api_key_name @@ -74,7 +80,13 @@ def configure( cls.max_network_retries = max_network_retries cdp_client = CdpApiClient( - api_key_name, private_key, base_path, debugging, max_network_retries + api_key_name, + private_key, + base_path, + debugging, + max_network_retries, + source, + source_version, ) cls.api_clients = ApiClients(cdp_client) @@ -86,6 +98,8 @@ def configure_from_json( debugging: bool = False, base_path: str = "https://api.cdp.coinbase.com/platform", max_network_retries: int = 3, + source: str = SDK_DEFAULT_SOURCE, + source_version: str = __version__, ) -> None: """Configure the CDP SDK from a JSON file. @@ -95,6 +109,8 @@ def configure_from_json( debugging (bool): Whether debugging is enabled. Defaults to False. base_path (str): The base URL for the CDP API. Defaults to "https://api.cdp.coinbase.com/platform". max_network_retries (int): The maximum number of network retries. Defaults to 3. + source (Optional[str]): Specifies whether the sdk is being used directly or if it's an Agentkit extension. + source_version (Optional[str]): The version of the source package. Raises: InvalidConfigurationError: If the JSON file is missing the 'api_key_name' or 'private_key'. @@ -108,7 +124,6 @@ def configure_from_json( raise InvalidConfigurationError("Invalid JSON format: Missing 'api_key_name'") if not private_key: raise InvalidConfigurationError("Invalid JSON format: Missing 'private_key'") - cls.configure( api_key_name, private_key, @@ -116,4 +131,6 @@ def configure_from_json( debugging, base_path, max_network_retries, + source, + source_version, ) diff --git a/cdp/cdp_api_client.py b/cdp/cdp_api_client.py index 783919d..15a7d2f 100644 --- a/cdp/cdp_api_client.py +++ b/cdp/cdp_api_client.py @@ -14,6 +14,7 @@ from cdp.client.api_response import T as ApiResponseT # noqa: N811 from cdp.client.configuration import Configuration from cdp.client.exceptions import ApiException +from cdp.constants import SDK_DEFAULT_SOURCE from cdp.errors import ApiError, InvalidAPIKeyFormatError @@ -27,6 +28,8 @@ def __init__( host: str = "https://api.cdp.coinbase.com/platform", debugging: bool = False, max_network_retries: int = 3, + source: str = SDK_DEFAULT_SOURCE, + source_version: str = __version__, ): """Initialize the CDP API Client. @@ -36,6 +39,8 @@ def __init__( host (str, optional): The base URL for the API. Defaults to "https://api.cdp.coinbase.com/platform". debugging (bool): Whether debugging is enabled. max_network_retries (int): The maximum number of network retries. Defaults to 3. + source (str): Specifies whether the sdk is being used directly or if it's an Agentkit extension. + source_version (str): The version of the source package. """ retry_strategy = self._get_retry_strategy(max_network_retries) @@ -44,6 +49,8 @@ def __init__( self._api_key = api_key self._private_key = private_key self._debugging = debugging + self._source = source + self._source_version = source_version @property def api_key(self) -> str: @@ -208,7 +215,7 @@ def _nonce(self) -> str: return "".join(random.choices("0123456789", k=16)) def _get_correlation_data(self) -> str: - """Return encoded correlation data including the SDK version and language. + """Return encoded correlation data including the SDK version, language, and source. Returns: str: The correlation data. @@ -217,6 +224,8 @@ def _get_correlation_data(self) -> str: data = { "sdk_version": __version__, "sdk_language": "python", + "source": self._source, + "source_version": self._source_version, } return ",".join(f"{key}={value}" for key, value in data.items()) diff --git a/cdp/constants.py b/cdp/constants.py new file mode 100644 index 0000000..c72717c --- /dev/null +++ b/cdp/constants.py @@ -0,0 +1,4 @@ +"""Specifies package level constants used throughout the package.""" + +# SDK_DEFAULT_SOURCE (str): Denotes the default source for the Python SDK. +SDK_DEFAULT_SOURCE = "sdk" diff --git a/tests/test_api_client.py b/tests/test_api_client.py new file mode 100644 index 0000000..0e8b418 --- /dev/null +++ b/tests/test_api_client.py @@ -0,0 +1,34 @@ +from cdp import __version__ +from cdp.cdp import Cdp +from cdp.cdp_api_client import CdpApiClient +from cdp.constants import SDK_DEFAULT_SOURCE + + +def test_api_client_get_correlation_data(): + """Tests _get_correlation_data from the CdpApiClient.""" + cdp_api_client = CdpApiClient( + api_key="test", + private_key="test", + ) + expected_result = f"""sdk_version={__version__},sdk_language=python,source={SDK_DEFAULT_SOURCE},source_version={__version__}""" + assert cdp_api_client._get_correlation_data() == expected_result + + cdp_api_client2 = CdpApiClient( + api_key="test", + private_key="test", + host="https://api.cdp.coinbase.com/platform", + debugging=False, + max_network_retries=3, + source="test", + source_version="test_ver", + ) + expected_result2 = ( + f"""sdk_version={__version__},sdk_language=python,source=test,source_version=test_ver""" + ) + assert cdp_api_client2._get_correlation_data() == expected_result2 + + Cdp.configure(api_key_name="test", private_key="test") + assert Cdp.api_clients._cdp_client._get_correlation_data() == expected_result + + Cdp.configure(api_key_name="test", private_key="test", source="test", source_version="test_ver") + assert Cdp.api_clients._cdp_client._get_correlation_data() == expected_result2 From 7660b83075f3403ae82bab5741820d9350243a32 Mon Sep 17 00:00:00 2001 From: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> Date: Thu, 7 Nov 2024 10:46:56 -0500 Subject: [PATCH 31/40] chore: Release 0.10.3 (#44) * chore: Release 0.10.3 * patch invoke contract str arg bug --- CHANGELOG.md | 10 ++++++++++ cdp/__version__.py | 2 +- cdp/wallet_address.py | 2 +- docs/conf.py | 2 +- pyproject.toml | 2 +- 5 files changed, 14 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b12d4e4..f87bbc4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +## [0.10.3] - 2024-11-07 + +### Added + +- Adds `source` and `source_version` to correlation header for better observability. + +### Fixed + +- Fix bug in `WalletAddress` `invoke_contract` that failed to properly handle `amount` with type `str` + ## [0.10.2] - 2024-11-06 ### Added diff --git a/cdp/__version__.py b/cdp/__version__.py index 17c1a62..b2385cb 100644 --- a/cdp/__version__.py +++ b/cdp/__version__.py @@ -1 +1 @@ -__version__ = "0.10.2" +__version__ = "0.10.3" diff --git a/cdp/wallet_address.py b/cdp/wallet_address.py index 98f0a8a..19bfb83 100644 --- a/cdp/wallet_address.py +++ b/cdp/wallet_address.py @@ -176,7 +176,7 @@ def invoke_contract( normalized_amount = Decimal(amount) if amount else Decimal("0") if amount and asset_id: - self._ensure_sufficient_balance(amount, asset_id) + self._ensure_sufficient_balance(normalized_amount, asset_id) invocation = ContractInvocation.create( address_id=self.address_id, diff --git a/docs/conf.py b/docs/conf.py index 249feb8..5dc3ee9 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -14,7 +14,7 @@ project = 'CDP SDK' author = 'Coinbase Developer Platform' -release = '0.10.2' +release = '0.10.3' # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration diff --git a/pyproject.toml b/pyproject.toml index 9610f45..251d4fc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "cdp-sdk" -version = "0.10.2" +version = "0.10.3" description = "CDP Python SDK" readme = "README.md" authors = [{name = "John Peterson", email = "john.peterson@coinbase.com"}] From 550e4593ace6fe32477ea4d3d4476786292e6a91 Mon Sep 17 00:00:00 2001 From: John Peterson <98187317+John-peterson-coinbase@users.noreply.github.com> Date: Fri, 15 Nov 2024 14:14:18 +0700 Subject: [PATCH 32/40] chore: Update README to Clarify Wallet Hydration + Doc Links (#45) * chore: Update README to Clarify Wallet Hydration + Doc Links * typo --- README.md | 79 ++++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 69 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index f46bd48..d8680d9 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,9 @@ To start a Python REPL: python ``` -## Creating a Wallet +## Quickstart + +### Creating a Wallet To start, [create a CDP API key](https://portal.cdp.coinbase.com/access/api). Then, initialize the CDP SDK by passing your API key name and API key's private key via the `configure` method: @@ -69,7 +71,7 @@ print("CDP SDK has been successfully configured from JSON file.") This will allow you to authenticate with the Platform APIs. -If you are using a CDP Server-Signer to manage your private keys, enable it with +If you are using a CDP [Server-Signer](https://docs.cdp.coinbase.com/mpc-wallet/docs/serversigners) to manage your private keys, enable it with ```python Cdp.use_server_signer = True @@ -91,7 +93,7 @@ Wallets come with a single default address, accessible via `default_address`: address = wallet1.default_address ``` -## Funding a Wallet +### Funding a Wallet Wallets do not have funds on them to start. For Base Sepolia testnet, we provide a `faucet` method to fund your wallet with testnet ETH. You are allowed one faucet claim per 24-hour window. @@ -106,7 +108,7 @@ faucet_tx.wait() print(f"Faucet transaction successfully completed: {faucet_tx}") ``` -## Transferring Funds +### Transferring Funds See [Transfers](https://docs.cdp.coinbase.com/wallets/docs/transfers) for more information. @@ -125,7 +127,7 @@ transfer = wallet1.transfer(0.00001, "eth", wallet2).wait() print(f"Transfer successfully completed: {transfer}") ``` -### Gasless USDC Transfers +#### Gasless USDC Transfers To transfer USDC without needing to hold ETH for gas, you can use the `transfer` method with the `gasless` option set to `True`. @@ -146,14 +148,14 @@ print(f"Faucet transaction successfully completed: {usdc_faucet_tx}") transfer = wallet1.transfer(0.00001, "usdc", wallet3, gasless=True).wait() ``` -## Listing Transfers +### Listing Transfers ```python # Return list of all transfers. This will paginate and fetch all transfers for the address. list(address.transfers()) ``` -## Trading Funds +### Trading Funds See [Trades](https://docs.cdp.coinbase.com/wallets/docs/trades) for more information. @@ -168,14 +170,68 @@ trade = wallet.trade(0.00001, "eth", "usdc").wait() print(f"Trade successfully completed: {trade}") ``` -## Listing Trades +### Listing Trades ```python # Return list of all trades. This will paginate and fetch all trades for the address. list(address.trades()) ``` -## Creating a Webhook +### Re-Instantiating Wallets + +The SDK creates wallets with [Developer-Managed (1-1)](https://docs.cdp.coinbase.com/mpc-wallet/docs/wallets#developer-managed-wallets) keys by default, which means you are responsible for securely storing the keys required to re-instantiate wallets. The below code walks you through how to export a wallet and store it in a secure location. + +```python +# Export the data required to re-instantiate the wallet. The data contains the seed and the ID of the wallet. +data = wallet.export_data() +``` + +In order to persist the data for the wallet, you will need to implement a store method to store the data export in a secure location. If you do not store the wallet in a secure location you will lose access to the wallet and all of the funds on it. + +```python +# You should implement the "store" method to securely persist the data object, +# which is required to re-instantiate the wallet at a later time. For ease of use, +# the data object is converted to a dictionary first. +store(data.to_dict()) +``` + +For convenience during testing, we provide a `save_seed` method that stores the wallet's seed in your local file system. This is an insecure method of storing wallet seeds and should only be used for development purposes. + +To encrypt the saved data, set encrypt to `True`. Note that your CDP API key also serves as the encryption key for the data persisted locally. To re-instantiate wallets with encrypted data, ensure that your SDK is configured with the same API key when invoking `save_seed` and `load_seed`. + +```python +# Pick a file to which to save your wallet seed. +file_path = "my_seed.json" + +# Set encrypt=True to encrypt the wallet seed with your CDP secret API key. +wallet.save_seed(file_path, encrypt=True) + +print(f"Seed for wallet {wallet.id} successfully saved to {file_path}.") +``` + +The below code demonstrates how to re-instantiate a wallet from the data export. + +```python +# You should implement the "fetch" method to retrieve the securely persisted data object, +# keyed by the wallet ID. +fetched_data = fetch(wallet.id) + +# imported_wallet will be equivalent to wallet. +imported_wallet = Wallet.import_data(fetched_data) +``` + +To import Wallets that were persisted to your local file system using `save_seed`, use the below code. + +```python +# Get the unhydrated wallet from the server. +fetched_wallet = Wallet.fetch(wallet.id) + +# You can now load the seed into the wallet from the local file. +# fetched_wallet will be equivalent to imported_wallet. +fetched_wallet.load_seed(file_path) +``` + +### Creating a Webhook A webhook is a way to provide other applications with real-time information from the blockchain. When an event occurs on a blockchain address, it can send a POST request to a URL you specify. You can create a webhook to receive notifications about events that occur in your wallet or crypto address, such as when a user makes a transfer. ```python from cdp.client.models.webhook import WebhookEventType @@ -189,7 +245,7 @@ wh1 = Webhook.create( print(wh1) ``` -## Creating a Webhook On A Wallet +### Creating a Webhook On A Wallet A webhook can be attached to an existing wallet to monitor events that occur on the wallet, i.e. all addresses associated with this wallet. A list of supported blockchain events can be found [here](https://docs.cdp.coinbase.com/get-started/docs/webhooks/event-types). ```python import cdp @@ -199,6 +255,9 @@ wh1 = wallet1.create_webhook("https://your-app.com/callback") print(wh1) ``` +## Examples +Examples, demo apps, and further code samples can be found in the [CDP SDK Python Documentation](https://docs.cdp.coinbase.com/cdp-apis/docs/welcome). + ## Contributing See [CONTRIBUTING.md](CONTRIBUTING.md) for more information. From a6b358704c975613758ed33ebff0a643953e07a1 Mon Sep 17 00:00:00 2001 From: rohan-agarwal-coinbase Date: Thu, 21 Nov 2024 18:38:03 -0500 Subject: [PATCH 33/40] Fix Asset from_model bug to use passed in asset_id when initializing (#46) --- CHANGELOG.md | 3 +++ cdp/asset.py | 2 +- tests/test_asset.py | 2 ++ tests/test_balance.py | 2 +- 4 files changed, 7 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f87bbc4..0f69fff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +### Fixed +- Fix bug in `Asset.from_model` where passed in asset ID was not used when creating a gwei or wei asset. + ## [0.10.3] - 2024-11-07 ### Added diff --git a/cdp/asset.py b/cdp/asset.py index c3857f6..d03a35d 100644 --- a/cdp/asset.py +++ b/cdp/asset.py @@ -52,7 +52,7 @@ def from_model(cls, model: AssetModel, asset_id: str | None = None) -> "Asset": return cls( network_id=model.network_id, - asset_id=model.asset_id, + asset_id=asset_id or model.asset_id, contract_address=model.contract_address, decimals=decimals, ) diff --git a/tests/test_asset.py b/tests/test_asset.py index 3b36338..2cea01b 100644 --- a/tests/test_asset.py +++ b/tests/test_asset.py @@ -32,6 +32,7 @@ def test_asset_from_model_with_gwei(asset_model_factory): asset_model = asset_model_factory(asset_id="eth", decimals=18) asset = Asset.from_model(asset_model, asset_id="gwei") + assert asset.asset_id == "gwei" assert asset.decimals == 9 @@ -40,6 +41,7 @@ def test_asset_from_model_with_wei(asset_model_factory): asset_model = asset_model_factory(asset_id="eth", decimals=18) asset = Asset.from_model(asset_model, asset_id="wei") + assert asset.asset_id == "wei" assert asset.decimals == 0 diff --git a/tests/test_balance.py b/tests/test_balance.py index 3f4f691..53303c9 100644 --- a/tests/test_balance.py +++ b/tests/test_balance.py @@ -42,7 +42,7 @@ def test_balance_from_model_with_asset_id(balance_model_factory): balance = Balance.from_model(balance_model, asset_id="gwei") assert balance.amount == Decimal("1000000000") assert isinstance(balance.asset, Asset) - assert balance.asset.asset_id == "eth" + assert balance.asset.asset_id == "gwei" assert balance.asset_id == "gwei" From ed052f17b02b97f958c475ff49237eed6b3d23be Mon Sep 17 00:00:00 2001 From: Chris Gerber Date: Mon, 25 Nov 2024 14:58:57 -0800 Subject: [PATCH 34/40] feat: export wallet address (#48) * first pass implementing wallet address private key export as a hex string * formatting * implementing feedback * adding additional check for key bytes --------- Co-authored-by: Christopher Gerber --- cdp/wallet_address.py | 20 ++++++++++++++++++++ tests/test_wallet_address.py | 19 +++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/cdp/wallet_address.py b/cdp/wallet_address.py index 19bfb83..4f0efa8 100644 --- a/cdp/wallet_address.py +++ b/cdp/wallet_address.py @@ -72,6 +72,26 @@ def can_sign(self) -> bool: """ return self.key is not None + def export(self) -> str: + """Export the wallet address's private key as a hex string. + + Returns: + str: The wallet address's private key as a hex string. + + Raises: + ValueError: If the wallet address does not have a private key. + + """ + local_account = self.key + if local_account is None: + raise ValueError("Private key is unavailable") + + key_bytes = local_account.key + if key_bytes is None: + raise ValueError("Private key is empty") + + return key_bytes.hex() + def transfer( self, amount: Number | Decimal | str, diff --git a/tests/test_wallet_address.py b/tests/test_wallet_address.py index a04d6f2..883782c 100644 --- a/tests/test_wallet_address.py +++ b/tests/test_wallet_address.py @@ -81,6 +81,25 @@ def test_key_setter_raises_error_when_already_set(wallet_address_factory): wallet_address_with_key.key = new_key +def test_export(wallet_address_factory): + """Test export method success for a WalletAddress.""" + wallet_address_with_key = wallet_address_factory(True) + + key_hex = wallet_address_with_key.export() + + assert key_hex is not None + assert key_hex != "" + assert key_hex.startswith("0x") + + +def test_export_raises_error_when_local_account_is_none(wallet_address_factory): + """Test export method failure for a WalletAddress with no LocalAccount.""" + wallet_address_without_key = wallet_address_factory() + + with pytest.raises(ValueError, match="Private key is unavailable"): + wallet_address_without_key.export() + + @patch("cdp.wallet_address.Transfer") @patch("cdp.Cdp.api_clients") @patch("cdp.Cdp.use_server_signer", True) From 4ebb72ffa962a0974a962db12d4623b5b0f30122 Mon Sep 17 00:00:00 2001 From: Chris Gerber Date: Tue, 26 Nov 2024 07:47:45 -0800 Subject: [PATCH 35/40] chore: release 0.10.4 (#49) --- CHANGELOG.md | 6 ++++++ cdp/__version__.py | 2 +- docs/conf.py | 3 +-- pyproject.toml | 2 +- 4 files changed, 9 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f87bbc4..8d307a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +## [0.10.4] - 2024-11-25 + +### Added + +- Wallet address key export + ## [0.10.3] - 2024-11-07 ### Added diff --git a/cdp/__version__.py b/cdp/__version__.py index b2385cb..d9b054a 100644 --- a/cdp/__version__.py +++ b/cdp/__version__.py @@ -1 +1 @@ -__version__ = "0.10.3" +__version__ = "0.10.4" diff --git a/docs/conf.py b/docs/conf.py index 5dc3ee9..647a963 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -14,7 +14,7 @@ project = 'CDP SDK' author = 'Coinbase Developer Platform' -release = '0.10.3' +release = '0.10.4' # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration @@ -30,7 +30,6 @@ exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] - # -- Options for HTML output ------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output diff --git a/pyproject.toml b/pyproject.toml index 251d4fc..4fdb416 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "cdp-sdk" -version = "0.10.3" +version = "0.10.4" description = "CDP Python SDK" readme = "README.md" authors = [{name = "John Peterson", email = "john.peterson@coinbase.com"}] From 1d02804d16c3f90b31bcc123fc1de0e7dcd37e9e Mon Sep 17 00:00:00 2001 From: rohan-agarwal-coinbase Date: Wed, 27 Nov 2024 14:21:55 -0500 Subject: [PATCH 36/40] Support for fund and quote_fund for wallet funding (#47) --- CHANGELOG.md | 4 + cdp/api_clients.py | 17 + cdp/client/__init__.py | 4 + cdp/client/api/__init__.py | 1 + cdp/client/api/reputation_api.py | 589 ++++++++++++++++++ cdp/client/models/__init__.py | 3 + cdp/client/models/address_reputation.py | 93 +++ .../models/address_reputation_metadata.py | 105 ++++ cdp/client/models/address_risk.py | 87 +++ cdp/crypto_amount.py | 116 ++++ cdp/fiat_amount.py | 69 ++ cdp/fund_operation.py | 247 ++++++++ cdp/fund_quote.py | 199 ++++++ cdp/wallet.py | 40 ++ cdp/wallet_address.py | 44 ++ tests/factories/crypto_amount_factory.py | 28 + tests/factories/fund_operation_factory.py | 51 ++ tests/factories/fund_quote_factory.py | 45 ++ tests/test_crypto_amount.py | 74 +++ tests/test_fiat_amount.py | 36 ++ tests/test_fund_operation.py | 206 ++++++ tests/test_fund_quote.py | 93 +++ tests/test_wallet.py | 123 ++-- tests/test_wallet_address.py | 80 +++ 24 files changed, 2299 insertions(+), 55 deletions(-) create mode 100644 cdp/client/api/reputation_api.py create mode 100644 cdp/client/models/address_reputation.py create mode 100644 cdp/client/models/address_reputation_metadata.py create mode 100644 cdp/client/models/address_risk.py create mode 100644 cdp/crypto_amount.py create mode 100644 cdp/fiat_amount.py create mode 100644 cdp/fund_operation.py create mode 100644 cdp/fund_quote.py create mode 100644 tests/factories/crypto_amount_factory.py create mode 100644 tests/factories/fund_operation_factory.py create mode 100644 tests/factories/fund_quote_factory.py create mode 100644 tests/test_crypto_amount.py create mode 100644 tests/test_fiat_amount.py create mode 100644 tests/test_fund_operation.py create mode 100644 tests/test_fund_quote.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f69fff..915995e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ ### Fixed - Fix bug in `Asset.from_model` where passed in asset ID was not used when creating a gwei or wei asset. +### Added + +- Add `FundOperation` and `FundQuote` classes to support wallet funding. + ## [0.10.3] - 2024-11-07 ### Added diff --git a/cdp/api_clients.py b/cdp/api_clients.py index 46c7532..e60e17b 100644 --- a/cdp/api_clients.py +++ b/cdp/api_clients.py @@ -4,6 +4,7 @@ from cdp.client.api.balance_history_api import BalanceHistoryApi from cdp.client.api.contract_invocations_api import ContractInvocationsApi from cdp.client.api.external_addresses_api import ExternalAddressesApi +from cdp.client.api.fund_api import FundApi from cdp.client.api.networks_api import NetworksApi from cdp.client.api.smart_contracts_api import SmartContractsApi from cdp.client.api.trades_api import TradesApi @@ -53,6 +54,7 @@ def __init__(self, cdp_client: CdpApiClient) -> None: self._smart_contracts: SmartContractsApi | None = None self._balance_history: BalanceHistoryApi | None = None self._transaction_history: TransactionHistoryApi | None = None + self._fund: FundApi | None = None @property def wallets(self) -> WalletsApi: @@ -233,3 +235,18 @@ def transaction_history(self) -> TransactionHistoryApi: if self._transaction_history is None: self._transaction_history = TransactionHistoryApi(api_client=self._cdp_client) return self._transaction_history + + @property + def fund(self) -> FundApi: + """Get the FundApi client instance. + + Returns: + FundApi: The FundApi client instance. + + Note: + This property lazily initializes the FundApi client on first access. + + """ + if self._fund is None: + self._fund = FundApi(api_client=self._cdp_client) + return self._fund diff --git a/cdp/client/__init__.py b/cdp/client/__init__.py index b0a5107..52e517f 100644 --- a/cdp/client/__init__.py +++ b/cdp/client/__init__.py @@ -27,6 +27,7 @@ from cdp.client.api.mpc_wallet_stake_api import MPCWalletStakeApi from cdp.client.api.networks_api import NetworksApi from cdp.client.api.onchain_identity_api import OnchainIdentityApi +from cdp.client.api.reputation_api import ReputationApi from cdp.client.api.server_signers_api import ServerSignersApi from cdp.client.api.smart_contracts_api import SmartContractsApi from cdp.client.api.stake_api import StakeApi @@ -53,6 +54,9 @@ from cdp.client.models.address_balance_list import AddressBalanceList from cdp.client.models.address_historical_balance_list import AddressHistoricalBalanceList from cdp.client.models.address_list import AddressList +from cdp.client.models.address_reputation import AddressReputation +from cdp.client.models.address_reputation_metadata import AddressReputationMetadata +from cdp.client.models.address_risk import AddressRisk from cdp.client.models.address_transaction_list import AddressTransactionList from cdp.client.models.asset import Asset from cdp.client.models.balance import Balance diff --git a/cdp/client/api/__init__.py b/cdp/client/api/__init__.py index f70084c..09e4751 100644 --- a/cdp/client/api/__init__.py +++ b/cdp/client/api/__init__.py @@ -11,6 +11,7 @@ from cdp.client.api.mpc_wallet_stake_api import MPCWalletStakeApi from cdp.client.api.networks_api import NetworksApi from cdp.client.api.onchain_identity_api import OnchainIdentityApi +from cdp.client.api.reputation_api import ReputationApi from cdp.client.api.server_signers_api import ServerSignersApi from cdp.client.api.smart_contracts_api import SmartContractsApi from cdp.client.api.stake_api import StakeApi diff --git a/cdp/client/api/reputation_api.py b/cdp/client/api/reputation_api.py new file mode 100644 index 0000000..5d77525 --- /dev/null +++ b/cdp/client/api/reputation_api.py @@ -0,0 +1,589 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from pydantic import Field, StrictStr +from typing_extensions import Annotated +from cdp.client.models.address_reputation import AddressReputation +from cdp.client.models.address_risk import AddressRisk + +from cdp.client.api_client import ApiClient, RequestSerialized +from cdp.client.api_response import ApiResponse +from cdp.client.rest import RESTResponseType + + +class ReputationApi: + """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) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def get_address_reputation( + self, + network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the reputation for.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> AddressReputation: + """Get the onchain reputation of an external address + + Get the onchain reputation of an external address + + :param network_id: The ID of the blockchain network. (required) + :type network_id: str + :param address_id: The ID of the address to fetch the reputation for. (required) + :type address_id: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_address_reputation_serialize( + network_id=network_id, + address_id=address_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressReputation", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_address_reputation_with_http_info( + self, + network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the reputation for.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[AddressReputation]: + """Get the onchain reputation of an external address + + Get the onchain reputation of an external address + + :param network_id: The ID of the blockchain network. (required) + :type network_id: str + :param address_id: The ID of the address to fetch the reputation for. (required) + :type address_id: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_address_reputation_serialize( + network_id=network_id, + address_id=address_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressReputation", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_address_reputation_without_preload_content( + self, + network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the reputation for.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get the onchain reputation of an external address + + Get the onchain reputation of an external address + + :param network_id: The ID of the blockchain network. (required) + :type network_id: str + :param address_id: The ID of the address to fetch the reputation for. (required) + :type address_id: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_address_reputation_serialize( + network_id=network_id, + address_id=address_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressReputation", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_address_reputation_serialize( + self, + network_id, + address_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if network_id is not None: + _path_params['network_id'] = network_id + if address_id is not None: + _path_params['address_id'] = address_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v1/networks/{network_id}/addresses/{address_id}/reputation', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_address_risk( + self, + network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the risk for.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> AddressRisk: + """Get the risk of an address + + Get the risk of an address + + :param network_id: The ID of the blockchain network. (required) + :type network_id: str + :param address_id: The ID of the address to fetch the risk for. (required) + :type address_id: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_address_risk_serialize( + network_id=network_id, + address_id=address_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressRisk", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_address_risk_with_http_info( + self, + network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the risk for.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[AddressRisk]: + """Get the risk of an address + + Get the risk of an address + + :param network_id: The ID of the blockchain network. (required) + :type network_id: str + :param address_id: The ID of the address to fetch the risk for. (required) + :type address_id: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_address_risk_serialize( + network_id=network_id, + address_id=address_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressRisk", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_address_risk_without_preload_content( + self, + network_id: Annotated[StrictStr, Field(description="The ID of the blockchain network.")], + address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the risk for.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get the risk of an address + + Get the risk of an address + + :param network_id: The ID of the blockchain network. (required) + :type network_id: str + :param address_id: The ID of the address to fetch the risk for. (required) + :type address_id: str + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_address_risk_serialize( + network_id=network_id, + address_id=address_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "AddressRisk", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_address_risk_serialize( + self, + network_id, + address_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if network_id is not None: + _path_params['network_id'] = network_id + if address_id is not None: + _path_params['address_id'] = address_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v1/networks/{network_id}/addresses/{address_id}/risk', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/cdp/client/models/__init__.py b/cdp/client/models/__init__.py index 188df88..db94dc4 100644 --- a/cdp/client/models/__init__.py +++ b/cdp/client/models/__init__.py @@ -18,6 +18,9 @@ from cdp.client.models.address_balance_list import AddressBalanceList from cdp.client.models.address_historical_balance_list import AddressHistoricalBalanceList from cdp.client.models.address_list import AddressList +from cdp.client.models.address_reputation import AddressReputation +from cdp.client.models.address_reputation_metadata import AddressReputationMetadata +from cdp.client.models.address_risk import AddressRisk from cdp.client.models.address_transaction_list import AddressTransactionList from cdp.client.models.asset import Asset from cdp.client.models.balance import Balance diff --git a/cdp/client/models/address_reputation.py b/cdp/client/models/address_reputation.py new file mode 100644 index 0000000..bbe381c --- /dev/null +++ b/cdp/client/models/address_reputation.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictInt +from typing import Any, ClassVar, Dict, List +from cdp.client.models.address_reputation_metadata import AddressReputationMetadata +from typing import Optional, Set +from typing_extensions import Self + +class AddressReputation(BaseModel): + """ + The reputation score with metadata of a blockchain address. + """ # noqa: E501 + reputation_score: StrictInt = Field(description="The reputation score of a wallet address which lie between 0 to 100.") + metadata: AddressReputationMetadata + __properties: ClassVar[List[str]] = ["reputation_score", "metadata"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of AddressReputation from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of AddressReputation from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "reputation_score": obj.get("reputation_score"), + "metadata": AddressReputationMetadata.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None + }) + return _obj + + diff --git a/cdp/client/models/address_reputation_metadata.py b/cdp/client/models/address_reputation_metadata.py new file mode 100644 index 0000000..950dbf8 --- /dev/null +++ b/cdp/client/models/address_reputation_metadata.py @@ -0,0 +1,105 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictInt +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class AddressReputationMetadata(BaseModel): + """ + The metadata for the reputation score of onchain address. + """ # noqa: E501 + total_transactions: StrictInt = Field(description="The total number of transactions performed by the address.") + unique_days_active: StrictInt = Field(description="The number of unique days the address was active.") + longest_active_streak: StrictInt = Field(description="The longest streak of consecutive active days.") + current_active_streak: StrictInt = Field(description="The current streak of consecutive active days.") + activity_period_days: StrictInt = Field(description="The total number of days the address has been active.") + token_swaps_performed: StrictInt = Field(description="The number of token swaps performed by the address.") + bridge_transactions_performed: StrictInt = Field(description="The number of bridge transactions performed by the address.") + lend_borrow_stake_transactions: StrictInt = Field(description="The number of lend, borrow, or stake transactions performed by the address.") + ens_contract_interactions: StrictInt = Field(description="The number of interactions with ENS contracts.") + smart_contract_deployments: StrictInt = Field(description="The number of smart contracts deployed by the address.") + __properties: ClassVar[List[str]] = ["total_transactions", "unique_days_active", "longest_active_streak", "current_active_streak", "activity_period_days", "token_swaps_performed", "bridge_transactions_performed", "lend_borrow_stake_transactions", "ens_contract_interactions", "smart_contract_deployments"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of AddressReputationMetadata from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of AddressReputationMetadata from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "total_transactions": obj.get("total_transactions"), + "unique_days_active": obj.get("unique_days_active"), + "longest_active_streak": obj.get("longest_active_streak"), + "current_active_streak": obj.get("current_active_streak"), + "activity_period_days": obj.get("activity_period_days"), + "token_swaps_performed": obj.get("token_swaps_performed"), + "bridge_transactions_performed": obj.get("bridge_transactions_performed"), + "lend_borrow_stake_transactions": obj.get("lend_borrow_stake_transactions"), + "ens_contract_interactions": obj.get("ens_contract_interactions"), + "smart_contract_deployments": obj.get("smart_contract_deployments") + }) + return _obj + + diff --git a/cdp/client/models/address_risk.py b/cdp/client/models/address_risk.py new file mode 100644 index 0000000..b2db6e0 --- /dev/null +++ b/cdp/client/models/address_risk.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictInt +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class AddressRisk(BaseModel): + """ + The risk score of a blockchain address. + """ # noqa: E501 + risk_score: StrictInt = Field(description="The lower the score is, the higher the risk is. The score lies between -100 to 0.") + __properties: ClassVar[List[str]] = ["risk_score"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of AddressRisk from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of AddressRisk from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "risk_score": obj.get("risk_score") + }) + return _obj + + diff --git a/cdp/crypto_amount.py b/cdp/crypto_amount.py new file mode 100644 index 0000000..63db82e --- /dev/null +++ b/cdp/crypto_amount.py @@ -0,0 +1,116 @@ +from decimal import Decimal + +from cdp.asset import Asset +from cdp.client.models.crypto_amount import CryptoAmount as CryptoAmountModel + + +class CryptoAmount: + """A representation of a CryptoAmount that includes the amount and asset.""" + + def __init__(self, amount: Decimal, asset: Asset, asset_id: str | None = None) -> None: + """Initialize a new CryptoAmount. Do not use this directly, use the from_model or from_model_and_asset_id methods instead. + + Args: + amount (Decimal): The amount of the Asset + asset (Asset): The Asset + asset_id (Optional[str]): The Asset ID + + """ + self._amount = amount + self._asset = asset + self._asset_id = asset_id or asset.asset_id + + @classmethod + def from_model(cls, crypto_amount_model: CryptoAmountModel) -> "CryptoAmount": + """Convert a CryptoAmount model to a CryptoAmount. + + Args: + crypto_amount_model (CryptoAmountModel): The crypto amount from the API. + + Returns: + CryptoAmount: The converted CryptoAmount object. + + """ + asset = Asset.from_model(crypto_amount_model.asset) + return cls(amount=asset.from_atomic_amount(crypto_amount_model.amount), asset=asset) + + @classmethod + def from_model_and_asset_id( + cls, crypto_amount_model: CryptoAmountModel, asset_id: str + ) -> "CryptoAmount": + """Convert a CryptoAmount model and asset ID to a CryptoAmount. + + This can be used to specify a non-primary denomination that we want the amount + to be converted to. + + Args: + crypto_amount_model (CryptoAmountModel): The crypto amount from the API. + asset_id (str): The Asset ID of the denomination we want returned. + + Returns: + CryptoAmount: The converted CryptoAmount object. + + """ + asset = Asset.from_model(crypto_amount_model.asset, asset_id=asset_id) + return cls( + amount=asset.from_atomic_amount(crypto_amount_model.amount), + asset=asset, + asset_id=asset_id, + ) + + @property + def amount(self) -> Decimal: + """Get the amount of the Asset. + + Returns: + Decimal: The amount of the Asset. + + """ + return self._amount + + @property + def asset(self) -> Asset: + """Get the Asset. + + Returns: + Asset: The Asset. + + """ + return self._asset + + @property + def asset_id(self) -> str: + """Get the Asset ID. + + Returns: + str: The Asset ID. + + """ + return self._asset_id + + def to_atomic_amount(self) -> Decimal: + """Convert the amount to atomic units. + + Returns: + Decimal: The amount in atomic units. + + """ + return self.asset.to_atomic_amount(self.amount) + + def __str__(self) -> str: + """Get a string representation of the CryptoAmount. + + Returns: + str: A string representation of the CryptoAmount. + + """ + return f"CryptoAmount(amount: '{int(self.amount)}', asset_id: '{self.asset_id}')" + + def __repr__(self) -> str: + """Get a string representation of the CryptoAmount. + + Returns: + str: A string representation of the CryptoAmount. + + """ + return self.__str__() diff --git a/cdp/fiat_amount.py b/cdp/fiat_amount.py new file mode 100644 index 0000000..7454c66 --- /dev/null +++ b/cdp/fiat_amount.py @@ -0,0 +1,69 @@ +from decimal import Decimal + +from cdp.client.models.fiat_amount import FiatAmount as FiatAmountModel + + +class FiatAmount: + """A representation of a FiatAmount that includes the amount and currency.""" + + def __init__(self, amount: Decimal, currency: str) -> None: + """Initialize a new FiatAmount. Do not use this directly, use the from_model method instead. + + Args: + amount (Decimal): The amount in the fiat currency + currency (str): The currency code (e.g. 'USD') + + """ + self._amount = amount + self._currency = currency + + @classmethod + def from_model(cls, fiat_amount_model: FiatAmountModel) -> "FiatAmount": + """Convert a FiatAmount model to a FiatAmount. + + Args: + fiat_amount_model (FiatAmountModel): The fiat amount from the API. + + Returns: + FiatAmount: The converted FiatAmount object. + + """ + return cls(amount=Decimal(fiat_amount_model.amount), currency=fiat_amount_model.currency) + + @property + def amount(self) -> Decimal: + """Get the amount in the fiat currency. + + Returns: + Decimal: The amount in the fiat currency. + + """ + return self._amount + + @property + def currency(self) -> str: + """Get the currency code. + + Returns: + str: The currency code. + + """ + return self._currency + + def __str__(self) -> str: + """Get a string representation of the FiatAmount. + + Returns: + str: A string representation of the FiatAmount. + + """ + return f"FiatAmount(amount: '{int(self.amount)}', currency: '{self.currency}')" + + def __repr__(self) -> str: + """Get a string representation of the FiatAmount. + + Returns: + str: A string representation of the FiatAmount. + + """ + return self.__str__() diff --git a/cdp/fund_operation.py b/cdp/fund_operation.py new file mode 100644 index 0000000..54e61e7 --- /dev/null +++ b/cdp/fund_operation.py @@ -0,0 +1,247 @@ +import time +from collections.abc import Iterator +from decimal import Decimal +from enum import Enum + +from cdp.asset import Asset +from cdp.cdp import Cdp +from cdp.client.models import FundOperation as FundOperationModel +from cdp.crypto_amount import CryptoAmount +from cdp.fiat_amount import FiatAmount +from cdp.fund_quote import FundQuote + + +class FundOperation: + """A representation of a Fund Operation.""" + + class Status(Enum): + """Fund Operation status constants.""" + + PENDING = "pending" + COMPLETE = "complete" + FAILED = "failed" + + @classmethod + def terminal_states(cls): + """Get the terminal states. + + Returns: + List[Status]: The terminal states. + + """ + return [cls.COMPLETE, cls.FAILED] + + def __str__(self) -> str: + """Return a string representation of the Status.""" + return self.value + + def __repr__(self) -> str: + """Return a string representation of the Status.""" + return str(self) + + def __init__(self, model: FundOperationModel) -> None: + """Initialize the FundOperation class. + + Args: + model (FundOperationModel): The model representing the fund operation. + + """ + self._model = model + self._network = None + self._asset = None + + @classmethod + def create( + cls, + wallet_id: str, + address_id: str, + amount: Decimal, + asset_id: str, + network_id: str, + quote: FundQuote | None = None, + ) -> "FundOperation": + """Create a new Fund Operation. + + Args: + wallet_id (str): The Wallet ID + address_id (str): The Address ID + amount (Decimal): The amount of the Asset + asset_id (str): The Asset ID + network_id (str): The Network ID + quote (Optional[FundQuote]): The optional Fund Quote + + Returns: + FundOperation: The new FundOperation object + + """ + asset = Asset.fetch(network_id, asset_id) + + create_request = { + "amount": str(int(asset.to_atomic_amount(amount))), + "asset_id": Asset.primary_denomination(asset.asset_id), + } + + if quote: + create_request["fund_quote_id"] = quote.id + + model = Cdp.api_clients.fund.create_fund_operation( + wallet_id=wallet_id, + address_id=address_id, + create_fund_operation_request=create_request, + ) + + return cls(model) + + @classmethod + def list(cls, wallet_id: str, address_id: str) -> Iterator["FundOperation"]: + """List fund operations. + + Args: + wallet_id (str): The wallet ID + address_id (str): The address ID + + Returns: + Iterator[FundOperation]: An iterator of fund operation objects + + """ + page = None + while True: + response = Cdp.api_clients.fund.list_fund_operations( + wallet_id=wallet_id, + address_id=address_id, + limit=100, + page=page, + ) + + for operation_model in response.data: + yield cls(operation_model) + + if not response.has_more: + break + + page = response.next_page + + @property + def id(self) -> str: + """Get the Fund Operation ID.""" + return self._model.fund_operation_id + + @property + def network_id(self) -> str: + """Get the Network ID.""" + return self._model.network_id + + @property + def wallet_id(self) -> str: + """Get the Wallet ID.""" + return self._model.wallet_id + + @property + def address_id(self) -> str: + """Get the Address ID.""" + return self._model.address_id + + @property + def asset(self) -> Asset: + """Get the Asset.""" + if self._asset is None: + self._asset = Asset.from_model(self._model.crypto_amount.asset) + return self._asset + + @property + def amount(self) -> CryptoAmount: + """Get the crypto amount.""" + return CryptoAmount.from_model(self._model.crypto_amount) + + @property + def fiat_amount(self) -> FiatAmount: + """Get the fiat amount.""" + return FiatAmount.from_model(self._model.fiat_amount) + + @property + def fiat_currency(self) -> str: + """Get the fiat currency.""" + return self._model.fiat_amount.currency + + @property + def buy_fee(self) -> dict: + """Get the buy fee. + + Returns: + dict: The buy fee information. + + """ + return { + "amount": self._model.fees.buy_fee.amount, + "currency": self._model.fees.buy_fee.currency, + } + + @property + def transfer_fee(self) -> CryptoAmount: + """Get the transfer fee. + + Returns: + CryptoAmount: The transfer fee. + + """ + return CryptoAmount.from_model(self._model.fees.transfer_fee) + + @property + def status(self) -> Status: + """Get the status.""" + return self.Status(self._model.status) + + def reload(self) -> "FundOperation": + """Reload the fund operation from the server. + + Returns: + FundOperation: The updated fund operation. + + """ + self._model = Cdp.api_clients.fund.get_fund_operation( + self.wallet_id, self.address_id, self.id + ) + return self + + def wait(self, interval_seconds: float = 0.2, timeout_seconds: float = 20) -> "FundOperation": + """Wait for the fund operation to complete. + + Args: + interval_seconds (float): The interval between checks + timeout_seconds (float): The maximum time to wait + + Returns: + FundOperation: The completed fund operation + + Raises: + TimeoutError: If the operation takes too long + + """ + start_time = time.time() + + while not self.terminal_state(): + self.reload() + + if time.time() - start_time > timeout_seconds: + raise TimeoutError("Fund operation timed out") + + time.sleep(interval_seconds) + + return self + + def terminal_state(self) -> bool: + """Check if the operation is in a terminal state.""" + return self.status in self.Status.terminal_states() + + def __str__(self) -> str: + """Get a string representation of the Fund Operation.""" + return ( + f"FundOperation(id: {self.id}, network_id: {self.network_id}, " + f"wallet_id: {self.wallet_id}, address_id: {self.address_id}, " + f"amount: {self.amount}, asset_id: {self.asset.asset_id}, " + f"status: {self.status.value})" + ) + + def __repr__(self) -> str: + """Get a string representation of the Fund Operation.""" + return self.__str__() diff --git a/cdp/fund_quote.py b/cdp/fund_quote.py new file mode 100644 index 0000000..36e318e --- /dev/null +++ b/cdp/fund_quote.py @@ -0,0 +1,199 @@ +from decimal import Decimal +from typing import TYPE_CHECKING + +from cdp.asset import Asset +from cdp.cdp import Cdp +from cdp.crypto_amount import CryptoAmount +from cdp.fiat_amount import FiatAmount + +if TYPE_CHECKING: + from cdp.fund_operation import FundOperation + +from cdp.client.models import FundQuote as FundQuoteModel + + +class FundQuote: + """A representation of a Fund Operation Quote.""" + + def __init__(self, model: FundQuoteModel) -> None: + """Initialize the FundQuote class. + + Args: + model (FundQuoteModel): The model representing the fund quote. + + """ + self._model = model + self._network = None + self._asset = None + + @classmethod + def create( + cls, + wallet_id: str, + address_id: str, + amount: Decimal, + asset_id: str, + network_id: str, + ) -> "FundQuote": + """Create a new Fund Operation Quote. + + Args: + wallet_id (str): The Wallet ID + address_id (str): The Address ID + amount (Decimal): The amount of the Asset + asset_id (str): The Asset ID + network_id (str): The Network ID + + Returns: + FundQuote: The new FundQuote object + + """ + asset = Asset.fetch(network_id, asset_id) + + model = Cdp.api_clients.fund.create_fund_quote( + wallet_id=wallet_id, + address_id=address_id, + create_fund_quote_request={ + "asset_id": Asset.primary_denomination(asset.asset_id), + "amount": str(int(asset.to_atomic_amount(amount))), + }, + ) + + return cls(model) + + @property + def id(self) -> str: + """Get the Fund Quote ID. + + Returns: + str: The Fund Quote ID. + + """ + return self._model.fund_quote_id + + @property + def network_id(self) -> str: + """Get the Network ID. + + Returns: + str: The Network ID. + + """ + return self._model.network_id + + @property + def wallet_id(self) -> str: + """Get the Wallet ID. + + Returns: + str: The Wallet ID. + + """ + return self._model.wallet_id + + @property + def address_id(self) -> str: + """Get the Address ID. + + Returns: + str: The Address ID. + + """ + return self._model.address_id + + @property + def asset(self) -> Asset: + """Get the Asset. + + Returns: + Asset: The Asset. + + """ + if self._asset is None: + self._asset = Asset.from_model(self._model.crypto_amount.asset) + return self._asset + + @property + def amount(self) -> CryptoAmount: + """Get the crypto amount. + + Returns: + CryptoAmount: The crypto amount. + + """ + return CryptoAmount.from_model(self._model.crypto_amount) + + @property + def fiat_amount(self) -> FiatAmount: + """Get the fiat amount. + + Returns: + Decimal: The fiat amount. + + """ + return FiatAmount.from_model(self._model.fiat_amount) + + @property + def fiat_currency(self) -> str: + """Get the fiat currency. + + Returns: + str: The fiat currency. + + """ + return self._model.fiat_amount.currency + + @property + def buy_fee(self) -> dict: + """Get the buy fee. + + Returns: + dict: The buy fee information. + + """ + return { + "amount": self._model.fees.buy_fee.amount, + "currency": self._model.fees.buy_fee.currency, + } + + @property + def transfer_fee(self) -> CryptoAmount: + """Get the transfer fee. + + Returns: + CryptoAmount: The transfer fee. + + """ + return CryptoAmount.from_model(self._model.fees.transfer_fee) + + def execute(self) -> "FundOperation": + """Execute the fund quote to create a fund operation. + + Returns: + FundOperation: The created fund operation. + + """ + from cdp.fund_operation import FundOperation + + return FundOperation.create( + wallet_id=self.wallet_id, + address_id=self.address_id, + amount=self.amount.amount, + asset_id=self.asset.asset_id, + network_id=self.network_id, + quote=self, + ) + + def __str__(self) -> str: + """Get a string representation of the Fund Quote.""" + return ( + f"FundQuote(network_id: {self.network_id}, wallet_id: {self.wallet_id}, " + f"address_id: {self.address_id}, crypto_amount: {self.amount.amount}, " + f"crypto_asset: {self.asset.asset_id}, fiat_amount: {self.fiat_amount.amount}, " + f"fiat_currency: {self.fiat_currency}, buy_fee: {{'amount': '{self.buy_fee['amount']}'}}, " + f"transfer_fee: {{'amount': '{self.transfer_fee.amount}'}})" + ) + + def __repr__(self) -> str: + """Get a string representation of the Fund Quote.""" + return self.__str__() diff --git a/cdp/wallet.py b/cdp/wallet.py index a35a22e..46958e0 100644 --- a/cdp/wallet.py +++ b/cdp/wallet.py @@ -29,6 +29,8 @@ from cdp.client.models.wallet_list import WalletList from cdp.contract_invocation import ContractInvocation from cdp.faucet_transaction import FaucetTransaction +from cdp.fund_operation import FundOperation +from cdp.fund_quote import FundQuote from cdp.payload_signature import PayloadSignature from cdp.smart_contract import SmartContract from cdp.trade import Trade @@ -801,3 +803,41 @@ def deploy_multi_token(self, uri: str) -> SmartContract: raise ValueError("Default address does not exist") return self.default_address.deploy_multi_token(uri) + + def fund(self, amount: Number | Decimal | str, asset_id: str) -> FundOperation: + """Fund the wallet from your account on the Coinbase Platform. + + Args: + amount (Union[Number, Decimal, str]): The amount of the Asset to fund the wallet with. + asset_id (str): The ID of the Asset to fund with. For Ether, 'eth', 'gwei', and 'wei' are supported. + + Returns: + FundOperation: The created fund operation object. + + Raises: + ValueError: If the default address does not exist. + + """ + if self.default_address is None: + raise ValueError("Default address does not exist") + + return self.default_address.fund(amount, asset_id) + + def quote_fund(self, amount: Number | Decimal | str, asset_id: str) -> FundQuote: + """Get a quote for funding the wallet from your Coinbase platform account. + + Args: + amount (Union[Number, Decimal, str]): The amount to fund. + asset_id (str): The ID of the Asset to fund with. For Ether, 'eth', 'gwei', and 'wei' are supported. + + Returns: + FundQuote: The fund quote object. + + Raises: + ValueError: If the default address does not exist. + + """ + if self.default_address is None: + raise ValueError("Default address does not exist") + + return self.default_address.quote_fund(amount, asset_id) diff --git a/cdp/wallet_address.py b/cdp/wallet_address.py index 19bfb83..e8d801d 100644 --- a/cdp/wallet_address.py +++ b/cdp/wallet_address.py @@ -11,6 +11,8 @@ from cdp.client.models.address import Address as AddressModel from cdp.contract_invocation import ContractInvocation from cdp.errors import InsufficientFundsError +from cdp.fund_operation import FundOperation +from cdp.fund_quote import FundQuote from cdp.payload_signature import PayloadSignature from cdp.smart_contract import SmartContract from cdp.trade import Trade @@ -323,6 +325,48 @@ def trades(self) -> Iterator[Trade]: """ return Trade.list(wallet_id=self.wallet_id, address_id=self.address_id) + def fund(self, amount: Number | Decimal | str, asset_id: str) -> FundOperation: + """Fund the address from your account on the Coinbase Platform. + + Args: + amount (Union[Number, Decimal, str]): The amount of the Asset to fund the wallet with. + asset_id (str): The ID of the Asset to fund with. For Ether, 'eth', 'gwei', and 'wei' are supported. + + Returns: + FundOperation: The created fund operation object. + + """ + normalized_amount = Decimal(amount) + + return FundOperation.create( + address_id=self.address_id, + amount=normalized_amount, + asset_id=asset_id, + network_id=self.network_id, + wallet_id=self.wallet_id, + ) + + def quote_fund(self, amount: Number | Decimal | str, asset_id: str) -> FundQuote: + """Get a quote for funding the address from your Coinbase platform account. + + Args: + amount (Union[Number, Decimal, str]): The amount to fund. + asset_id (str): The ID of the Asset to fund with. For Ether, 'eth', 'gwei', and 'wei' are supported. + + Returns: + FundQuote: The fund quote object. + + """ + normalized_amount = Decimal(amount) + + return FundQuote.create( + address_id=self.address_id, + amount=str(normalized_amount), + asset_id=asset_id, + network_id=self.network_id, + wallet_id=self.wallet_id, + ) + def _ensure_sufficient_balance(self, amount: Decimal, asset_id: str) -> None: """Ensure the wallet address has sufficient balance. diff --git a/tests/factories/crypto_amount_factory.py b/tests/factories/crypto_amount_factory.py new file mode 100644 index 0000000..cad725a --- /dev/null +++ b/tests/factories/crypto_amount_factory.py @@ -0,0 +1,28 @@ +from decimal import Decimal + +import pytest + +from cdp.client.models.crypto_amount import CryptoAmount as CryptoAmountModel +from cdp.crypto_amount import CryptoAmount + + +@pytest.fixture +def crypto_amount_model_factory(asset_model_factory): + """Create and return a factory for creating CryptoAmountModel fixtures.""" + + def _create_crypto_amount_model(asset_id="USDC", decimals=6, amount="1"): + asset_model = asset_model_factory("base-sepolia", asset_id, decimals) + return CryptoAmountModel(amount=amount, asset=asset_model) + + return _create_crypto_amount_model + + +@pytest.fixture +def crypto_amount_factory(asset_factory): + """Create and return a factory for creating CryptoAmount fixtures.""" + + def _create_crypto_amount(asset_id="USDC", decimals=6, amount="1"): + asset = asset_factory("base-sepolia", asset_id, decimals) + return CryptoAmount(Decimal(amount), asset) + + return _create_crypto_amount diff --git a/tests/factories/fund_operation_factory.py b/tests/factories/fund_operation_factory.py new file mode 100644 index 0000000..784368f --- /dev/null +++ b/tests/factories/fund_operation_factory.py @@ -0,0 +1,51 @@ +import pytest + +from cdp.client.models.fiat_amount import FiatAmount +from cdp.client.models.fund_operation import FundOperation as FundOperationModel +from cdp.client.models.fund_operation_fees import FundOperationFees +from cdp.fund_operation import FundOperation + + +@pytest.fixture +def fund_operation_model_factory( + crypto_amount_model_factory, transaction_model_factory, fund_quote_model_factory +): + """Create and return a factory for creating FundOperationModel fixtures.""" + + def _create_fund_operation_model( + status="complete", asset_id="eth", amount="2000000000000000000", decimals=18 + ): + crypto_amount_model = crypto_amount_model_factory(asset_id, decimals, amount) + transfer_fee_crypto_amount_model = crypto_amount_model_factory( + asset_id, 18, "10000000000000000" + ) # 0.01 ETH + return FundOperationModel( + fund_operation_id="test-operation-id", + network_id="base-sepolia", + wallet_id="test-wallet-id", + address_id="test-address-id", + crypto_amount=crypto_amount_model, + fiat_amount=FiatAmount(amount="100", currency="USD"), + fees=FundOperationFees( + buy_fee=FiatAmount(amount="1", currency="USD"), + transfer_fee=transfer_fee_crypto_amount_model, + ), + status=status, + ) + + return _create_fund_operation_model + + +@pytest.fixture +def fund_operation_factory(fund_operation_model_factory): + """Create and return a factory for creating FundOperation fixtures.""" + + def _create_fund_operation( + status="complete", asset_id="eth", amount="2000000000000000000", decimals=18 + ): + fund_operation_model = fund_operation_model_factory( + status=status, asset_id=asset_id, amount=amount, decimals=decimals + ) + return FundOperation(fund_operation_model) + + return _create_fund_operation diff --git a/tests/factories/fund_quote_factory.py b/tests/factories/fund_quote_factory.py new file mode 100644 index 0000000..849da6f --- /dev/null +++ b/tests/factories/fund_quote_factory.py @@ -0,0 +1,45 @@ +import pytest + +from cdp.client.models.fiat_amount import FiatAmount +from cdp.client.models.fund_operation_fees import FundOperationFees +from cdp.client.models.fund_quote import FundQuote as FundQuoteModel +from cdp.fund_quote import FundQuote + + +@pytest.fixture +def fund_quote_model_factory(crypto_amount_model_factory): + """Create and return a factory for creating FundQuoteModel fixtures.""" + + def _create_fund_quote_model(amount="2000000000000000000", decimals=18, asset_id="eth"): + crypto_amount_model = crypto_amount_model_factory(asset_id, decimals, amount) + transfer_fee_crypto_amount_model = crypto_amount_model_factory( + asset_id, 18, "10000000000000000" + ) # 0.01 ETH + return FundQuoteModel( + fund_quote_id="test-quote-id", + network_id="base-sepolia", + wallet_id="test-wallet-id", + address_id="test-address-id", + crypto_amount=crypto_amount_model, + fiat_amount=FiatAmount(amount="100", currency="USD"), + expires_at="2024-12-31T23:59:59Z", + fees=FundOperationFees( + buy_fee=FiatAmount(amount="1", currency="USD"), + transfer_fee=transfer_fee_crypto_amount_model, + ), + ) + + return _create_fund_quote_model + + +@pytest.fixture +def fund_quote_factory(fund_quote_model_factory): + """Create and return a factory for creating FundQuote fixtures.""" + + def _create_fund_quote(amount="2000000000000000000", decimals=18, asset_id="eth"): + fund_quote_model = fund_quote_model_factory( + amount=amount, decimals=decimals, asset_id=asset_id + ) + return FundQuote(fund_quote_model) + + return _create_fund_quote diff --git a/tests/test_crypto_amount.py b/tests/test_crypto_amount.py new file mode 100644 index 0000000..ebccd95 --- /dev/null +++ b/tests/test_crypto_amount.py @@ -0,0 +1,74 @@ +from decimal import Decimal + +from cdp.crypto_amount import CryptoAmount + + +def test_crypto_amount_initialization(crypto_amount_factory): + """Test crypto amount initialization.""" + crypto_amount = crypto_amount_factory("USDC", 6, "1") + assert isinstance(crypto_amount, CryptoAmount) + assert crypto_amount.amount == Decimal("1") + assert crypto_amount.asset.asset_id == "USDC" + assert crypto_amount.asset.network_id == "base-sepolia" + assert crypto_amount.asset.decimals == 6 + + +def test_crypto_amount_from_model(crypto_amount_model_factory): + """Test crypto amount from model.""" + crypto_amount_model = crypto_amount_model_factory("USDC", 6, "1") + crypto_amount = CryptoAmount.from_model(crypto_amount_model) + assert isinstance(crypto_amount, CryptoAmount) + assert crypto_amount.amount == ( + Decimal(crypto_amount_model.amount) / Decimal(10) ** crypto_amount_model.asset.decimals + ) + assert crypto_amount.asset.asset_id == "USDC" + assert crypto_amount.asset.network_id == "base-sepolia" + assert crypto_amount.asset.decimals == 6 + + +def test_crypto_amount_from_model_and_asset_id_with_gwei(crypto_amount_model_factory): + """Test crypto amount from model with gwei.""" + crypto_amount_model = crypto_amount_model_factory("eth", 18, "1") + crypto_amount = CryptoAmount.from_model_and_asset_id(crypto_amount_model, "gwei") + assert isinstance(crypto_amount, CryptoAmount) + assert crypto_amount.amount == (Decimal(crypto_amount_model.amount) / Decimal(10) ** 9) + assert crypto_amount.asset.asset_id == "gwei" + assert crypto_amount.asset.network_id == "base-sepolia" + assert crypto_amount.asset.decimals == 9 + + +def test_crypto_amount_from_model_and_asset_id_with_wei(crypto_amount_model_factory): + """Test crypto amount from model with wei.""" + crypto_amount_model = crypto_amount_model_factory("eth", 18, "1") + crypto_amount = CryptoAmount.from_model_and_asset_id(crypto_amount_model, "wei") + assert isinstance(crypto_amount, CryptoAmount) + assert crypto_amount.amount == Decimal(crypto_amount_model.amount) + assert crypto_amount.asset.asset_id == "wei" + assert crypto_amount.asset.network_id == "base-sepolia" + assert crypto_amount.asset.decimals == 0 + + +def test_crypto_amount_to_atomic_amount(crypto_amount_factory): + """Test crypto amount to atomic amount.""" + crypto_amount = crypto_amount_factory() + assert crypto_amount.to_atomic_amount() == ( + Decimal(crypto_amount.amount) * Decimal(10) ** crypto_amount.asset.decimals + ) + + +def test_crypto_amount_str_representation(crypto_amount_factory): + """Test crypto amount string representation.""" + crypto_amount = crypto_amount_factory() + assert ( + str(crypto_amount) + == f"CryptoAmount(amount: '{int(crypto_amount.amount)}', asset_id: '{crypto_amount.asset.asset_id}')" + ) + + +def test_crypto_amount_repr(crypto_amount_factory): + """Test crypto amount repr.""" + crypto_amount = crypto_amount_factory() + assert ( + repr(crypto_amount) + == f"CryptoAmount(amount: '{int(crypto_amount.amount)}', asset_id: '{crypto_amount.asset.asset_id}')" + ) diff --git a/tests/test_fiat_amount.py b/tests/test_fiat_amount.py new file mode 100644 index 0000000..ff802b9 --- /dev/null +++ b/tests/test_fiat_amount.py @@ -0,0 +1,36 @@ +from decimal import Decimal + +from cdp.client.models.fiat_amount import FiatAmount as FiatAmountModel +from cdp.fiat_amount import FiatAmount + + +def test_fiat_amount_from_model(): + """Test converting a FiatAmount model to a FiatAmount.""" + model = FiatAmountModel(amount="100.50", currency="USD") + fiat_amount = FiatAmount.from_model(model) + + assert fiat_amount.amount == Decimal("100.50") + assert fiat_amount.currency == "USD" + + +def test_fiat_amount_properties(): + """Test FiatAmount properties.""" + fiat_amount = FiatAmount(amount=Decimal("50.25"), currency="USD") + + assert fiat_amount.amount == Decimal("50.25") + assert fiat_amount.currency == "USD" + + +def test_fiat_amount_str_representation(): + """Test string representation of FiatAmount.""" + fiat_amount = FiatAmount(amount=Decimal("75.00"), currency="USD") + expected_str = "FiatAmount(amount: '75', currency: 'USD')" + + assert str(fiat_amount) == expected_str + assert repr(fiat_amount) == expected_str + + +def test_fiat_amount_repr(): + """Test repr of FiatAmount.""" + fiat_amount = FiatAmount(amount=Decimal("75.00"), currency="USD") + assert repr(fiat_amount) == "FiatAmount(amount: '75', currency: 'USD')" diff --git a/tests/test_fund_operation.py b/tests/test_fund_operation.py new file mode 100644 index 0000000..e3b7e53 --- /dev/null +++ b/tests/test_fund_operation.py @@ -0,0 +1,206 @@ +from decimal import Decimal +from unittest.mock import Mock, call, patch + +import pytest + +from cdp.asset import Asset +from cdp.fund_operation import FundOperation + + +def test_fund_operation_initialization(fund_operation_factory): + """Test the initialization of a FundOperation object.""" + fund_operation = fund_operation_factory() + assert isinstance(fund_operation, FundOperation) + + +def test_fund_operation_properties(fund_operation_factory): + """Test the properties of a FundOperation object.""" + fund_operation = fund_operation_factory() + assert fund_operation.amount.amount == Decimal("2") + assert fund_operation.fiat_amount.amount == Decimal("100") + assert fund_operation.buy_fee["amount"] == "1" + assert fund_operation.transfer_fee.amount == Decimal("0.01") + assert fund_operation.status.value == "complete" + assert isinstance(fund_operation.asset, Asset) + + +@patch("cdp.Cdp.api_clients") +@patch("cdp.fund_operation.Asset") +def test_fund_operation_create(mock_asset, mock_api_clients, asset_factory, fund_operation_factory): + """Test the creation of a FundOperation object without a quote.""" + mock_fetch = Mock() + mock_fetch.return_value = asset_factory(asset_id="eth", decimals=18) + mock_asset.fetch = mock_fetch + + mock_primary_denomination = Mock() + mock_primary_denomination.return_value = "eth" + mock_asset.primary_denomination = mock_primary_denomination + + mock_create_fund_operation = Mock() + mock_create_fund_operation.return_value = fund_operation_factory()._model + mock_api_clients.fund.create_fund_operation = mock_create_fund_operation + + fund_operation = FundOperation.create( + wallet_id="test-wallet-id", + address_id="test-address-id", + amount=Decimal("2"), + asset_id="eth", + network_id="base-sepolia", + ) + assert isinstance(fund_operation, FundOperation) + mock_fetch.assert_called_once_with("base-sepolia", "eth") + mock_primary_denomination.assert_called_once_with("eth") + mock_create_fund_operation.assert_called_once_with( + wallet_id="test-wallet-id", + address_id="test-address-id", + create_fund_operation_request={ + "amount": "2000000000000000000", + "asset_id": "eth", + }, + ) + + +@patch("cdp.Cdp.api_clients") +@patch("cdp.fund_operation.Asset") +def test_fund_operation_create_with_quote( + mock_asset, mock_api_clients, asset_factory, fund_operation_factory, fund_quote_factory +): + """Test the creation of a FundOperation object with a quote.""" + mock_fetch = Mock() + mock_fetch.return_value = asset_factory(asset_id="eth", decimals=18) + mock_asset.fetch = mock_fetch + + mock_primary_denomination = Mock() + mock_primary_denomination.return_value = "eth" + mock_asset.primary_denomination = mock_primary_denomination + + mock_create_fund_operation = Mock() + mock_create_fund_operation.return_value = fund_operation_factory()._model + mock_api_clients.fund.create_fund_operation = mock_create_fund_operation + + fund_operation = FundOperation.create( + wallet_id="test-wallet-id", + address_id="test-address-id", + amount=Decimal("2"), + asset_id="eth", + network_id="base-sepolia", + quote=fund_quote_factory(), + ) + assert isinstance(fund_operation, FundOperation) + mock_fetch.assert_called_once_with("base-sepolia", "eth") + mock_primary_denomination.assert_called_once_with("eth") + mock_create_fund_operation.assert_called_once_with( + wallet_id="test-wallet-id", + address_id="test-address-id", + create_fund_operation_request={ + "amount": "2000000000000000000", + "asset_id": "eth", + "fund_quote_id": "test-quote-id", + }, + ) + + +@patch("cdp.Cdp.api_clients") +def test_list_fund_operations(mock_api_clients, fund_operation_factory): + """Test the listing of fund operations.""" + mock_list_fund_operations = Mock() + mock_list_fund_operations.return_value = Mock( + data=[fund_operation_factory()._model], has_more=False + ) + mock_api_clients.fund.list_fund_operations = mock_list_fund_operations + fund_operations = FundOperation.list("test-wallet-id", "0xaddressid") + assert len(list(fund_operations)) == 1 + assert all(isinstance(f, FundOperation) for f in fund_operations) + mock_list_fund_operations.assert_called_once_with( + wallet_id="test-wallet-id", address_id="0xaddressid", limit=100, page=None + ) + + +@patch("cdp.Cdp.api_clients") +def test_fund_operation_reload(mock_api_clients, fund_operation_factory): + """Test the reloading of a FundOperation object.""" + mock_reload_fund_operation = Mock() + mock_reload_fund_operation.return_value = fund_operation_factory()._model + mock_api_clients.fund.get_fund_operation = mock_reload_fund_operation + + fund_operation = fund_operation_factory() + fund_operation.reload() + mock_reload_fund_operation.assert_called_once_with( + fund_operation.wallet_id, fund_operation.address_id, fund_operation.id + ) + assert fund_operation.status.value == "complete" + + +@patch("cdp.Cdp.api_clients") +@patch("cdp.fund_operation.time.sleep") +@patch("cdp.fund_operation.time.time") +def test_fund_operation_wait(mock_time, mock_sleep, mock_api_clients, fund_operation_factory): + """Test the waiting for a FundOperation object to complete.""" + pending_fund_operation = fund_operation_factory(status="pending") + complete_fund_operation = fund_operation_factory(status="complete") + mock_get_fund_operation = Mock() + mock_api_clients.fund.get_fund_operation = mock_get_fund_operation + mock_get_fund_operation.side_effect = [ + pending_fund_operation._model, + complete_fund_operation._model, + ] + + mock_time.side_effect = [0, 0.2, 0.4] + + result = pending_fund_operation.wait(interval_seconds=0.2, timeout_seconds=1) + + assert result.status.value == "complete" + mock_get_fund_operation.assert_called_with( + pending_fund_operation.wallet_id, + pending_fund_operation.address_id, + pending_fund_operation.id, + ) + assert mock_get_fund_operation.call_count == 2 + mock_sleep.assert_has_calls([call(0.2)] * 2) + assert mock_time.call_count == 3 + + +@patch("cdp.Cdp.api_clients") +@patch("cdp.fund_operation.time.sleep") +@patch("cdp.fund_operation.time.time") +def test_wait_for_fund_operation_timeout( + mock_time, mock_sleep, mock_api_clients, fund_operation_factory +): + """Test the waiting for a FundOperation object to complete with a timeout.""" + pending_fund_operation = fund_operation_factory(status="pending") + mock_get_fund_operation = Mock(return_value=pending_fund_operation._model) + mock_api_clients.fund.get_fund_operation = mock_get_fund_operation + + mock_time.side_effect = [0, 0.5, 1.0, 1.5, 2.0, 2.5] + + with pytest.raises(TimeoutError, match="Fund operation timed out"): + pending_fund_operation.wait(interval_seconds=0.5, timeout_seconds=2) + + mock_get_fund_operation.assert_called_with( + pending_fund_operation.wallet_id, + pending_fund_operation.address_id, + pending_fund_operation.id, + ) + assert mock_get_fund_operation.call_count == 5 + mock_sleep.assert_has_calls([call(0.5)] * 4) + assert mock_time.call_count == 6 + + +@pytest.mark.parametrize("status", ["pending", "complete", "failed"]) +def test_fund_operation_str_representation(fund_operation_factory, status): + """Test the string representation of a FundOperation object.""" + fund_operation = fund_operation_factory(status=status) + expected_str = ( + f"FundOperation(id: {fund_operation.id}, network_id: {fund_operation.network_id}, " + f"wallet_id: {fund_operation.wallet_id}, address_id: {fund_operation.address_id}, " + f"amount: {fund_operation.amount}, asset_id: {fund_operation.asset.asset_id}, " + f"status: {fund_operation.status.value})" + ) + assert str(fund_operation) == expected_str + + +@pytest.mark.parametrize("status", ["pending", "complete", "failed"]) +def test_fund_operation_repr(fund_operation_factory, status): + """Test the representation of a FundOperation object.""" + fund_operation = fund_operation_factory(status=status) + assert repr(fund_operation) == str(fund_operation) diff --git a/tests/test_fund_quote.py b/tests/test_fund_quote.py new file mode 100644 index 0000000..23084ab --- /dev/null +++ b/tests/test_fund_quote.py @@ -0,0 +1,93 @@ +from decimal import Decimal +from unittest.mock import Mock, patch + +from cdp.asset import Asset +from cdp.fund_quote import FundQuote + + +def test_fund_quote_initialization(fund_quote_factory): + """Test the initialization of a FundQuote object.""" + fund_quote = fund_quote_factory() + assert isinstance(fund_quote, FundQuote) + + +def test_fund_quote_properties(fund_quote_factory): + """Test the properties of a FundQuote object.""" + fund_quote = fund_quote_factory() + assert fund_quote.amount.amount == Decimal("2") + assert fund_quote.fiat_amount.amount == Decimal("100") + assert fund_quote.buy_fee["amount"] == "1" + assert fund_quote.transfer_fee.amount == Decimal("0.01") + assert isinstance(fund_quote.asset, Asset) + + +@patch("cdp.Cdp.api_clients") +@patch("cdp.fund_quote.Asset") +def test_fund_quote_create(mock_asset, mock_api_clients, asset_factory, fund_quote_factory): + """Test the creation of a FundQuote object.""" + mock_fetch = Mock() + mock_fetch.return_value = asset_factory(asset_id="eth", decimals=18) + mock_asset.fetch = mock_fetch + + mock_primary_denomination = Mock() + mock_primary_denomination.return_value = "eth" + mock_asset.primary_denomination = mock_primary_denomination + + mock_create_fund_quote = Mock() + mock_create_fund_quote.return_value = fund_quote_factory()._model + mock_api_clients.fund.create_fund_quote = mock_create_fund_quote + + fund_quote = FundQuote.create( + wallet_id="test-wallet-id", + address_id="test-address-id", + amount=Decimal("2"), + asset_id="eth", + network_id="base-sepolia", + ) + assert isinstance(fund_quote, FundQuote) + mock_fetch.assert_called_once_with("base-sepolia", "eth") + mock_primary_denomination.assert_called_once_with("eth") + mock_create_fund_quote.assert_called_once_with( + wallet_id="test-wallet-id", + address_id="test-address-id", + create_fund_quote_request={ + "asset_id": "eth", + "amount": "2000000000000000000", + }, + ) + + +@patch("cdp.fund_operation.FundOperation") +def test_fund_quote_execute(mock_fund_operation, fund_quote_factory): + """Test the execution of a FundQuote object.""" + mock_create = Mock() + mock_fund_operation.create = mock_create + + fund_quote = fund_quote_factory() + fund_quote.execute() + mock_create.assert_called_once_with( + wallet_id=fund_quote.wallet_id, + address_id=fund_quote.address_id, + amount=fund_quote.amount.amount, + asset_id=fund_quote.asset.asset_id, + network_id=fund_quote.network_id, + quote=fund_quote, + ) + + +def test_fund_quote_str(fund_quote_factory): + """Test the string representation of a FundQuote object.""" + fund_quote = fund_quote_factory() + assert ( + str(fund_quote) + == "FundQuote(network_id: base-sepolia, wallet_id: test-wallet-id, address_id: test-address-id, crypto_amount: 2, crypto_asset: eth, fiat_amount: 100, fiat_currency: USD, buy_fee: {'amount': '1'}, transfer_fee: {'amount': '0.01'})" + ) + + +def test_fund_quote_repr(fund_quote_factory): + """Test the string representation of a FundQuote object.""" + fund_quote = fund_quote_factory() + assert ( + repr(fund_quote) + == "FundQuote(network_id: base-sepolia, wallet_id: test-wallet-id, address_id: test-address-id, crypto_amount: 2, crypto_asset: eth, fiat_amount: 100, fiat_currency: USD, buy_fee: {'amount': '1'}, transfer_fee: {'amount': '0.01'})" + ) diff --git a/tests/test_wallet.py b/tests/test_wallet.py index 292397a..751d56b 100644 --- a/tests/test_wallet.py +++ b/tests/test_wallet.py @@ -2,13 +2,14 @@ from unittest.mock import ANY, Mock, PropertyMock, call, patch import pytest -from bip_utils import Bip32Slip10Secp256k1 from eth_account import Account from cdp.client.models.create_address_request import CreateAddressRequest from cdp.client.models.create_wallet_request import CreateWalletRequest, CreateWalletRequestWallet from cdp.client.models.create_wallet_webhook_request import CreateWalletWebhookRequest from cdp.contract_invocation import ContractInvocation +from cdp.fund_operation import FundOperation +from cdp.fund_quote import FundQuote from cdp.payload_signature import PayloadSignature from cdp.smart_contract import SmartContract from cdp.trade import Trade @@ -51,60 +52,6 @@ def test_wallet_initialization_with_server_signer(wallet_factory): assert not wallet.can_sign -@patch("cdp.Cdp.use_server_signer", False) -@patch("cdp.wallet.Account") -@patch("cdp.wallet.Bip32Slip10Secp256k1") -@patch("cdp.Cdp.api_clients") -def test_wallet_addresses( - mock_api_clients, mock_bip32, mock_account, wallet_factory, address_model_factory -): - """Test Wallet addresses method.""" - wallet = wallet_factory() - mock_list_addresses = Mock() - mock_list_addresses.return_value.data = [ - address_model_factory(address_id="0x1234"), - address_model_factory(address_id="0x5678"), - ] - mock_api_clients.addresses.list_addresses = mock_list_addresses - - mock_from_key = Mock( - side_effect=[Mock(spec=Account, address="0x1234"), Mock(spec=Account, address="0x5678")] - ) - mock_account.from_key = mock_from_key - - mock_derive_path = Mock(spec=Bip32Slip10Secp256k1) - mock_bip32.DerivePath = mock_derive_path - - addresses = wallet.addresses - - assert len(addresses) == 2 - assert all(isinstance(addr, WalletAddress) for addr in addresses) - assert addresses[0].address_id == "0x1234" - assert addresses[1].address_id == "0x5678" - - -@patch("cdp.Cdp.use_server_signer", True) -@patch("cdp.Cdp.api_clients") -def test_wallet_addresses_with_server_signer( - mock_api_clients, wallet_factory, address_model_factory -): - """Test Wallet addresses method with server-signer.""" - wallet = wallet_factory() - mock_list_addresses = Mock() - mock_list_addresses.return_value.data = [ - address_model_factory(address_id="0x1234"), - address_model_factory(address_id="0x5678"), - ] - mock_api_clients.addresses.list_addresses = mock_list_addresses - - addresses = wallet.addresses - - assert len(addresses) == 2 - assert all(isinstance(addr, WalletAddress) for addr in addresses) - assert addresses[0].address_id == "0x1234" - assert addresses[1].address_id == "0x5678" - - @patch("cdp.Cdp.use_server_signer", False) @patch("cdp.Cdp.api_clients") @patch("cdp.wallet.Bip32Slip10Secp256k1") @@ -645,3 +592,69 @@ def test_create_webhook(mock_api_clients, wallet_factory, webhook_factory): # Additional assertions to check the returned webhook object assert webhook.notification_uri == notification_uri + + +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_fund(wallet_factory): + """Test the fund method of a Wallet.""" + wallet = wallet_factory() + mock_default_address = Mock(spec=WalletAddress) + mock_fund_operation = Mock(spec=FundOperation) + mock_default_address.fund.return_value = mock_fund_operation + + with patch.object( + Wallet, "default_address", new_callable=PropertyMock + ) as mock_default_address_prop: + mock_default_address_prop.return_value = mock_default_address + + fund_operation = wallet.fund(amount="1.0", asset_id="eth") + + assert isinstance(fund_operation, FundOperation) + mock_default_address.fund.assert_called_once_with("1.0", "eth") + + +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_fund_no_default_address(wallet_factory): + """Test the fund method of a Wallet with no default address.""" + wallet = wallet_factory() + + with patch.object( + Wallet, "default_address", new_callable=PropertyMock + ) as mock_default_address_prop: + mock_default_address_prop.return_value = None + + with pytest.raises(ValueError, match="Default address does not exist"): + wallet.fund(amount="1.0", asset_id="eth") + + +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_quote_fund(wallet_factory): + """Test the quote_fund method of a Wallet.""" + wallet = wallet_factory() + mock_default_address = Mock(spec=WalletAddress) + mock_fund_quote = Mock(spec=FundQuote) + mock_default_address.quote_fund.return_value = mock_fund_quote + + with patch.object( + Wallet, "default_address", new_callable=PropertyMock + ) as mock_default_address_prop: + mock_default_address_prop.return_value = mock_default_address + + fund_quote = wallet.quote_fund(amount="1.0", asset_id="eth") + + assert isinstance(fund_quote, FundQuote) + mock_default_address.quote_fund.assert_called_once_with("1.0", "eth") + + +@patch("cdp.Cdp.use_server_signer", True) +def test_wallet_quote_fund_no_default_address(wallet_factory): + """Test the quote_fund method of a Wallet with no default address.""" + wallet = wallet_factory() + + with patch.object( + Wallet, "default_address", new_callable=PropertyMock + ) as mock_default_address_prop: + mock_default_address_prop.return_value = None + + with pytest.raises(ValueError, match="Default address does not exist"): + wallet.quote_fund(amount="1.0", asset_id="eth") diff --git a/tests/test_wallet_address.py b/tests/test_wallet_address.py index a04d6f2..2c82940 100644 --- a/tests/test_wallet_address.py +++ b/tests/test_wallet_address.py @@ -10,6 +10,8 @@ from cdp.contract_invocation import ContractInvocation from cdp.errors import InsufficientFundsError +from cdp.fund_operation import FundOperation +from cdp.fund_quote import FundQuote from cdp.payload_signature import PayloadSignature from cdp.smart_contract import SmartContract from cdp.trade import Trade @@ -1020,3 +1022,81 @@ def test_ensure_sufficient_balance_sufficient_full_amount( mock_get_balance.assert_called_once_with( network_id=wallet_address.network_id, address_id=wallet_address.address_id, asset_id="eth" ) + + +@patch("cdp.wallet_address.FundOperation") +def test_fund(mock_fund_operation, wallet_address_factory): + """Test the fund method.""" + wallet_address = wallet_address_factory() + + mock_fund_operation_instance = Mock(spec=FundOperation) + mock_fund_operation.create.return_value = mock_fund_operation_instance + + fund_operation = wallet_address.fund(amount="1.0", asset_id="eth") + + assert isinstance(fund_operation, FundOperation) + mock_fund_operation.create.assert_called_once_with( + address_id=wallet_address.address_id, + amount=Decimal("1.0"), + asset_id="eth", + network_id=wallet_address.network_id, + wallet_id=wallet_address.wallet_id, + ) + + +@patch("cdp.wallet_address.FundOperation") +def test_fund_api_error(mock_fund_operation, wallet_address_factory): + """Test the fund method raises an error when the API call fails.""" + wallet_address = wallet_address_factory() + + mock_fund_operation.create.side_effect = Exception("API Error") + + with pytest.raises(Exception, match="API Error"): + wallet_address.fund(amount="1.0", asset_id="eth") + + mock_fund_operation.create.assert_called_once_with( + address_id=wallet_address.address_id, + amount=Decimal("1.0"), + asset_id="eth", + network_id=wallet_address.network_id, + wallet_id=wallet_address.wallet_id, + ) + + +@patch("cdp.wallet_address.FundQuote") +def test_quote_fund(mock_fund_quote, wallet_address_factory): + """Test the quote_fund method.""" + wallet_address = wallet_address_factory() + + mock_fund_quote_instance = Mock(spec=FundQuote) + mock_fund_quote.create.return_value = mock_fund_quote_instance + + fund_quote = wallet_address.quote_fund(amount="1.0", asset_id="eth") + + assert isinstance(fund_quote, FundQuote) + mock_fund_quote.create.assert_called_once_with( + address_id=wallet_address.address_id, + amount="1.0", + asset_id="eth", + network_id=wallet_address.network_id, + wallet_id=wallet_address.wallet_id, + ) + + +@patch("cdp.wallet_address.FundQuote") +def test_quote_fund_api_error(mock_fund_quote, wallet_address_factory): + """Test the quote_fund method raises an error when the API call fails.""" + wallet_address = wallet_address_factory() + + mock_fund_quote.create.side_effect = Exception("API Error") + + with pytest.raises(Exception, match="API Error"): + wallet_address.quote_fund(amount="1.0", asset_id="eth") + + mock_fund_quote.create.assert_called_once_with( + address_id=wallet_address.address_id, + amount="1.0", + asset_id="eth", + network_id=wallet_address.network_id, + wallet_id=wallet_address.wallet_id, + ) From 02af63450ac4f52f1fd0d720a4ae133c38918661 Mon Sep 17 00:00:00 2001 From: rohan-agarwal-coinbase Date: Wed, 27 Nov 2024 14:55:31 -0500 Subject: [PATCH 37/40] Fix quote fund to properly pass in normalized amount (#50) --- cdp/wallet_address.py | 2 +- tests/test_wallet_address.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cdp/wallet_address.py b/cdp/wallet_address.py index e8d801d..1f9a3f9 100644 --- a/cdp/wallet_address.py +++ b/cdp/wallet_address.py @@ -361,7 +361,7 @@ def quote_fund(self, amount: Number | Decimal | str, asset_id: str) -> FundQuote return FundQuote.create( address_id=self.address_id, - amount=str(normalized_amount), + amount=normalized_amount, asset_id=asset_id, network_id=self.network_id, wallet_id=self.wallet_id, diff --git a/tests/test_wallet_address.py b/tests/test_wallet_address.py index 2c82940..48a65af 100644 --- a/tests/test_wallet_address.py +++ b/tests/test_wallet_address.py @@ -1076,7 +1076,7 @@ def test_quote_fund(mock_fund_quote, wallet_address_factory): assert isinstance(fund_quote, FundQuote) mock_fund_quote.create.assert_called_once_with( address_id=wallet_address.address_id, - amount="1.0", + amount=Decimal("1.0"), asset_id="eth", network_id=wallet_address.network_id, wallet_id=wallet_address.wallet_id, @@ -1095,7 +1095,7 @@ def test_quote_fund_api_error(mock_fund_quote, wallet_address_factory): mock_fund_quote.create.assert_called_once_with( address_id=wallet_address.address_id, - amount="1.0", + amount=Decimal("1.0"), asset_id="eth", network_id=wallet_address.network_id, wallet_id=wallet_address.wallet_id, From 59d554ce7b0d54c4dcf4bad02757c30985f54760 Mon Sep 17 00:00:00 2001 From: cb-howardatcb <86798563+howard-at-cb@users.noreply.github.com> Date: Wed, 27 Nov 2024 12:47:18 -0800 Subject: [PATCH 38/40] Contract webhook support (#52) * contract activity webhook support * Update webhook.py * Update webhook_factory.py --- cdp/client/__init__.py | 3 + cdp/client/api/smart_contracts_api.py | 366 ++++++++++++++++-- cdp/client/models/__init__.py | 3 + cdp/client/models/abi.py | 89 +++++ cdp/client/models/ethereum_transaction.py | 6 +- cdp/client/models/smart_contract.py | 4 +- .../models/smart_contract_activity_event.py | 122 ++++++ cdp/client/models/smart_contract_type.py | 1 + cdp/client/models/webhook_event_type.py | 1 + .../models/webhook_event_type_filter.py | 30 +- .../webhook_smart_contract_event_filter.py | 87 +++++ .../models/webhook_wallet_activity_filter.py | 2 +- cdp/webhook.py | 8 +- tests/factories/smart_contract_factory.py | 1 + tests/factories/webhook_factory.py | 10 + 15 files changed, 683 insertions(+), 50 deletions(-) create mode 100644 cdp/client/models/abi.py create mode 100644 cdp/client/models/smart_contract_activity_event.py create mode 100644 cdp/client/models/webhook_smart_contract_event_filter.py diff --git a/cdp/client/__init__.py b/cdp/client/__init__.py index 52e517f..216b8c1 100644 --- a/cdp/client/__init__.py +++ b/cdp/client/__init__.py @@ -50,6 +50,7 @@ from cdp.client.exceptions import ApiException # import models into sdk package +from cdp.client.models.abi import ABI from cdp.client.models.address import Address from cdp.client.models.address_balance_list import AddressBalanceList from cdp.client.models.address_historical_balance_list import AddressHistoricalBalanceList @@ -126,6 +127,7 @@ from cdp.client.models.signature_creation_event_result import SignatureCreationEventResult from cdp.client.models.signed_voluntary_exit_message_metadata import SignedVoluntaryExitMessageMetadata from cdp.client.models.smart_contract import SmartContract +from cdp.client.models.smart_contract_activity_event import SmartContractActivityEvent from cdp.client.models.smart_contract_list import SmartContractList from cdp.client.models.smart_contract_options import SmartContractOptions from cdp.client.models.smart_contract_type import SmartContractType @@ -161,4 +163,5 @@ from cdp.client.models.webhook_event_type import WebhookEventType from cdp.client.models.webhook_event_type_filter import WebhookEventTypeFilter from cdp.client.models.webhook_list import WebhookList +from cdp.client.models.webhook_smart_contract_event_filter import WebhookSmartContractEventFilter from cdp.client.models.webhook_wallet_activity_filter import WebhookWalletActivityFilter diff --git a/cdp/client/api/smart_contracts_api.py b/cdp/client/api/smart_contracts_api.py index 6d59210..ab3a59e 100644 --- a/cdp/client/api/smart_contracts_api.py +++ b/cdp/client/api/smart_contracts_api.py @@ -17,7 +17,9 @@ from typing_extensions import Annotated from pydantic import Field, StrictStr +from typing import Optional from typing_extensions import Annotated +from cdp.client.models.abi import ABI from cdp.client.models.create_smart_contract_request import CreateSmartContractRequest from cdp.client.models.deploy_smart_contract_request import DeploySmartContractRequest from cdp.client.models.read_contract_request import ReadContractRequest @@ -957,8 +959,7 @@ def _get_smart_contract_serialize( @validate_call def list_smart_contracts( self, - wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], - address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the smart contracts for.")], + page: Annotated[Optional[StrictStr], Field(description="Pagination token for retrieving the next set of results")] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -972,14 +973,12 @@ def list_smart_contracts( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> SmartContractList: - """List smart contracts deployed by address + """List smart contracts - List all smart contracts deployed by address. + List smart contracts - :param wallet_id: The ID of the wallet the address belongs to. (required) - :type wallet_id: str - :param address_id: The ID of the address to fetch the smart contracts for. (required) - :type address_id: str + :param page: Pagination token for retrieving the next set of results + :type page: str :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 @@ -1003,8 +1002,7 @@ def list_smart_contracts( """ # noqa: E501 _param = self._list_smart_contracts_serialize( - wallet_id=wallet_id, - address_id=address_id, + page=page, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -1028,8 +1026,7 @@ def list_smart_contracts( @validate_call def list_smart_contracts_with_http_info( self, - wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], - address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the smart contracts for.")], + page: Annotated[Optional[StrictStr], Field(description="Pagination token for retrieving the next set of results")] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -1043,14 +1040,12 @@ def list_smart_contracts_with_http_info( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> ApiResponse[SmartContractList]: - """List smart contracts deployed by address + """List smart contracts - List all smart contracts deployed by address. + List smart contracts - :param wallet_id: The ID of the wallet the address belongs to. (required) - :type wallet_id: str - :param address_id: The ID of the address to fetch the smart contracts for. (required) - :type address_id: str + :param page: Pagination token for retrieving the next set of results + :type page: str :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 @@ -1074,8 +1069,7 @@ def list_smart_contracts_with_http_info( """ # noqa: E501 _param = self._list_smart_contracts_serialize( - wallet_id=wallet_id, - address_id=address_id, + page=page, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -1099,8 +1093,7 @@ def list_smart_contracts_with_http_info( @validate_call def list_smart_contracts_without_preload_content( self, - wallet_id: Annotated[StrictStr, Field(description="The ID of the wallet the address belongs to.")], - address_id: Annotated[StrictStr, Field(description="The ID of the address to fetch the smart contracts for.")], + page: Annotated[Optional[StrictStr], Field(description="Pagination token for retrieving the next set of results")] = None, _request_timeout: Union[ None, Annotated[StrictFloat, Field(gt=0)], @@ -1114,14 +1107,12 @@ def list_smart_contracts_without_preload_content( _headers: Optional[Dict[StrictStr, Any]] = None, _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> RESTResponseType: - """List smart contracts deployed by address + """List smart contracts - List all smart contracts deployed by address. + List smart contracts - :param wallet_id: The ID of the wallet the address belongs to. (required) - :type wallet_id: str - :param address_id: The ID of the address to fetch the smart contracts for. (required) - :type address_id: str + :param page: Pagination token for retrieving the next set of results + :type page: str :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 @@ -1145,8 +1136,7 @@ def list_smart_contracts_without_preload_content( """ # noqa: E501 _param = self._list_smart_contracts_serialize( - wallet_id=wallet_id, - address_id=address_id, + page=page, _request_auth=_request_auth, _content_type=_content_type, _headers=_headers, @@ -1165,8 +1155,7 @@ def list_smart_contracts_without_preload_content( def _list_smart_contracts_serialize( self, - wallet_id, - address_id, + page, _request_auth, _content_type, _headers, @@ -1188,11 +1177,11 @@ def _list_smart_contracts_serialize( _body_params: Optional[bytes] = None # process the path parameters - if wallet_id is not None: - _path_params['wallet_id'] = wallet_id - if address_id is not None: - _path_params['address_id'] = address_id # process the query parameters + if page is not None: + + _query_params.append(('page', page)) + # process the header parameters # process the form parameters # process the body parameter @@ -1213,7 +1202,7 @@ def _list_smart_contracts_serialize( return self.api_client.param_serialize( method='GET', - resource_path='/v1/wallets/{wallet_id}/addresses/{address_id}/smart_contracts', + resource_path='/v1/smart_contracts', path_params=_path_params, query_params=_query_params, header_params=_header_params, @@ -1530,3 +1519,306 @@ def _read_contract_serialize( ) + + + @validate_call + def register_smart_contract( + self, + contract_address: Annotated[StrictStr, Field(description="EVM address of the smart contract (42 characters, including '0x', in lowercase)")], + network_id: Annotated[StrictStr, Field(description="The ID of the network to fetch.")], + abi: ABI, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Register a smart contract + + Register a smart contract + + :param contract_address: EVM address of the smart contract (42 characters, including '0x', in lowercase) (required) + :type contract_address: str + :param network_id: The ID of the network to fetch. (required) + :type network_id: str + :param abi: (required) + :type abi: ABI + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._register_smart_contract_serialize( + contract_address=contract_address, + network_id=network_id, + abi=abi, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def register_smart_contract_with_http_info( + self, + contract_address: Annotated[StrictStr, Field(description="EVM address of the smart contract (42 characters, including '0x', in lowercase)")], + network_id: Annotated[StrictStr, Field(description="The ID of the network to fetch.")], + abi: ABI, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Register a smart contract + + Register a smart contract + + :param contract_address: EVM address of the smart contract (42 characters, including '0x', in lowercase) (required) + :type contract_address: str + :param network_id: The ID of the network to fetch. (required) + :type network_id: str + :param abi: (required) + :type abi: ABI + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._register_smart_contract_serialize( + contract_address=contract_address, + network_id=network_id, + abi=abi, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def register_smart_contract_without_preload_content( + self, + contract_address: Annotated[StrictStr, Field(description="EVM address of the smart contract (42 characters, including '0x', in lowercase)")], + network_id: Annotated[StrictStr, Field(description="The ID of the network to fetch.")], + abi: ABI, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Register a smart contract + + Register a smart contract + + :param contract_address: EVM address of the smart contract (42 characters, including '0x', in lowercase) (required) + :type contract_address: str + :param network_id: The ID of the network to fetch. (required) + :type network_id: str + :param abi: (required) + :type abi: ABI + :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. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._register_smart_contract_serialize( + contract_address=contract_address, + network_id=network_id, + abi=abi, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _register_smart_contract_serialize( + self, + contract_address, + network_id, + abi, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if contract_address is not None: + _path_params['contract_address'] = contract_address + if network_id is not None: + _path_params['network_id'] = network_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if abi is not None: + _body_params = abi + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/v1/networks/{network_id}/smart_contracts/{contract_address}/register', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/cdp/client/models/__init__.py b/cdp/client/models/__init__.py index db94dc4..d10d6ed 100644 --- a/cdp/client/models/__init__.py +++ b/cdp/client/models/__init__.py @@ -14,6 +14,7 @@ # import models into model package +from cdp.client.models.abi import ABI from cdp.client.models.address import Address from cdp.client.models.address_balance_list import AddressBalanceList from cdp.client.models.address_historical_balance_list import AddressHistoricalBalanceList @@ -90,6 +91,7 @@ from cdp.client.models.signature_creation_event_result import SignatureCreationEventResult from cdp.client.models.signed_voluntary_exit_message_metadata import SignedVoluntaryExitMessageMetadata from cdp.client.models.smart_contract import SmartContract +from cdp.client.models.smart_contract_activity_event import SmartContractActivityEvent from cdp.client.models.smart_contract_list import SmartContractList from cdp.client.models.smart_contract_options import SmartContractOptions from cdp.client.models.smart_contract_type import SmartContractType @@ -125,4 +127,5 @@ from cdp.client.models.webhook_event_type import WebhookEventType from cdp.client.models.webhook_event_type_filter import WebhookEventTypeFilter from cdp.client.models.webhook_list import WebhookList +from cdp.client.models.webhook_smart_contract_event_filter import WebhookSmartContractEventFilter from cdp.client.models.webhook_wallet_activity_filter import WebhookWalletActivityFilter diff --git a/cdp/client/models/abi.py b/cdp/client/models/abi.py new file mode 100644 index 0000000..66883ca --- /dev/null +++ b/cdp/client/models/abi.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class ABI(BaseModel): + """ + Smart Contract to be registered + """ # noqa: E501 + abi: StrictStr = Field(description="ABI of the smart contract") + contract_name: StrictStr = Field(description="Name of the smart contract") + __properties: ClassVar[List[str]] = ["abi", "contract_name"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ABI from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ABI from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "abi": obj.get("abi"), + "contract_name": obj.get("contract_name") + }) + return _obj + + diff --git a/cdp/client/models/ethereum_transaction.py b/cdp/client/models/ethereum_transaction.py index 4ce2d4b..9405d8e 100644 --- a/cdp/client/models/ethereum_transaction.py +++ b/cdp/client/models/ethereum_transaction.py @@ -48,7 +48,8 @@ class EthereumTransaction(BaseModel): flattened_traces: Optional[List[EthereumTransactionFlattenedTrace]] = None block_timestamp: Optional[datetime] = Field(default=None, description="The timestamp of the block in which the event was emitted") mint: Optional[StrictStr] = Field(default=None, description="This is for handling optimism rollup specific EIP-2718 transaction type field.") - __properties: ClassVar[List[str]] = ["from", "gas", "gas_price", "hash", "input", "nonce", "to", "index", "value", "type", "max_fee_per_gas", "max_priority_fee_per_gas", "priority_fee_per_gas", "transaction_access_list", "token_transfers", "flattened_traces", "block_timestamp", "mint"] + rlp_encoded_tx: Optional[StrictStr] = Field(default=None, description="RLP encoded transaction as a hex string (prefixed with 0x) for native compatibility with popular eth clients such as etherjs, viem etc.") + __properties: ClassVar[List[str]] = ["from", "gas", "gas_price", "hash", "input", "nonce", "to", "index", "value", "type", "max_fee_per_gas", "max_priority_fee_per_gas", "priority_fee_per_gas", "transaction_access_list", "token_transfers", "flattened_traces", "block_timestamp", "mint", "rlp_encoded_tx"] model_config = ConfigDict( populate_by_name=True, @@ -135,7 +136,8 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: "token_transfers": [EthereumTokenTransfer.from_dict(_item) for _item in obj["token_transfers"]] if obj.get("token_transfers") is not None else None, "flattened_traces": [EthereumTransactionFlattenedTrace.from_dict(_item) for _item in obj["flattened_traces"]] if obj.get("flattened_traces") is not None else None, "block_timestamp": obj.get("block_timestamp"), - "mint": obj.get("mint") + "mint": obj.get("mint"), + "rlp_encoded_tx": obj.get("rlp_encoded_tx") }) return _obj diff --git a/cdp/client/models/smart_contract.py b/cdp/client/models/smart_contract.py index 884ca0c..1d1a54f 100644 --- a/cdp/client/models/smart_contract.py +++ b/cdp/client/models/smart_contract.py @@ -33,12 +33,13 @@ class SmartContract(BaseModel): network_id: StrictStr = Field(description="The name of the blockchain network") wallet_id: StrictStr = Field(description="The ID of the wallet that deployed the smart contract") contract_address: StrictStr = Field(description="The EVM address of the smart contract") + contract_name: StrictStr = Field(description="The name of the smart contract") deployer_address: StrictStr = Field(description="The EVM address of the account that deployed the smart contract") type: SmartContractType options: SmartContractOptions abi: StrictStr = Field(description="The JSON-encoded ABI of the contract") transaction: Transaction - __properties: ClassVar[List[str]] = ["smart_contract_id", "network_id", "wallet_id", "contract_address", "deployer_address", "type", "options", "abi", "transaction"] + __properties: ClassVar[List[str]] = ["smart_contract_id", "network_id", "wallet_id", "contract_address", "contract_name", "deployer_address", "type", "options", "abi", "transaction"] model_config = ConfigDict( populate_by_name=True, @@ -101,6 +102,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: "network_id": obj.get("network_id"), "wallet_id": obj.get("wallet_id"), "contract_address": obj.get("contract_address"), + "contract_name": obj.get("contract_name"), "deployer_address": obj.get("deployer_address"), "type": obj.get("type"), "options": SmartContractOptions.from_dict(obj["options"]) if obj.get("options") is not None else None, diff --git a/cdp/client/models/smart_contract_activity_event.py b/cdp/client/models/smart_contract_activity_event.py new file mode 100644 index 0000000..dbc494d --- /dev/null +++ b/cdp/client/models/smart_contract_activity_event.py @@ -0,0 +1,122 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class SmartContractActivityEvent(BaseModel): + """ + Represents an event triggered by a smart contract activity on the blockchain. Contains information about the function, transaction, block, and involved addresses. + """ # noqa: E501 + webhook_id: Optional[StrictStr] = Field(default=None, description="Unique identifier for the webhook that triggered this event.", alias="webhookId") + event_type: Optional[StrictStr] = Field(default=None, description="Type of event, in this case, an ERC-721 token transfer.", alias="eventType") + network: Optional[StrictStr] = Field(default=None, description="Blockchain network where the event occurred.") + project_name: Optional[StrictStr] = Field(default=None, description="Name of the project this smart contract belongs to.", alias="projectName") + contract_name: Optional[StrictStr] = Field(default=None, description="Name of the contract.", alias="contractName") + func: Optional[StrictStr] = Field(default=None, description="Name of the function.") + sig: Optional[StrictStr] = Field(default=None, description="Signature of the function.") + four_bytes: Optional[StrictStr] = Field(default=None, description="First 4 bytes of the Transaction, a unique ID.", alias="fourBytes") + contract_address: Optional[StrictStr] = Field(default=None, description="Address of the smart contract.", alias="contractAddress") + block_hash: Optional[StrictStr] = Field(default=None, description="Hash of the block containing the transaction.", alias="blockHash") + block_number: Optional[StrictInt] = Field(default=None, description="Number of the block containing the transaction.", alias="blockNumber") + block_time: Optional[datetime] = Field(default=None, description="Timestamp when the block was mined.", alias="blockTime") + transaction_hash: Optional[StrictStr] = Field(default=None, description="Hash of the transaction that triggered the event.", alias="transactionHash") + transaction_index: Optional[StrictInt] = Field(default=None, description="Position of the transaction within the block.", alias="transactionIndex") + log_index: Optional[StrictInt] = Field(default=None, description="Position of the event log within the transaction.", alias="logIndex") + var_from: Optional[StrictStr] = Field(default=None, description="Address of the initiator in the transfer.", alias="from") + to: Optional[StrictStr] = Field(default=None, description="Address of the recipient in the transfer.") + value: Optional[StrictInt] = Field(default=None, description="Amount of tokens transferred, typically in the smallest unit (e.g., wei for Ethereum).") + __properties: ClassVar[List[str]] = ["webhookId", "eventType", "network", "projectName", "contractName", "func", "sig", "fourBytes", "contractAddress", "blockHash", "blockNumber", "blockTime", "transactionHash", "transactionIndex", "logIndex", "from", "to", "value"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of SmartContractActivityEvent from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of SmartContractActivityEvent from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "webhookId": obj.get("webhookId"), + "eventType": obj.get("eventType"), + "network": obj.get("network"), + "projectName": obj.get("projectName"), + "contractName": obj.get("contractName"), + "func": obj.get("func"), + "sig": obj.get("sig"), + "fourBytes": obj.get("fourBytes"), + "contractAddress": obj.get("contractAddress"), + "blockHash": obj.get("blockHash"), + "blockNumber": obj.get("blockNumber"), + "blockTime": obj.get("blockTime"), + "transactionHash": obj.get("transactionHash"), + "transactionIndex": obj.get("transactionIndex"), + "logIndex": obj.get("logIndex"), + "from": obj.get("from"), + "to": obj.get("to"), + "value": obj.get("value") + }) + return _obj + + diff --git a/cdp/client/models/smart_contract_type.py b/cdp/client/models/smart_contract_type.py index 7399f69..db6c791 100644 --- a/cdp/client/models/smart_contract_type.py +++ b/cdp/client/models/smart_contract_type.py @@ -29,6 +29,7 @@ class SmartContractType(str, Enum): ERC20 = 'erc20' ERC721 = 'erc721' ERC1155 = 'erc1155' + CUSTOM = 'custom' @classmethod def from_json(cls, json_str: str) -> Self: diff --git a/cdp/client/models/webhook_event_type.py b/cdp/client/models/webhook_event_type.py index d2438b7..15cf4e5 100644 --- a/cdp/client/models/webhook_event_type.py +++ b/cdp/client/models/webhook_event_type.py @@ -30,6 +30,7 @@ class WebhookEventType(str, Enum): ERC20_TRANSFER = 'erc20_transfer' ERC721_TRANSFER = 'erc721_transfer' WALLET_ACTIVITY = 'wallet_activity' + SMART_CONTRACT_EVENT_ACTIVITY = 'smart_contract_event_activity' @classmethod def from_json(cls, json_str: str) -> Self: diff --git a/cdp/client/models/webhook_event_type_filter.py b/cdp/client/models/webhook_event_type_filter.py index 6344979..19acac0 100644 --- a/cdp/client/models/webhook_event_type_filter.py +++ b/cdp/client/models/webhook_event_type_filter.py @@ -17,12 +17,13 @@ import pprint from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator from typing import Any, List, Optional +from cdp.client.models.webhook_smart_contract_event_filter import WebhookSmartContractEventFilter from cdp.client.models.webhook_wallet_activity_filter import WebhookWalletActivityFilter from pydantic import StrictStr, Field from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self -WEBHOOKEVENTTYPEFILTER_ONE_OF_SCHEMAS = ["WebhookWalletActivityFilter"] +WEBHOOKEVENTTYPEFILTER_ONE_OF_SCHEMAS = ["WebhookSmartContractEventFilter", "WebhookWalletActivityFilter"] class WebhookEventTypeFilter(BaseModel): """ @@ -30,8 +31,10 @@ class WebhookEventTypeFilter(BaseModel): """ # data type: WebhookWalletActivityFilter oneof_schema_1_validator: Optional[WebhookWalletActivityFilter] = None - actual_instance: Optional[Union[WebhookWalletActivityFilter]] = None - one_of_schemas: Set[str] = { "WebhookWalletActivityFilter" } + # data type: WebhookSmartContractEventFilter + oneof_schema_2_validator: Optional[WebhookSmartContractEventFilter] = None + actual_instance: Optional[Union[WebhookSmartContractEventFilter, WebhookWalletActivityFilter]] = None + one_of_schemas: Set[str] = { "WebhookSmartContractEventFilter", "WebhookWalletActivityFilter" } model_config = ConfigDict( validate_assignment=True, @@ -59,12 +62,17 @@ def actual_instance_must_validate_oneof(cls, v): error_messages.append(f"Error! Input type `{type(v)}` is not `WebhookWalletActivityFilter`") else: match += 1 + # validate data type: WebhookSmartContractEventFilter + if not isinstance(v, WebhookSmartContractEventFilter): + error_messages.append(f"Error! Input type `{type(v)}` is not `WebhookSmartContractEventFilter`") + else: + match += 1 if match > 1: # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in WebhookEventTypeFilter with oneOf schemas: WebhookWalletActivityFilter. Details: " + ", ".join(error_messages)) + raise ValueError("Multiple matches found when setting `actual_instance` in WebhookEventTypeFilter with oneOf schemas: WebhookSmartContractEventFilter, WebhookWalletActivityFilter. Details: " + ", ".join(error_messages)) elif match == 0: # no match - raise ValueError("No match found when setting `actual_instance` in WebhookEventTypeFilter with oneOf schemas: WebhookWalletActivityFilter. Details: " + ", ".join(error_messages)) + raise ValueError("No match found when setting `actual_instance` in WebhookEventTypeFilter with oneOf schemas: WebhookSmartContractEventFilter, WebhookWalletActivityFilter. Details: " + ", ".join(error_messages)) else: return v @@ -85,13 +93,19 @@ def from_json(cls, json_str: str) -> Self: match += 1 except (ValidationError, ValueError) as e: error_messages.append(str(e)) + # deserialize data into WebhookSmartContractEventFilter + try: + instance.actual_instance = WebhookSmartContractEventFilter.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) if match > 1: # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into WebhookEventTypeFilter with oneOf schemas: WebhookWalletActivityFilter. Details: " + ", ".join(error_messages)) + raise ValueError("Multiple matches found when deserializing the JSON string into WebhookEventTypeFilter with oneOf schemas: WebhookSmartContractEventFilter, WebhookWalletActivityFilter. Details: " + ", ".join(error_messages)) elif match == 0: # no match - raise ValueError("No match found when deserializing the JSON string into WebhookEventTypeFilter with oneOf schemas: WebhookWalletActivityFilter. Details: " + ", ".join(error_messages)) + raise ValueError("No match found when deserializing the JSON string into WebhookEventTypeFilter with oneOf schemas: WebhookSmartContractEventFilter, WebhookWalletActivityFilter. Details: " + ", ".join(error_messages)) else: return instance @@ -105,7 +119,7 @@ def to_json(self) -> str: else: return json.dumps(self.actual_instance) - def to_dict(self) -> Optional[Union[Dict[str, Any], WebhookWalletActivityFilter]]: + def to_dict(self) -> Optional[Union[Dict[str, Any], WebhookSmartContractEventFilter, WebhookWalletActivityFilter]]: """Returns the dict representation of the actual instance""" if self.actual_instance is None: return None diff --git a/cdp/client/models/webhook_smart_contract_event_filter.py b/cdp/client/models/webhook_smart_contract_event_filter.py new file mode 100644 index 0000000..c9869c4 --- /dev/null +++ b/cdp/client/models/webhook_smart_contract_event_filter.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + Coinbase Platform API + + This is the OpenAPI 3.0 specification for the Coinbase Platform APIs, used in conjunction with the Coinbase Platform SDKs. + + The version of the OpenAPI document: 0.0.1-alpha + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class WebhookSmartContractEventFilter(BaseModel): + """ + Filter for smart contract events. This filter allows the client to specify smart contract addresses to monitor for activities such as contract function calls. + """ # noqa: E501 + contract_addresses: List[StrictStr] = Field(description="A list of smart contract addresses to filter on.") + __properties: ClassVar[List[str]] = ["contract_addresses"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of WebhookSmartContractEventFilter from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of WebhookSmartContractEventFilter from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "contract_addresses": obj.get("contract_addresses") + }) + return _obj + + diff --git a/cdp/client/models/webhook_wallet_activity_filter.py b/cdp/client/models/webhook_wallet_activity_filter.py index 30356d4..253e442 100644 --- a/cdp/client/models/webhook_wallet_activity_filter.py +++ b/cdp/client/models/webhook_wallet_activity_filter.py @@ -27,7 +27,7 @@ class WebhookWalletActivityFilter(BaseModel): Filter for wallet activity events. This filter allows the client to specify one or more wallet addresses to monitor for activities such as transactions, transfers, or other types of events that are associated with the specified addresses. """ # noqa: E501 addresses: Optional[List[StrictStr]] = Field(default=None, description="A list of wallet addresses to filter on.") - wallet_id: Optional[StrictStr] = Field(default=None, description="The ID of the wallet that owns the webhook.") + wallet_id: StrictStr = Field(description="The ID of the wallet that owns the webhook.") __properties: ClassVar[List[str]] = ["addresses", "wallet_id"] model_config = ConfigDict( diff --git a/cdp/webhook.py b/cdp/webhook.py index 4f26318..0be1567 100644 --- a/cdp/webhook.py +++ b/cdp/webhook.py @@ -94,7 +94,7 @@ def create( Args: notification_uri (str): The URI where notifications should be sent. event_type (WebhookEventType): The type of event that the webhook listens to. - event_type_filter (WebhookEventTypeFilter): Filter specifically for wallet activity event type. + event_type_filter (WebhookEventTypeFilter): Filter specifically for wallet or contract activity event type. event_filters (List[WebhookEventTypeFilter]): Filters applied to the events that determine which specific address(es) trigger. network_id (str): The network ID of the wallet. Defaults to "base-sepolia". @@ -165,6 +165,12 @@ def update( final_notification_uri = notification_uri or self.notification_uri final_event_type_filter = event_type_filter or self.event_type_filter + # wallet ID is required for wallet activity event type filter, but we do not support updating it just yet, this will be added in the future + if self.event_type == WebhookEventType.WALLET_ACTIVITY: + final_event_type_filter.actual_instance.wallet_id = ( + self.event_type_filter.actual_instance.wallet_id + ) + update_webhook_request = UpdateWebhookRequest( event_type_filter=final_event_type_filter, event_filters=self.event_filters, diff --git a/tests/factories/smart_contract_factory.py b/tests/factories/smart_contract_factory.py index e8d16d4..efa2bf6 100644 --- a/tests/factories/smart_contract_factory.py +++ b/tests/factories/smart_contract_factory.py @@ -19,6 +19,7 @@ def _create_smart_contract_model(status="complete"): network_id="base-sepolia", wallet_id="test-wallet-id", contract_address="0xcontractaddress", + contract_name="TestContract", deployer_address="0xdeployeraddress", type="erc20", options=smart_contract_options, diff --git a/tests/factories/webhook_factory.py b/tests/factories/webhook_factory.py index d15d5cb..2a3dcc2 100644 --- a/tests/factories/webhook_factory.py +++ b/tests/factories/webhook_factory.py @@ -1,5 +1,6 @@ import pytest +from cdp.client import WebhookEventTypeFilter, WebhookWalletActivityFilter from cdp.webhook import Webhook, WebhookEventType, WebhookModel @@ -15,6 +16,15 @@ def _create_webhook( event_type_filter=None, event_filters=None, ): + # Ensure the event_type_filter is properly initialized + if event_type_filter is None and event_type == WebhookEventType.WALLET_ACTIVITY: + event_type_filter = WebhookEventTypeFilter( + actual_instance=WebhookWalletActivityFilter( + wallet_id="w1", + addresses=["0xa55C5950F7A3C42Fa5799B2Cac0e455774a07382"], + ) + ) + model = WebhookModel( id=webhook_id, network_id=network_id, From d569b15633cda9c2b72420621e1488719b18bc0c Mon Sep 17 00:00:00 2001 From: Alexander Stone Date: Wed, 27 Nov 2024 12:51:07 -0800 Subject: [PATCH 39/40] chore: Prep v0.11.0 release (#51) --- CHANGELOG.md | 9 ++++++--- cdp/__version__.py | 2 +- docs/conf.py | 2 +- pyproject.toml | 2 +- 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 915995e..b56a304 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,12 +2,15 @@ ## Unreleased -### Fixed -- Fix bug in `Asset.from_model` where passed in asset ID was not used when creating a gwei or wei asset. +### [0.11.0] - 2024-11-27 ### Added +- Add support for funding wallets (Alpha feature release) + - Must reach out to CDP SDK Discord channel to be considered for this feature. +- Added create and update feature for `SmartContractEventActivity` webhook and its related event type filter. -- Add `FundOperation` and `FundQuote` classes to support wallet funding. +### Fixed +- Fix bug in `Asset.from_model` where passed in asset ID was not used when creating a gwei or wei asset. ## [0.10.3] - 2024-11-07 diff --git a/cdp/__version__.py b/cdp/__version__.py index b2385cb..ae6db5f 100644 --- a/cdp/__version__.py +++ b/cdp/__version__.py @@ -1 +1 @@ -__version__ = "0.10.3" +__version__ = "0.11.0" diff --git a/docs/conf.py b/docs/conf.py index 5dc3ee9..fe1550f 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -14,7 +14,7 @@ project = 'CDP SDK' author = 'Coinbase Developer Platform' -release = '0.10.3' +release = '0.11.0' # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration diff --git a/pyproject.toml b/pyproject.toml index 251d4fc..d681820 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "cdp-sdk" -version = "0.10.3" +version = "0.11.0" description = "CDP Python SDK" readme = "README.md" authors = [{name = "John Peterson", email = "john.peterson@coinbase.com"}] From cb70de316a1d57f98a1f4598eaf263f4acd53ae3 Mon Sep 17 00:00:00 2001 From: Alex Stone Date: Wed, 27 Nov 2024 12:57:49 -0800 Subject: [PATCH 40/40] Merge remote-tracking branch 'origin' into HEAD --- CHANGELOG.md | 6 ++++++ cdp/wallet_address.py | 20 ++++++++++++++++++++ docs/conf.py | 1 - tests/test_wallet_address.py | 19 +++++++++++++++++++ 4 files changed, 45 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b56a304..6c1b378 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,12 @@ ### Fixed - Fix bug in `Asset.from_model` where passed in asset ID was not used when creating a gwei or wei asset. +## [0.10.4] - 2024-11-25 + +### Added + +- Wallet address key export + ## [0.10.3] - 2024-11-07 ### Added diff --git a/cdp/wallet_address.py b/cdp/wallet_address.py index 1f9a3f9..51ef753 100644 --- a/cdp/wallet_address.py +++ b/cdp/wallet_address.py @@ -74,6 +74,26 @@ def can_sign(self) -> bool: """ return self.key is not None + def export(self) -> str: + """Export the wallet address's private key as a hex string. + + Returns: + str: The wallet address's private key as a hex string. + + Raises: + ValueError: If the wallet address does not have a private key. + + """ + local_account = self.key + if local_account is None: + raise ValueError("Private key is unavailable") + + key_bytes = local_account.key + if key_bytes is None: + raise ValueError("Private key is empty") + + return key_bytes.hex() + def transfer( self, amount: Number | Decimal | str, diff --git a/docs/conf.py b/docs/conf.py index fe1550f..d1ac1c3 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -30,7 +30,6 @@ exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] - # -- Options for HTML output ------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output diff --git a/tests/test_wallet_address.py b/tests/test_wallet_address.py index 48a65af..4bc6119 100644 --- a/tests/test_wallet_address.py +++ b/tests/test_wallet_address.py @@ -83,6 +83,25 @@ def test_key_setter_raises_error_when_already_set(wallet_address_factory): wallet_address_with_key.key = new_key +def test_export(wallet_address_factory): + """Test export method success for a WalletAddress.""" + wallet_address_with_key = wallet_address_factory(True) + + key_hex = wallet_address_with_key.export() + + assert key_hex is not None + assert key_hex != "" + assert key_hex.startswith("0x") + + +def test_export_raises_error_when_local_account_is_none(wallet_address_factory): + """Test export method failure for a WalletAddress with no LocalAccount.""" + wallet_address_without_key = wallet_address_factory() + + with pytest.raises(ValueError, match="Private key is unavailable"): + wallet_address_without_key.export() + + @patch("cdp.wallet_address.Transfer") @patch("cdp.Cdp.api_clients") @patch("cdp.Cdp.use_server_signer", True)