Public Blockchain Class - public_blockchain_client

Classes:

PublicBlockchainClient(network, trusted_ips, …)

This class allows the user to interact with the TradeScan API including information available with validators, tokens, delegators, addresses, and blockchain stats.

class tradehub.public_blockchain_client.PublicBlockchainClient(network: str = 'testnet', trusted_ips: Union[None, list] = None, trusted_uris: Union[None, list] = None, is_websocket_client: bool = False)[source]

Bases: tradehub.decentralized_client.NetworkCrawlerClient

This class allows the user to interact with the TradeScan API including information available with validators, tokens, delegators, addresses, and blockchain stats.

Methods:

get_all_validators()

Get all validators.

get_block([block_nbr])

get_block_time()

Get the block time in format HH:MM:SS.ZZZZZZ.

get_blocks([before_id, after_id, order_by, …])

Get latest blocks or request specific blocks.

get_commitment_curve()

get_distribution_parameters()

get_inflation_start_time()

get_insurance_fund_balance()

get_latest_blocks()

get_liquidations(before_id, after_id, …)

get_liquidity_pools()

get_market(market)

Get information about a market.

get_market_stats([market])

Get statistics about one or all markets.

get_markets([market_type, is_active, is_settled])

Get all markets or filter markets.

get_nodes()

get_oracle_result(oracle_id)

get_oracle_results()

get_prices(market)

Get prices off a market.

get_reward_curve()

get_rich_list(token)

get_staking_pool()

get_status()

Return cosmos RPC status endpoint.

get_token(denom)

Get information about a token.

get_token_details()

get_tokens()

Get all known tokens on tradehub chain.

get_top_r_profits(market, limit)

get_total_balances()

get_transaction_types()

Get transaction types used by tradehub.

get_transactions_fees()

get_validator_delegations(operator_address)

get_validator_missed_blocks()

get_validator_public_node_ips()

get_validator_public_nodes()

get_validator_signing_info([limit])

get_validators([status])

get_vault_types()

param token

get_vaults(swth_address)

parse_validator_status(request_json, …)

Function to parse each peer’s JSON element and build information about each.

sentry_status_request([uri])

This function is here to ensure the nodes that have open network connections also have their persistence service running.

tradehub_get_request(path[, params])

This is a wrapper for the get request function to allow for retrying network calls on different available validators if a request fails.

tradehub_post_request(path[, data, …])

This is a wrapper for the post request function to allow for retrying network calls on different available validators if a request fails.

validator_crawler_mp()

Crawl the Tradehub Validators to test for available API endpoints.

validator_status_request(validator_ip)

Function that makes the network requests to the Tradehub validators across the network.

websocket_status_check(ip[, port])

Function to check if the websocket port is open for communication.

get_all_validators()List[dict][source]

Get all validators. This includes active, unbonding and unbonded validators.

Example:

public_client.get_all_validators()

The expected return result for this function is as follows:

[
    {
    "OperatorAddress":"swthvaloper1vwges9p847l9csj8ehrlgzajhmt4fcq4dmg8x0",
    "ConsPubKey":"swthvalconspub1zcjduepqcufdssqqfycjwz2srp42tytrs7gtdkkry9cpspea3zqsjzqd2tps73pr63",
    "Jailed":false,
    "Status":2,
    "Tokens":"22414566.55131922",
    "DelegatorShares":"22414566.55131922",
    "Description":{
        "moniker":"Devel & Co",
        "identity":"c572aef1818379c38996878357c321398165fcf0",
        "website":"https://gitlab.com/switcheo-utils",
        "security_contact":"",
        "details":"..."},
        "UnbondingHeight":0,
        "UnbondingCompletionTime":"1970-01-01T00:00:00Z",
        "Commission":{
            "commission_rates":{
                "rate":"0.004200000000000000",
                "max_rate":"0.200000000000000000",
                "max_change_rate":"0.010000000000000000"
            },
            "update_time":"2020-11-27T20:25:33.45991154Z"
        },
        "MinSelfDelegation":"1",
        "ConsAddress":"swthvalcons1pqnlj0na6k8u9y27j3elrx584mt3380dal0j9s",
        "ConsAddressByte":"0827F93E7DD58FC2915E9473F19A87AED7189DED",
        "WalletAddress":"swth1vwges9p847l9csj8ehrlgzajhmt4fcq4sd7gzl",
        "BondStatus":"bonded"
    },
    ...
]

