xchainpy-client 0.1.6
A specification for a generalised interface for crypto wallets clients, to be used by XChainPY implementations. The client should not have any functionality to generate a key, instead, the `asgardex-crypto` library should be used to ensure cross-chain com
License: MIT
Keywords: THORChain,XChainpy,xchainpy_client

# XChainPy Wallet Client Interface

A specification for a generalised interface for crypto wallets clients, to be used by XChainPy
implementations. The client should not have any functionality to generate a key, instead, the `asgardex-crypto` library should be used to ensure cross-chain compatible keystores are handled. The client is only ever passed a master BIP39 phrase, from which a temporary key and address is decoded. 

### Configuration
Initialise and set up the client to connect to its necessary third-party services to fulfil basic functionality. The third-party services used must be at a minimum to fulfil the wallet functionality, such as displaying balances and sending transactions. 

During configuration, the following can be passed in:
* Network choice (default is TESTNET)
* Phrase (mandatory)
* Service Keys (optional, if null, client will use config defaults or free service limits.)

### Querying
Querying the client for balances and transaction history. Transaction history is optional. 

Optional blockchain-specific queries can be added here, such as Binance Chain market information.

### Transactions
Making transfers.

Optional blockchain-specific transactions can be added here, such as Binance Chain freeze/unfreeze.

---- 

# Class Variables

## Client
Client Implementation
```python
class client(IXChainClient) 
```
## Network
Network types are `'mainnet'` and `'testnet'` strings

## Address
Public variable that returns the address decoded from the private key during initialisation. type of address is `str`

# Config and Setup

## Set Network
Used to set a type of `Network`, which is either `'mainnet'` or `'testnet'`. 

```python
set_network(net:str)
```
## Set Phrase
Used to set the master BIP39 phrase, from which the private key is extracted and the address decoded.
```python
set_phrase(phrase:str) -> str
```
The function should store the private key and address, then return the address generated by the phrase. 

---- 

# Querying

## Get Explorer URLs

Returns the correctly formatted url string with paths for:

- Addresses
- Transactions

The default Explorer URL can be hard-coded, or passed in as a service. It will be provided by `get_explorer_url`

```python
get_explorer_url() -> str
```

To get explorer's URL for an address, use `get_explorer_address_url` by passing an `address`.

```python
get_explorer_address_url = (address:str) -> str
```

To get explorer's URL for a transaction, use `get_explorer_tx_url` by passing a transaction ID.

```python
get_explorer_tx_url = (tx_id:str) -> str
```

All functions should return the correctly formatted url string.

**Example**

```
https://blockchair.com/bitcoin/transaction/d11ff3352c50b1f5c8e2030711702a2071ca0e65457b40e6e0bcbea99e5dc82e
https://blockchair.com/bitcoin/address/19iqYbeATe4RxghQZJnYVFU4mjUUu76EA6

https://explorer.binance.org/tx/94F3A6257337052B04F9CC09F657966BFBD88546CA5C23F47AB0A601D29D8979
https://explorer.binance.org/address/bnb1z35wusfv8twfele77vddclka9z84ugywug48gn

https://etherscan.io/tx/0x87a4fa498cc48874631eaa776e84a49d28f42f01e22c51ff7cdfe1f2f6772f67
https://etherscan.io/address/0x8eb68e8f207be3dd1ec4baedf0b5c22245cda463
```


## Get Balance
Returns the balance of an address. 
* If address is not passed, gets the balance of the current client address. 
* Optional asset can be passed, in which the query will be specific to that asset, such as ERC-20 token. 
* Returns an array of assets and amounts, with assets in chain notation `CHAIN.SYMBOL-ID`

Balance model :
```python
get_balance(address:str=None, asset:str=None) -> Balance
```

Example of third-party service queries to get balances:
```
https://sochain.com/api/v2/get_address_balance/BTCTEST/tb1q2pkall6rf6v6j0cvpady05xhy37erndvku08wp
https://api.ethplorer.io/getAddressInfo/0xb00E81207bcDA63c9E290E0b748252418818c869?apiKey=freekey
https://dex.binance.org/api/v1/account/bnb1jxfh2g85q3v0tdq56fnevx6xcxtcnhtsmcu64m
```
Example of returned array:
```python
[
   {   # xchainpy_client.models.balance.Balance
      asset: {  # xchainpy_util.asset.Asset
         chain: "BNB",
         symbol: "BNB",
         ticker: "BNB"
      },
      amount: 100000000
   }
]
```

