# How to Use

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

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

### Peer Dependencies

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

### Extras <a href="#extras" id="extras"></a>

Important note: Make sure to install same version of cosmos-client/core as xchain-cosmos is using (currently "@cosmos-client/core": "^0.45.1", ). In other case things might break.

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

```
yarn install
yarn test
```

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

#### Connect Wallet to New Cosmos Client <a href="#connect-wallet-to-new-cosmos-client" id="connect-wallet-to-new-cosmos-client"></a>

Create a new thorchain client\
Set `phrase` and `network` when creating an instance.\
The network default is Mainnet

```

//Imports
import { AssetAtom, Client, COSMOS_DECIMAL } from "@xchainjs/xchain-cosmos"
import { assetToBase, baseToAsset, assetAmount } from "@xchainjs/xchain-util"

// Create new instance of the client and query chain for balances.
const connectWallet = async () => {
    let phrase = "phrase"
    const cosmosClient = new Client({phrase})
    let address = cosmosClient.getAddress()
    let isValid = cosmosClient.validateAddress(address)
    console.log(address)
    if(isValid === true){
        try {
            const balance = await cosmosClient.getBalance(address)
            let assetAmount = (baseToAsset(balance[0].amount)).amount()
            console.log(`Adress: ${address} with balance ${assetAmount}`)
            
        } catch (error) {
            console.log(`Caught: ${error} `)
        }
    } else {
        console.log(`Address: ${address} is invalid`)
    }
}

```

#### Transfer ATOM using Cosmos Client <a href="#transfer-atom-using-cosmos-client" id="transfer-atom-using-cosmos-client"></a>

Create a new Cosmos client instance\
Convert amount to transfer to base amount\
Build transaction.

```
const transfer = async () => {
    let phrase = "phrase"
    const cosmosclient = new Client({ phrase})
    let amountToTransfer = 0.1
    let amount = assetToBase(assetAmount(amountToTransfer, COSMOS_DECIMAL))
    let recipient = "cosmos1f2hzu2cup9tk427w5tpfysvx9cf4c9wkud0qn9" 
    try {
        const txid = await cosmosclient.transfer({
            "amount": amount,
            "recipient": recipient,
            "memo": "test",
            "asset": AssetAtom,
            "walletIndex": 0 
        })
        console.log(`Transaction sent: ${JSON.stringify(txid)}`)
    } catch (error) {
        console.log(`Caught ${error}`)
    }
}

// Transfer with fee rate set 
    let feeRate = await cosmosClient.getFeeRates()
    try {
        const txid = await cosmosClient.transfer({
            "amount": amount,
            "recipient": recipient,
            "memo": "test",
            "asset": AssetAtom,
            feeRate: feeRate.fastest
        })
        console.log(`Transaction sent: ${txid}`)

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

```

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

Retrieve transaction data using transaction hash and address

```

const transactionData = async () => {
    let txHash = 'insert txHash'
    let phrase = "phrase"
    const cosmosClient = new Client({ phrase})
    try {
        const txData = await cosmosClient.getTransactionData(txHash)
        console.log(`From ${JSON.stringify(txData)}`)
    } catch (error) {
        console.log(`Caught ${error}`)
    }
}

// By default getTransactions() returns the transactions for the current address

const transactionHistory = async () => {
    let phrase = "phrase"
    const cosmosClient = new Client({phrase})
    const address = cosmosClient.getAddress()
    const url = cosmosClient.getExplorerUrl()
    console.log(url)
    try {
        const txHistory = await cosmosClient.getTransactions()
        console.log(`Found ${txHistory.total.toString()}`)
        txHistory.txs.forEach(tx => console.log(tx.hash))   
    } catch (error) {
        console.log(`Caught: ${error}`)
    }
}
```

#### Get Transfer Fees <a href="#get-transfer-fees" id="get-transfer-fees"></a>

```
const feeData = async () => {
    let phrase = "phrase"
    const cosmosClient = new Client({ phrase})
    try {
        const {fast, fastest, average} = await cosmosClient.getFees()
        console.log(`Fees Fast: ${baseToAsset(fast).amount()} Fastest: ${baseToAsset(fastest).amount()} Average: ${baseToAsset(average).amount()}`)
    } catch (error) {
        console.log(`Caught ${error}`)
    }
}

```

#### Get Network and Explorer Data <a href="#get-network-and-explorer-data" id="get-network-and-explorer-data"></a>

```
// Query Cosmos client for network data and explorer data

const explorerUrl = async () => {
    let phrase = "phrase"
    const cosmosClient = new Client({ phrase})
    let hash = "insert hash"
    try {
        const networkData = cosmosClient.getExplorerUrl()
        console.log(`Explorer url: ${networkData}`)
        const transactionUrl = cosmosClient.getExplorerTxUrl(hash)
        console.log(`Explorer transaction: ${transactionUrl}`)

    } catch (error) {
        console.log(`Caught ${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-cosmos-sdk/xchain-cosmos/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.
