# How to use

## Installation <a href="#installation" id="installation"></a>

```
yarn add @xchainjs/xchain-bitcoin
```

### Peer Dependencies

You can visit the [xchain-bitcoin](https://github.com/xchainjs/xchainjs-lib/blob/master/packages/xchain-bitcoin/package.json) package repository to get the updated peer dependencies by looking at the "peerDependencies" object in the "package.json" file.

### Testing <a href="#bitcoin-client-testing" id="bitcoin-client-testing"></a>

```
yarn install
yarn test
```

## Examples <a href="#basic-usage-examples" id="basic-usage-examples"></a>

#### Connect Wallet to New Client and Access Class Methods <a href="#connect-wallet-to-new-client-and-access-class-methods" id="connect-wallet-to-new-client-and-access-class-methods"></a>

Decrypt keystore returns `phrase`\
Create a new client instance\
Use the client to getAddress() & getBalance() of address\
The network default is Mainnet

```
//Imports
import { Client } from "@xchainjs/xchain-bitcoin"

// Connect wallet to new btc client 
const connectWallet = async () => {
    let phrase = "phrase"
    const btcClient = new Client({ phrase})
    let address = btcClient.getAddress()     
    console.log(`Asset Address is: ${address}`)

    let balances = await btcClient.getBalance(address)
    try { 
        let assetAmount = (baseToAsset(balances[0].amount)).amount()
        console.log(`Asset address balance: ${assetAmount}`)
    } catch (error) {
        console.log('Address has no balance')
    }
}
```

#### Transfer BTC Using btcClient <a href="#transfer-btc-using-btcclient" id="transfer-btc-using-btcclient"></a>

Default feeRate is `fast`\
Import helper functions from `@xchainjs/xchain-util`\
Decrypt keystore to retrieve a phrase\
Use utils to convert to BaseAmount for tx params\
Build TX using parameters\
Client.transfer() > returns `Promise<string>` - The transaction hash

```
//Imports
import { assetToBase, baseToAsset, assetAmount, AssetBTC } from "@xchainjs/xchain-util"

let amountToTransfer = 0.0001
let recipient = 'Recipent_address'

const transfer = async () => {
    let phrase = "phrase"
    let btcClient = new Client({phrase })
    let amount = assetToBase(assetAmount(amountToTransfer, 8))
    try {
        const txid = await btcClient.transfer({
            'asset': AssetBTC,
            'recipient': recipient,
            'amount': amount,
            'memo': "payment"
        })
        console.log(`Amount: ${amount.amount().toString()} ${AssetBTC.symbol} Transaction id: ${txid}`)
    } catch (error){
        console.log(`Transfer failed ${error}`)
    }
}

```

#### Transfer & Set feeRate <a href="#transfer--set-feerate" id="transfer--set-feerate"></a>

Build transactions using parameters\
Set feeRate in transaction parameters\
Or use getFeeRates()

```
//Returns FeeRates > this allows for dynamic feeRate adjustment on selection
const { fast, fastest, average } = await btcClient.getFeeRates()

try {
        const txid = await btcClient.transfer({
            'asset': AssetBTC,
            'recipient': recipient,
            'amount': amount,
            'memo': "test transfer",
            feeRate: fast
        })
        console.log(`Amount ${baseToAsset(amount).amount()} ${AssetBTC.symbol} Transaction id ${txid}`)
    } catch (error){
        console.log(`Transfer failed ${error}`)
    }
```

#### Get Fees & FeeRates Estimations <a href="#get-fees--feerates-estimations" id="get-fees--feerates-estimations"></a>

Client function getFees() returns an object\
`Fast: {"type":"BASE","decimal":8}`

```
//Get Fees - returns FeeOption & fee in BaseAmount 
` Fees Fast: 0.00001 Fastest: 0.0000468 Average: 0.00001 `
    try{
        const { fast, fastest, average } = await btcClient.getFees()
        console.log(`Fees Fast: ${baseToAsset(fast).amount()} Fastest: ${baseToAsset(fastest).amount()} Average: ${baseToAsset(average).amount()}`)

    }catch (error){
        console.log(error)
    }

//Get FeeRates - returns FeeOption & rate  
` Fast: 12, Fastest 60, Average: 6 `

    try{
        const { fast, fastest, average } = await btcClient.getFeeRates()
        console.log(`Fast: ${fast}, Fastest ${fastest}, Average: ${average}`)

    }catch (error){
        console.log(error)
    }

```

#### Get Transaction Data <a href="#get-transaction-data" id="get-transaction-data"></a>

Create a new btcClient instance\
Call getTransaction(hash) returns JSON object

```
const transactionData = async () => {
    let phrase = "phrase"
    let btcClient = new Client({network: Network.Mainnet, phrase })
    let hash = "txhash string" 
    try{
        const txData = await btcClient.getTransactionData(hash)
        console.log(`From ${JSON.stringify(txData)}`)

    }catch (error) {
        console.log(`Error: ${error}`)
    }
}

```

#### Get Transaction History <a href="#get-transaction-history" id="get-transaction-history"></a>

Search the client for transaction history\
Create a new client instance\
Call a function with a variable `address`\
Results can be filtered with extra parameters { offset, limit, startTime, asset?}

```
const transactionHistory = async () => {
    let phrase = "phrase"
    let btcClient = new Client({phrase })
    let Address = keystore1Address

    try {
        const txHistory = await btcClient.getTransactions({ address: Address, limit: 4 })
        console.log(`Found ${txHistory.total.toString()}`)
        txHistory.txs.forEach(tx => console.log(tx.hash))

    } catch (error) {
            console.log(`Error: ${error}`)
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://xchainjs.gitbook.io/xchainjs/clients/xchain-utxo/xchain-bitcoin/how-to-use.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