Warning

The response from this endpoint uses different types off name conventions! For example ‘MinSelfDelegation’ and ‘max_change_rate’.

Warning

This endpoint returns numbers as string(eg. “volume”:”2100”) or integer(eg. “resolution”:5)

Returns

list with validators.

get_block(block_nbr: int = 1)[source]
get_block_time()str[source]

Get the block time in format HH:MM:SS.ZZZZZZ.

Example:

public_client.get_block_time()

The expected return result for this function is as follows:

"00:00:02.190211"

Warning

This endpoint returns only a string.

Returns

block time as string.

get_blocks(before_id: Optional[int] = None, after_id: Optional[int] = None, order_by: Optional[str] = None, swth_valcons: Optional[str] = None, limit: Optional[int] = None)List[dict][source]

Get latest blocks or request specific blocks.

Example:

public_client.get_blocks()

The expected return result for this function is as follows:

[
    {
        "block_height":"6103923",
        "time":"2021-01-09T14:15:53.071509+01:00",
        "count":"1",
        "proposer_address":"swthvalcons17m2ueqqqt8u0jz4rv5kvk4kg0teel4sckytjlc"
    },
    {
        "block_height":"6103922",
        "time":"2021-01-09T14:15:50.824548+01:00",
        "count":"0",
        "proposer_address":"swthvalcons1zecfdrf22f6syz8xj4vn8jsvsalxdhwl9tlflk"
    },
    ...
]

Warning

This endpoint is not well documented in official documents. The parameters are NOT required.

Parameters
  • before_id – Before block height(exclusive).

  • after_id – After block height(exclusive).

  • order_by – Not specified yet.

  • swth_valcons – Switcheo tradehub validator consensus starting with ‘swthvalcons1’ on mainnet and ‘tswthvalcons1’ on testnet.

  • limit – Limit the responded result. Values greater than 200 have no effect and a maximum off 200 results are returned.

Returns

List with found blocks matching the requested parameters. Can be empty list [].

get_commitment_curve()[source]
get_distribution_parameters()[source]
get_inflation_start_time()[source]
get_insurance_fund_balance()[source]

Warning

This endpoint is not working yet.

Returns

get_latest_blocks()[source]
get_liquidations(before_id: int, after_id: int, order_by: str, limit: int)[source]

Warning

This endpoint is not working yet.

Parameters
  • before_id

  • after_id

  • order_by

  • limit

Returns

get_liquidity_pools()[source]
get_market(market: str)dict[source]

Get information about a market.

Example:

public_client.get_market("swth_eth1")

The expected return result for this function is as follows:

{
     "type":"",
     "name":"swth_eth1",
     "display_name":"SWTH_ETH",
     "description":"SWTH/ETH Spot Market",
     "market_type":"spot",
     "base":"swth",
     "base_name":"Switcheo",
     "base_precision":8,
     "quote":"eth1",
     "quote_name":"Ethereum",
     "quote_precision":18,
     "lot_size":"1",
     "tick_size":"0.0000001",
     "min_quantity":"200",
     "maker_fee":"-0.0005",
     "taker_fee":"0.0025",
     "risk_step_size":"0",
     "initial_margin_base":"1",
     "initial_margin_step":"0",
     "maintenance_margin_ratio":"0",
     "max_liquidation_order_ticket":"0",
     "max_liquidation_order_duration":0,
     "impact_size":"0",
     "mark_price_band":0,
     "last_price_protected_band":0,
     "index_oracle_id":"",
     "expiry_time":"1970-01-01T01:00:00+01:00",
     "is_active":true,
     "is_settled":false,
     "closed_block_height":0,
     "created_block_height":0
 }

Warning

This endpoint is not well documented in official documents. The example market swth_eth does not exist on mainnet. The correct market ticker is ‘swth_eth1’. See get_markets() for correct tickers.

Warning

This endpoint returns numbers as string(eg. “lot_size”:”1”) or integer(eg. “base_precision”:8).

Warning

This endpoint returns the same dict structure even the market does not exist with default values!

Parameters

market – Market ticker used by blockchain (eg. swth_eth1).

Returns

get_market_stats(market: Optional[str] = None)List[dict][source]

Get statistics about one or all markets.

Example:

public_client.get_market_stats()

The expected return result for this function is as follows:

[
    {
        "day_high":"0.0000215",
        "day_low":"0.000021",
        "day_open":"0.0000211",
        "day_close":"0.0000212",
        "day_volume":"436030",
        "day_quote_volume":"9.2787298",
        "index_price":"0",
        "mark_price":"0",
        "last_price":"0.00212000",
        "market":"swth_eth1",
        "market_type":"spot",
        "open_interest":"0"
    }
    ...
]
Parameters

market – Market ticker used by blockchain (eg. swth_eth1).

Returns

List with market stats as dict

get_markets(market_type: Optional[str] = None, is_active: Optional[bool] = None, is_settled: Optional[bool] = None)List[dict][source]

Get all markets or filter markets.

Example:

public_client.get_markets()

The expected return result for this function is as follows:

[
    {
        "type":"",
        "name":"swth_eth1",
        "display_name":"SWTH_ETH",
        "description":"SWTH/ETH Spot Market",
        "market_type":"spot",
        "base":"swth",
        "base_name":"Switcheo",
        "base_precision":8,
        "quote":"eth1",
        "quote_name":"Ethereum",
        "quote_precision":18,
        "lot_size":"1",
        "tick_size":"0.0000001",
        "min_quantity":"200",
        "maker_fee":"-0.0005",
        "taker_fee":"0.0025",
        "risk_step_size":"0",
        "initial_margin_base":"1",
        "initial_margin_step":"0",
        "maintenance_margin_ratio":"0",
        "max_liquidation_order_ticket":"0",
        "max_liquidation_order_duration":0,
        "impact_size":"0",
        "mark_price_band":0,
        "last_price_protected_band":0,
        "index_oracle_id":"",
        "expiry_time":"1970-01-01T01:00:00+01:00",
        "is_active":true,
        "is_settled":false,
        "closed_block_height":0,
        "created_block_height":0
    },
    ...
]

Warning

This endpoint returns numbers as string(eg. “lot_size”:”1”) or integer(eg. “base_precision”:8)

Parameters
  • market_type – type of the market can be ‘futures’ or ‘spot’

  • is_active – if only active markets should be returned

  • is_settled – if only settled markets should be returned

Returns

List with returned market stats as dict

get_nodes()dict[source]
get_oracle_result(oracle_id: str)[source]

Warning

This endpoint is not working yet.

Parameters

oracle_id

Returns

get_oracle_results()[source]

Warning

This endpoint is not working yet.

Returns

get_prices(market: Optional[str])dict[source]

Get prices off a market.

Example:

public_client.get_prices("swth_eth1")

The expected return result for this function is as follows:

{
    "last":"207000",
    "index":"0",
    "fair":"0",
    "mark":"0",
    "mark_avg":"0",
    "settlement":"0",
    "fair_index_delta_avg":"0",
    "market":"",
    "marking_strategy":"",
    "index_updated_at":"0001-01-01T00:00:00Z",
    "last_updated_at":"2021-01-09T22:50:59.068526+01:00",
    "block_height":0
}

Warning

This endpoint is not well documented in official documents. Parameter ‘market’ is NOT required, but strongly recommended. The return result has an empty ‘market’ field.

Warning

This endpoint returns amounts which are NOT human readable values. Consider ‘base_precision’ and ‘quote_precision’ to calculate a multiplication factor = 10 ^ (‘base_precision’ - ‘quote_precision’)

Warning

This endpoint returns numbers as string(eg. “last”:”207000”) or integer(eg. “block_height”:0)

Warning

This endpoint returns a result even if the market is not known. Result contains default values.

Parameters

market – Market ticker used by blockchain (eg. swth_eth1).

Returns

Prices as dict

get_reward_curve()[source]
get_rich_list(token: str)[source]

Warning

This endpoint is not working yet.

Parameters

token

Returns

get_staking_pool()[source]
get_status()dict[source]

Return cosmos RPC status endpoint.

Example:

public_client.get_status()

The expected return result for this function is as follows:

{
  "jsonrpc": "2.0",
  "id": -1,
  "result": {
    "node_info": {
      "protocol_version": {
        "p2p": "7",
        "block": "10",
        "app": "0"
      },
      "id": "f4cee80e4dec5a686139cb82729118e15f7ce19c",
      "listen_addr": "tcp://0.0.0.0:26656",
      "network": "switcheo-tradehub-1",
      "version": "0.33.7",
      "channels": "4020212223303800",
      "moniker": "Devel Sentry Node 2",
      "other": {
        "tx_index": "on",
        "rpc_address": "tcp://0.0.0.0:26659"
      }
    },
    "sync_info": {
      "latest_block_hash": "4A2C89C105D7864AA74C9DE4752AF5B59E96045EBAF984C69DD447C4524EC36F",
      "latest_app_hash": "773651392EEDBFF6AEE088F76E7D75F2932B4D9F74CA27D568F706ADFC12B174",
      "latest_block_height": "6119142",
      "latest_block_time": "2021-01-09T22:18:52.722611018Z",
      "earliest_block_hash": "B4AF1F3D3D3FD5795BDDB7A6A2E6CA4E34D06338505D6EC46DD8F99E72ADCDAB",
      "earliest_app_hash": "",
      "earliest_block_height": "1",
      "earliest_block_time": "2020-08-14T07:32:27.856700491Z",
      "catching_up": false
    },
    "validator_info": {
      "address": "DCB03C204B7F94765B4ADCE1D8BEE88AA43AE811",
      "pub_key": {
        "type": "tendermint/PubKeyEd25519",
        "value": "1GmDSymN6jTqQlZA2KeyzqknIncGMMrwnnas/DWGNOI="
      },
      "voting_power": "0"
    }
  }
}
Returns

Status as dict

get_token(denom)dict[source]

Get information about a token.

Example:

public_client.get_token("swth")

The expected return result for this function is as follows:

{
    "name":"Switcheo",
    "symbol":"swth",
    "denom":"swth",
    "decimals":8,
    "blockchain":"neo",
    "chain_id":4,
    "asset_id":"32e125258b7db0a0dffde5bd03b2b859253538ab",
    "is_active":true,
    "is_collateral":false,
    "lock_proxy_hash":"17d0f66eca7fcbfddc8d9706f20513bf5d7419cd",
    "delegated_supply":"100000000000000000",
    "originator":"swth1mw90en8tcqnvdjhp64qmyhuq4qasvhy25dpmvw"
}

Warning

This endpoint returns numbers as string(eg. “delegated_supply”:”100000000000000000”) or integer(eg. “decimals”:8)

Parameters

denom – Denom used by tradehub.

Returns

Information about token as dict.

get_token_details()dict[source]
get_tokens()List[dict][source]

Get all known tokens on tradehub chain.

Example:

public_client.get_tokens()

The expected return result for this function is as follows:

[
    {
        "name":"Switcheo",
        "symbol":"swth",
        "denom":"swth",
        "decimals":8,
        "blockchain":"neo",
        "chain_id":4,
        "asset_id":"32e125258b7db0a0dffde5bd03b2b859253538ab",
        "is_active":true,
        "is_collateral":false,
        "lock_proxy_hash":"17d0f66eca7fcbfddc8d9706f20513bf5d7419cd",
        "delegated_supply":"100000000000000000",
        "originator":"swth1mw90en8tcqnvdjhp64qmyhuq4qasvhy25dpmvw"
    },
    ...
]

Warning

This endpoint returns numbers as string(eg. “delegated_supply”:”100000000000000000”) or integer(eg. “decimals”:8)

Returns

List with tokens as dict

get_top_r_profits(market: str, limit: int)[source]

Warning

This endpoint is not working yet.

Parameters
  • market

  • limit

Returns

get_total_balances()[source]

Warning

This endpoint is not working yet.

Returns

get_transaction_types()List[str][source]

Get transaction types used by tradehub.

Example:

public_client.get_transaction_types()

The expected return result for this function is as follows:

[
    "submit_proposal",
    "create_pool",
    "set_reward_curve",
    "send",
    ...
]
Returns

List with transaction types as strings.

get_transactions_fees()[source]
get_validator_delegations(operator_address)[source]
get_validator_missed_blocks()[source]
get_validator_public_node_ips()[source]
get_validator_public_nodes()[source]
get_validator_signing_info(limit: int = 100)[source]
get_validators(status: Optional[str] = None)[source]
get_vault_types()list[source]
Parameters

token

:return :

get_vaults(swth_address: str)dict[source]
parse_validator_status(request_json: dict, validator_ip: str)

Function to parse each peer’s JSON element and build information about each.

Execution of this function is as follows:

parse_validator_status(request_json='/status', validator_ip='54.255.5.46')

The expected return result for this function is as follows:

