xchainpy_client 0.1
A specification for a generalised interface for crypto wallets clients, to be used by XChainPY implementations

# 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 MAINNET)
* 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(XChainClient) 
```
## 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)
```
Returns the client. 

## 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 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
# Defined in xchainpy-client/models/balance.py
class Balance:
    _asset = None # Asset
    _amount = 0

    def __init__(self, asset, amount):
        """
        :param asset: asset type
        :type asset: Asset
        :param amount: amount 
        :type amount: str
        """
        self._asset = asset
        self._amount = amount

    @property
    def asset(self):
        return self._asset

    @asset.setter
    def asset(self, asset):
        self._asset = asset

    @property
    def amount(self):
        return self._amount

    @amount.setter
    def amount(self, amount):
        self._amount = amount
```

```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:
```json
[
  { 
    "asset" : "BTC.BTC"
    "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

    @property
    def address(self):
        return self._address

    @address.setter
    def address(self, address):
        self._address = address


    @property
    def offset(self):
        return self._offset

    @offset.setter
    def offset(self, offset):
        self._offset = offset

    @property
    def limit(self):
        return self._limit

    @limit.setter
    def limit(self, limit):
        self._limit = limit

    @property
    def start_time(self):
        return self._start_time

    @start_time.setter
    def start_time(self, start_time):
        self._start_time = start_time

    @property
    def asset(self):
        return self._asset

    @asset.setter
    def asset(self, asset):
        self._asset = asset

get_transactions(params: TxHistoryParams):{total : str , tx:list}
```

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:
```json
[
  { 
    "hash" : "980D9519CCB39DC02F8B0208A4D181125EE8A2678B280AF70666288B62957DAE",
    "from" : "34xp4vRoCGJym3xR7yCVPFHoCNxv4Twseo",
    "to" : 34vRoCGJym3xR7yCVPFHoCNxv4Twseoxp4,
    "amount": 100000000,
    "asset" : "BTC.BTC",
    "fee" : 2500,
    "memo" : "transfer"
    "date" : "2020-10-04T06:24:36.548Z"
   },
   { 
    "hash" : "0D9519CCB39DC02F8B0208A4D181125EE8A2678B280AF70666288B62957DAE98",
    "from" : "34xp4vRoCGJym3xR7yCVPFHoCNxv4Twseo",
    "to" : 34vRoCGJym3xR7yCVPFHoCNxv4Twseoxp4,
    "amount": 200000000,
    "asset" : "BTC.BTC",
    "fee" : 2500,
    "memo" : "transfer"
    "date" : "2020-10-04T06:24:36.548Z"
   },
]
```

> 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

All models defined in xchainpy-client/models/tx_types.py

TX model:
```python
class TX:
    def __init__(self, asset: Asset, tx_froms, tx_tos, tx_date, tx_type:str, tx_hash:str):
        self._asset = asset
        self._tx_from = tx_froms # list of "to" txs. BNC will have one `TxFrom` only, `BTC` might have many transactions going "in" (based on UTXO)
        self._tx_to = tx_tos # list of "to" transactions. BNC will have one `TxTo` only, `BTC` might have many transactions going "out" (based on UTXO)
        self._tx_date = tx_date
        self._tx_type = tx_type
        self._tx_hash = tx_hash

    @property
    def asset(self):
        return self._asset

    @asset.setter
    def asset(self, asset):
        self._asset = asset

    @property
    def tx_from(self):
        return self._tx_from

    @tx_from.setter
    def tx_from(self, tx_from):
        self._tx_from = tx_from

    @property
    def tx_to(self):
        return self._tx_to

    @tx_to.setter
    def tx_to(self, tx_to):
        self._tx_to = tx_to

    @property
    def tx_date(self):
        return self._tx_date

    @tx_date.setter
    def tx_date(self, tx_date):
        self._tx_date = tx_date

    @property
    def tx_type(self):
        return self._tx_type

    @tx_type.setter
    def tx_type(self, tx_type):
        self._tx_type = tx_type

    @property
    def tx_hash(self):
        return self._tx_hash

    @tx_hash.setter
    def tx_hash(self, tx_hash):
        self._tx_hash = tx_hash
```

TX_to model : 
```python
class TxTo:
    def __init__(self, address, amount):
        self._address = address
        self._amount = amount

    @property
    def address(self):
        return self._address

    @address.setter
    def address(self, address):
        self._address = address


    @property
    def amount(self):
        return self._amount

    @amount.setter
    def amount(self, amount):
        self._amount = amount
```

TX_from model:
```python
class TxFrom:
    def __init__(self, address, amount):
        self._address = address
        self._amount = amount

    @property
    def address(self):
        return self._address

    @address.setter
    def address(self, address):
        self._address = address


    @property
    def amount(self):
        return self._amount

    @amount.setter
    def amount(self, amount):
        self._amount = amount
```

## 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:
https://bitcoinfees.earn.com/api/v1/fees/recommended
for more information about it go to https://bitcoinfees.earn.com/api


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


```python
get_fees(): {fastest: float  , fast : float , average : float}
```

## 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://sochain.com/api/v2/send_tx/BTC
with body : {"tx_hex":"<TX_HEX>"}

https://dex.binance.org/api/v1/broadcast
```

```python
transfer(amount, recipient, memo: str = None, fee_rate=None) -> 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 `this.phrase = ''` 

```python
purge_client()
```