## Get Transactions
Gets a simplied array of recent transactions for an address. 
```python
# Defined in xchainpy_client/models/tx_types.py
 class TxHistoryParams:
    def __init__(self, address:str, offset:int=None, limit:int=None, start_time=None, asset:Asset=None):
        self._address = address
        self._offset = offset
        self._limit = limit
        self._start_time = start_time
        self._asset = asset


get_transactions(params:TxHistoryParams) -> xchainpy_client.models.tx_types.TxPage
```

Example of third party services to help:
```
// get UTXOS for address
https://sochain.com/api/v2/get_tx_unspent/BTC/34xp4vRoCGJym3xR7yCVPFHoCNxv4Twseo
// get tx details
https://sochain.com/api/v2/get_tx/BTC/ff0bd969cce99b8d8086e452d7b63167fc178680fee796fc742cb14a9a6ef929

https://api.ethplorer.io/getAddressTransactions/0xb297cacf0f91c86dd9d2fb47c6d12783121ab780?apiKey=freekey
https://dex.binance.org/api/v1/transactions?address=bnb1jxfh2g85q3v0tdq56fnevx6xcxtcnhtsmcu64m
```

Example of return:
```python
[ # xchainpy_client.models.tx_types.TxPage
    total: 1,
    txs: [
        {  # # xchainpy_client.models.tx_types.TX
        tx_hash: "980D9519CCB39DC02F8B0208A4D181125EE8A2678B280AF70666288B62957DAE",
        tx_from: [ # xchainpy_client.models.tx_types.TxFrom
            {
                address: "tbnb1t95kjgmjc045l2a728z02textadd98yt339jk7",
                amount: 100
            }
        ],
        tx_to: [ # xchainpy_client.models.tx_types.TxTo
            {
                address: "tbnb1t95kjgmjc045l2a728z02textadd98yt339jk7",
                amount: 100
            }
        ],
        tx_amount: 100,
        tx_fee: 2500,
        tx_memo: "transfer"
        tx_date: datetime.datetime(2021, 8, 2, 12, 50, 10, 407000),
        asset: {  # xchainpy_util.asset.Asset
             chain: "BNB",
             symbol: "BNB",
             ticker: "BNB"
        },
       }
    ]
]
```

> Due to the complexity of this function and dependence of third-party services, this function can be omitted in early versions of the client. 

---- 

# Transactions

## Get Fees
This function calculates and returns the fee object in a generalised way for a simple transfer function. 

Since this depends on optional third-party services, sensible defaults should be hardcoded if there are errors.

The fastest fee rate should be guaranteed next block (1.5x Fast), fast should be 1-2 blocks (1x next block fee rate), average should be 2-3 blocks (0.5x Fast). 
*Don't over-complicate this. PoW blockchains have no guarantees.* 

* Type should specify the units to display, or if flat fees, simply "flat". The client should interpret and display this, such as showing the user the fee rates and their units.
* Fastest (target of next block)
* Fast (target of 1-2 blocks)
* Average (target of 2-3 blocks)

Third party services:
Bitcoin - returns next block feeRate (fast). Use multiples of this to extrapolate to Fastest/Average.
https://api.blockchair.com/bitcoin/stats

Ethereum - returns fastest/fast/average
https://ethgasstation.info/api/ethgasAPI.json?api-key=XXAPI_Key_HereXXX


```python
get_fees() -> xchainpy_client.models.types.Fees
```


**Example**

```python
# Binance Chain
{ # xchainpy_client.models.types.Fees
  fastest : 0.0001125
  fast : 0.0001125
  average : 0.0001125
}
```

## Transfer
General transfer function that should be signed and broadcast using a third party service. 
The fee should always be *rate*, which is units per transaction size. The size should be calculated on the fly or hardcoded:

* Bitcoin: 250 bytes is typical, so feeRate of 10 is 10 sats per byte, eg, 2500 sats 
* Ethereum: gwei is standard, so a feeRate of 20 would be interpreted as 20 GWEI 
* Binance Chain: fixed size, so the feeRate is ignored. 

**Broadcast URLs**

```
https://api.blockchair.com/{:chain}/push/transaction
https://dex.binance.org/api/v1/broadcast
```

```python
class TxParams:
    def __init__(self, asset:Asset, amount, recipient, memo='', wallet_index=None):
        self._asset = asset
        self._amount = amount
        self._recipient = recipient
        self._memo = memo
        self._wallet_index = wallet_index

transfer(params:tx_types.TxParams) -> str
```

The function should return the hash of the finalised transaction.

## Purge
When a wallet is "locked" the private key should be purged in each client by setting it back to null. Also the phrase has to be cleared `self.phrase = ''` 

```python
purge_client()
```