{
    'moniker': 'spock',
    'id': 'ca1189045e84d2be5db0a1ed326ce7cd56015f11',
    'ip': '54.255.5.46',
    'version': '0.33.7',
    'network': 'switcheo-tradehub-1',
    'latest_block_hash': 'DF194D43058D3CD89DD98A7DA28164B239B9693C822A1DB16CCC27FB49CA587B',
    'latest_block_height': '7995864',
    'latest_block_time': '2021-02-27T19:51:00.162091183Z',
    'earliest_block_height': '1',
    'earliest_block_time': '2020-08-14T07:32:27.856700491Z',
    'catching_up': False,
    'validator_address': '7091A72888509B3F3069231081621DC988D63542',
    'validator_pub_key_type': 'tendermint/PubKeyEd25519',
    'validator_pub_key': 'epMp0h65WflL7r8tPGQwusVMbCHgy7ucRg8eDlEJPW0=',
    'validator_voting_power': '0'
}
Parameters
  • request_json – Dictionary of the return response from the validator status request.

  • validator_ip – String of the IP address to connect to.

Returns

Dictionary of validator information.

sentry_status_request(uri: bool = False)

This function is here to ensure the nodes that have open network connections also have their persistence service running. Many times the network connection is open for communication but the persistence service will not be on.

Execution of this function is as follows:

sentry_status_request(uri=True)
Parameters

uri – Bool value for a URI or IP address.

tradehub_get_request(path: str, params: Optional[dict] = None)

This is a wrapper for the get request function to allow for retrying network calls on different available validators if a request fails.

Execution of this function is as follows:

tradehub_get_request(path='/txs')
Parameters
  • path – String of the path being used for the network request that is going to be made.

  • params – Dict values that will added to the get request.

Returns

Dictionary of the return request based on the network path sent.

tradehub_post_request(path: str, data: Optional[dict] = None, json_data: Optional[dict] = None, params: Optional[dict] = None)

This is a wrapper for the post request function to allow for retrying network calls on different available validators if a request fails.

Execution of this function is as follows:

tradehub_post_request(path='/txs')
Parameters
  • path – String of the path being used for the network request that is going to be made.

  • data – Dict values that will added to the post request.

  • json_data – Dict values that will added to the post request.

  • params – Dict values that will added to the post request.

Returns

Dictionary of the return request based on the network path sent.

validator_crawler_mp()

Crawl the Tradehub Validators to test for available API endpoints.

Execution of this function is as follows:

validator_crawler_mp()
validator_status_request(validator_ip: str)

Function that makes the network requests to the Tradehub validators across the network.

Execution of this function is as follows:

validator_status_request(validator_ip='54.255.5.46')

The expected return result for this function is as follows:

{
    'moniker': 'spock',
    'id': 'ca1189045e84d2be5db0a1ed326ce7cd56015f11',
    'ip': '54.255.5.46',
    'version': '0.33.7',
    'network': 'switcheo-tradehub-1',
    'latest_block_hash': 'DF194D43058D3CD89DD98A7DA28164B239B9693C822A1DB16CCC27FB49CA587B',
    'latest_block_height': '7995864',
    'latest_block_time': '2021-02-27T19:51:00.162091183Z',
    'earliest_block_height': '1',
    'earliest_block_time': '2020-08-14T07:32:27.856700491Z',
    'catching_up': False,
    'validator_address': '7091A72888509B3F3069231081621DC988D63542',
    'validator_pub_key_type': 'tendermint/PubKeyEd25519',
    'validator_pub_key': 'epMp0h65WflL7r8tPGQwusVMbCHgy7ucRg8eDlEJPW0=',
    'validator_voting_power': '0',
    'validator_status': 'Active',
    'connected_nodes': [
        {
            'node_id': 'd57a64f41487b5e421e91b71dceb0784cae57733',
            'node_ip': '195.201.82.228',
            'node_full': 'd57a64f41487b5e421e91b71dceb0784cae57733@195.201.82.228'
        },
        ...
    ]
}
Parameters

validator_ip – String of the IP address to connect to.

Returns

Dictionary of validators that the crawler has found with the status.

websocket_status_check(ip: str, port: int = 5000)

Function to check if the websocket port is open for communication. This is called as part of the sentry check because calling the websocket also requires the persistence service to be available.

Execution of this function is as follows:

websocket_status_check(ip='54.255.5.46', port=5000)
Parameters
  • ip – String of the IP address to connect to.

  • port – Int value for the port to be checked.