<!--
order: 1
-->

# Gaia Client

## Gaia CLI

`gaiacli` is the tool that enables you to interact with the node that runs on the Cosmos Hub network, whether you run it yourself or not. Let us set it up properly. In order to install it, follow the [installation procedure](../gaia-tutorials/installation.md).

### Setting up gaiacli

The main command used to set up `gaiacli` is the following:

```bash
gaiacli config <flag> <value>
```

It allows you to set a default value for each given flag.

First, set up the address of the full-node you want to connect to:

```bash
gaiacli config node <host>:<port>

# example: gaiacli config node https://77.87.106.33:26657
```

If you run your own full-node, just use `tcp://localhost:26657` as the address.

Then, let us set the default value of the `--trust-node` flag:

```bash
gaiacli config trust-node true

# Set to true if you trust the full-node you are connecting to, false otherwise
```

Finally, let us set the `chain-id` of the blockchain we want to interact with:

```bash
gaiacli config chain-id cosmoshub-2
```

### Keys

#### Key Types

There are three types of key representations that are used:

- `cosmos`
  - Derived from account keys generated by `gaiacli keys add`
  - Used to receive funds
  - e.g. `cosmos15h6vd5f0wqps26zjlwrc6chah08ryu4hzzdwhc`

* `cosmosvaloper`
  - Used to associate a validator to it's operator
  - Used to invoke staking commands
  - e.g. `cosmosvaloper1carzvgq3e6y3z5kz5y6gxp3wpy3qdrv928vyah`

- `cosmospub`
  - Derived from account keys generated by `gaiacli keys add`
  - e.g. `cosmospub1zcjduc3q7fu03jnlu2xpl75s2nkt7krm6grh4cc5aqth73v0zwmea25wj2hsqhlqzm`
- `cosmosvalconspub`
  - Generated when the node is created with `gaiad init`.
  - Get this value with `gaiad tendermint show-validator`
  - e.g. `cosmosvalconspub1zcjduepq0ms2738680y72v44tfyqm3c9ppduku8fs6sr73fx7m666sjztznqzp2emf`

#### Migrate Keys From Legacy On-Disk Keybase To OS Built-in Secret Store

Older versions of `gaiacli` used store keys in the user's home directory. If you are migrating
from an old version of `gaiacli` you will need to migrate your old keys into your operating system's
credentials storage by running the following command:

```bash
gaiacli keys migrate
```

The command will prompt for every passphrase. If a passphrase is incorrect, it will skip the
respective key.

#### Generate Keys

You'll need an account private and public key pair \(a.k.a. `sk, pk` respectively\) to be able to receive funds, send txs, bond tx, etc.

To generate a new _secp256k1_ key:

```bash
gaiacli keys add <account_name>
```

The output of the above command will contain a _seed phrase_. It is recommended to save the _seed
phrase_ in a safe place so that in case you forget the password of the operating system's
credentials store, you could eventually regenerate the key from the seed phrase with the
following command:

```bash
gaiacli keys add --recover
```

If you check your private keys, you'll now see `<account_name>`:

```bash
gaiacli keys show <account_name>
```

View the validator operator's address via:

```shell
gaiacli keys show <account_name> --bech=val
```

You can see all your available keys by typing:

```bash
gaiacli keys list
```

View the validator pubkey for your node by typing:

```bash
gaiad tendermint show-validator
```

Note that this is the Tendermint signing key, _not_ the operator key you will use in delegation transactions.

::: danger Warning
We strongly recommend _NOT_ using the same passphrase for multiple keys. The Tendermint team and the Interchain Foundation will not be responsible for the loss of funds.
:::

#### Generate Multisig Public Keys

You can generate and print a multisig public key by typing:

```bash
gaiacli keys add --multisig=name1,name2,name3[...] --multisig-threshold=K new_key_name
```

`K` is the minimum number of private keys that must have signed the
transactions that carry the public key's address as signer.

The `--multisig` flag must contain the name of public keys that will be combined into a
public key that will be generated and stored as `new_key_name` in the local database.
All names supplied through `--multisig` must already exist in the local database. Unless
the flag `--nosort` is set, the order in which the keys are supplied on the command line
does not matter, i.e. the following commands generate two identical keys:

```bash
gaiacli keys add --multisig=foo,bar,baz --multisig-threshold=2 multisig_address
gaiacli keys add --multisig=baz,foo,bar --multisig-threshold=2 multisig_address
```

Multisig addresses can also be generated on-the-fly and printed through the which command:

```bash
gaiacli keys show --multisig-threshold K name1 name2 name3 [...]
```

For more information regarding how to generate, sign and broadcast transactions with a
multi signature account see [Multisig Transactions](#multisig-transactions).

### Tx Broadcasting

When broadcasting transactions, `gaiacli` accepts a `--broadcast-mode` flag. This
flag can have a value of `sync` (default), `async`, or `block`, where `sync` makes
the client return a CheckTx response, `async` makes the client return immediately,
and `block` makes the client wait for the tx to be committed (or timing out).

It is important to note that the `block` mode should **not** be used in most
circumstances. This is because broadcasting can timeout but the tx may still be
included in a block. This can result in many undesirable situations. Therefore, it
is best to use `sync` or `async` and query by tx hash to determine when the tx
is included in a block.

### Fees & Gas

Each transaction may either supply fees or gas prices, but not both.

Validator's have a minimum gas price (multi-denom) configuration and they use
this value when when determining if they should include the transaction in a block during `CheckTx`, where `gasPrices >= minGasPrices`. Note, your transaction must supply fees that are greater than or equal to **any** of the denominations the validator requires.

**Note**: With such a mechanism in place, validators may start to prioritize
txs by `gasPrice` in the mempool, so providing higher fees or gas prices may yield higher tx priority.

e.g.

```bash
gaiacli tx send ... --fees=50000uatom
```

or

```bash
gaiacli tx send ... --gas-prices=0.025uatom
```

### Account

#### Get Tokens

On a testnet, getting tokens is usually done via a faucet.

#### Query Account Balance

After receiving tokens to your address, you can view your account's balance by typing:

```bash
gaiacli query account <account_cosmos>
```

::: warning Note
When you query an account balance with zero tokens, you will get this error: `No account with address <account_cosmos> was found in the state.` This can also happen if you fund the account before your node has fully synced with the chain. These are both normal.

:::

### Send Tokens

The following command could be used to send coins from one account to another:

```bash
gaiacli tx send <sender_key_name_or_address> <recipient_address> 10faucetToken \
  --chain-id=<chain_id>
```

::: warning Note
The `amount` argument accepts the format `<value|coin_name>`.
:::

::: tip Note
You may want to cap the maximum gas that can be consumed by the transaction via the `--gas` flag.
If you pass `--gas=auto`, the gas supply will be automatically estimated before executing the transaction.
Gas estimate might be inaccurate as state changes could occur in between the end of the simulation and the actual execution of a transaction, thus an adjustment is applied on top of the original estimate in order to ensure the transaction is broadcasted successfully. The adjustment can be controlled via the `--gas-adjustment` flag, whose default value is 1.0.
:::

Now, view the updated balances of the origin and destination accounts:

```bash
gaiacli query account <account_cosmos>
gaiacli query account <destination_cosmos>
```

You can also check your balance at a given block by using the `--block` flag:

```bash
gaiacli query account <account_cosmos> --block=<block_height>
```

You can simulate a transaction without actually broadcasting it by appending the
`--dry-run` flag to the command line:

```bash
gaiacli tx send <sender_key_name_or_address> <destination_cosmosaccaddr> 10faucetToken \
  --chain-id=<chain_id> \
  --dry-run
```

Furthermore, you can build a transaction and print its JSON format to STDOUT by
appending `--generate-only` to the list of the command line arguments:

```bash
gaiacli tx send <sender_address> <recipient_address> 10faucetToken \
  --chain-id=<chain_id> \
  --generate-only > unsignedSendTx.json
```

```bash
gaiacli tx sign \
  --chain-id=<chain_id> \
  --from=<key_name> \
  unsignedSendTx.json > signedSendTx.json
```

::: tip Note
The `--generate-only` flag prevents `gaiacli` from accessing the local keybase.
Thus when such flag is supplied `<sender_key_name_or_address>` must be an address.
:::

You can validate the transaction's signatures by typing the following:

```bash
gaiacli tx sign --validate-signatures signedSendTx.json
```

You can broadcast the signed transaction to a node by providing the JSON file to the following command:

```bash
gaiacli tx broadcast --node=<node> signedSendTx.json
```

### Query Transactions

#### Matching a Set of Events

You can use the transaction search command to query for transactions that match a
specific set of `events`, which are added on every transaction.

Each event is composed by a key-value pair in the form of `{eventType}.{eventAttribute}={value}`.
Events can also be combined to query for a more specific result using the `&` symbol.

You can query transactions by `events` as follows:

```bash
gaiacli query txs --events='message.sender=cosmos1...'
```

And for using multiple `events`:

```bash
gaiacli query txs --events='message.sender=cosmos1...&message.action=withdraw_delegator_reward'
```

The pagination is supported as well via `page` and `limit`:

```bash
gaiacli query txs --events='message.sender=cosmos1...' --page=1 --limit=20
```

::: tip Note

The action tag always equals the message type returned by the `Type()` function of the relevant message.

You can find a list of available `events` on each of the SDK modules:

- [Staking events](https://github.com/cosmos/cosmos-sdk/blob/master/x/staking/spec/07_events.md)
- [Governance events](https://github.com/cosmos/cosmos-sdk/blob/master/x/gov/spec/04_events.md)
- [Slashing events](https://github.com/cosmos/cosmos-sdk/blob/master/x/slashing/spec/06_events.md)
- [Distribution events](https://github.com/cosmos/cosmos-sdk/blob/master/x/distribution/spec/06_events.md)
- [Bank events](https://github.com/cosmos/cosmos-sdk/blob/master/x/bank/spec/04_events.md)
  :::

#### Matching a Transaction's Hash

You can also query a single transaction by its hash using the following command:

```bash
gaiacli query tx [hash]
```

### Slashing

#### Unjailing

To unjail your jailed validator

```bash
gaiacli tx slashing unjail --from <validator-operator-addr>
```

#### Signing Info

To retrieve a validator's signing info:

```bash
gaiacli query slashing signing-info <validator-pubkey>
```

#### Query Parameters

You can get the current slashing parameters via:

```bash
gaiacli query slashing params
```

### Minting

You can query for the minting/inflation parameters via:

```bash
gaiacli query minting params
```

To query for the current inflation value:

```bash
gaiacli query minting inflation
```

To query for the current annual provisions value:

```bash
gaiacli query minting annual-provisions
```

### Staking

#### Set up a Validator

Please refer to the [Validator Setup](../validators/validator-setup.md) section for a more complete guide on how to set up a validator-candidate.

#### Delegate to a Validator

On the upcoming mainnet, you can delegate `atom` to a validator. These [delegators](../delegators/delegator-faq.md) can receive part of the validator's fee revenue. Read more about the [Cosmos Token Model](https://github.com/cosmos/cosmos/raw/master/Cosmos_Token_Model.pdf).

##### Query Validators

You can query the list of all validators of a specific chain:

```bash
gaiacli query staking validators
```

If you want to get the information of a single validator you can check it with:

```bash
gaiacli query staking validator <account_cosmosval>
```

#### Bond Tokens

On the Cosmos Hub mainnet, we delegate `uatom`, where `1atom = 1000000uatom`. Here's how you can bond tokens to a testnet validator (_i.e._ delegate):

```bash
gaiacli tx staking delegate \
  --amount=10000000uatom \
  --validator=<validator> \
  --from=<key_name> \
  --chain-id=<chain_id>
```

`<validator>` is the operator address of the validator to which you intend to delegate. If you are running a local testnet, you can find this with:

```bash
gaiacli keys show [name] --bech val
```

where `[name]` is the name of the key you specified when you initialized `gaiad`.

While tokens are bonded, they are pooled with all the other bonded tokens in the network. Validators and delegators obtain a percentage of shares that equal their stake in this pool.

##### Query Delegations

Once submitted a delegation to a validator, you can see it's information by using the following command:

```bash
gaiacli query staking delegation <delegator_addr> <validator_addr>
```

Or if you want to check all your current delegations with disctinct validators:

```bash
gaiacli query staking delegations <delegator_addr>
```

#### Unbond Tokens

If for any reason the validator misbehaves, or you just want to unbond a certain
amount of tokens, use this following command.

```bash
gaiacli tx staking unbond \
  <validator_addr> \
  10atom \
  --from=<key_name> \
  --chain-id=<chain_id>
```

The unbonding will be automatically completed when the unbonding period has passed.

##### Query Unbonding-Delegations

Once you begin an unbonding-delegation, you can see it's information by using the following command:

```bash
gaiacli query staking unbonding-delegation <delegator_addr> <validator_addr>
```

Or if you want to check all your current unbonding-delegations with disctinct validators:

```bash
gaiacli query staking unbonding-delegations <account_cosmos>
```

Additionally, as you can get all the unbonding-delegations from a particular validator:

```bash
gaiacli query staking unbonding-delegations-from <account_cosmosval>
```

#### Redelegate Tokens

A redelegation is a type delegation that allows you to bond illiquid tokens from one validator to another:

```bash
gaiacli tx staking redelegate \
  <src-validator-operator-addr> \
  <dst-validator-operator-addr> \
  10atom \
  --from=<key_name> \
  --chain-id=<chain_id>
```

Here you can also redelegate a specific `shares-amount` or a `shares-fraction` with the corresponding flags.

The redelegation will be automatically completed when the unbonding period has passed.

##### Query Redelegations

Once you begin an redelegation, you can see it's information by using the following command:

```bash
gaiacli query staking redelegation <delegator_addr> <src_val_addr> <dst_val_addr>
```

Or if you want to check all your current unbonding-delegations with distinct validators:

```bash
gaiacli query staking redelegations <account_cosmos>
```

Additionally, as you can get all the outgoing redelegations from a particular validator:

```bash
  gaiacli query staking redelegations-from <account_cosmosval>
```

#### Query Parameters

Parameters define high level settings for staking. You can get the current values by using:

```bash
gaiacli query staking params
```

With the above command you will get the values for:

- Unbonding time
- Maximum numbers of validators
- Coin denomination for staking

All these values will be subject to updates though a `governance` process by `ParameterChange` proposals.

#### Query Pool

A staking `Pool` defines the dynamic parameters of the current state. You can query them with the following command:

```bash
gaiacli query staking pool
```

With the `pool` command you will get the values for:

- Not-bonded and bonded tokens
- Token supply
- Current annual inflation and the block in which the last inflation was processed
- Last recorded bonded shares

##### Query Delegations To Validator

You can also query all of the delegations to a particular validator:

```bash
  gaiacli query delegations-to <account_cosmosval>
```

### Governance

Governance is the process from which users in the Cosmos Hub can come to consensus
on software upgrades, parameters of the mainnet or signaling mechanisms through
text proposals. This is done through voting on proposals, which will be submitted
by `ATOM` holders on the mainnet.

Some considerations about the voting process:

- Voting is done by bonded `ATOM` holders on a 1 bonded `ATOM` 1 vote basis
- Delegators inherit the vote of their validator if they don't vote
- Votes are tallied at the end of the voting period (2 weeks on mainnet) where
  each address can vote multiple times to update its `Option` value (paying the transaction fee each time),
  only the most recently cast vote will count as valid
- Voters can choose between options `Yes`, `No`, `NoWithVeto` and `Abstain`
- At the end of the voting period, a proposal is accepted iff:
  - `(YesVotes / (YesVotes+NoVotes+NoWithVetoVotes)) > 1/2`
  - `(NoWithVetoVotes / (YesVotes+NoVotes+NoWithVetoVotes)) < 1/3`
  - `((YesVotes+NoVotes+NoWithVetoVotes) / totalBondedStake) >= quorum`

For more information about the governance process and how it works, please check
out the Governance module [specification](https://github.com/cosmos/cosmos-sdk/tree/master/x/gov/spec).

#### Create a Governance Proposal

In order to create a governance proposal, you must submit an initial deposit
along with a title and description. Various modules outside of governance may
implement their own proposal types and handlers (eg. parameter changes), where
the governance module itself supports `Text` proposals. Any module
outside of governance has it's command mounted on top of `submit-proposal`.

To submit a `Text` proposal:

```bash
gaiacli tx gov submit-proposal \
  --title=<title> \
  --description=<description> \
  --type="Text" \
  --deposit="1000000uatom" \
  --from=<name> \
  --chain-id=<chain_id>
```

You may also provide the proposal directly through the `--proposal` flag which
points to a JSON file containing the proposal.

To submit a parameter change proposal, you must provide a proposal file as its
contents are less friendly to CLI input:

```bash
gaiacli tx gov submit-proposal param-change <path/to/proposal.json> \
  --from=<name> \
  --chain-id=<chain_id>
```

Where `proposal.json` contains the following:

```json
{
  "title": "Param Change",
  "description": "Update max validators",
  "changes": [
    {
      "subspace": "staking",
      "key": "MaxValidators",
      "value": 105
    }
  ],
  "deposit": [
    {
      "denom": "stake",
      "amount": "10000000"
    }
  ]
}
```

::: danger Warning

Currently parameter changes are _evaluated_ but not _validated_, so it is very important
that any `value` change is valid (ie. correct type and within bounds) for its
respective parameter, eg. `MaxValidators` should be an integer and not a decimal.

Proper vetting of a parameter change proposal should prevent this from happening
(no deposits should occur during the governance process), but it should be noted
regardless.

:::

::: tip Note

The `SoftwareUpgrade` is currently not supported as it's not implemented and
currently does not differ from the semantics of a `Text` proposal.

:::

##### Query Proposals

Once created, you can now query information of the proposal:

```bash
gaiacli query gov proposal <proposal_id>
```

Or query all available proposals:

```bash
gaiacli query gov proposals
```

You can also query proposals filtered by `voter` or `depositor` by using the corresponding flags.

To query for the proposer of a given governance proposal:

```bash
gaiacli query gov proposer <proposal_id>
```

#### Increase Deposit

In order for a proposal to be broadcasted to the network, the amount deposited must be above a `minDeposit` value (initial value: `512000000uatom`). If the proposal you previously created didn't meet this requirement, you can still increase the total amount deposited to activate it. Once the minimum deposit is reached, the proposal enters voting period:

```bash
gaiacli tx gov deposit <proposal_id> "10000000uatom" \
  --from=<name> \
  --chain-id=<chain_id>
```

> _NOTE_: Proposals that don't meet this requirement will be deleted after `MaxDepositPeriod` is reached.

##### Query Deposits

Once a new proposal is created, you can query all the deposits submitted to it:

```bash
gaiacli query gov deposits <proposal_id>
```

You can also query a deposit submitted by a specific address:

```bash
gaiacli query gov deposit <proposal_id> <depositor_address>
```

#### Vote on a Proposal

After a proposal's deposit reaches the `MinDeposit` value, the voting period opens. Bonded `Atom` holders can then cast vote on it:

```bash
gaiacli tx gov vote <proposal_id> <Yes/No/NoWithVeto/Abstain> \
  --from=<name> \
  --chain-id=<chain_id>
```

##### Query Votes

Check the vote with the option you just submitted:

```bash
gaiacli query gov vote <proposal_id> <voter_address>
```

You can also get all the previous votes submitted to the proposal with:

```bash
gaiacli query gov votes <proposal_id>
```

#### Query proposal tally results

To check the current tally of a given proposal you can use the `tally` command:

```bash
gaiacli query gov tally <proposal_id>
```

#### Query Governance Parameters

To check the current governance parameters run:

```bash
gaiacli query gov params
```

To query subsets of the governance parameters run:

```bash
gaiacli query gov param voting
gaiacli query gov param tallying
gaiacli query gov param deposit
```

### Fee Distribution

#### Query Distribution Parameters

To check the current distribution parameters, run:

```bash
gaiacli query distribution params
```

#### Query distribution Community Pool

To query all coins in the community pool which is under Governance control:

```bash
gaiacli query distribution community-pool
```

#### Query outstanding rewards

To check the current outstanding (un-withdrawn) rewards, run:

```bash
gaiacli query distribution outstanding-rewards
```

#### Query Validator Commission

To check the current outstanding commission for a validator, run:

```bash
gaiacli query distribution commission <validator_address>
```

#### Query Validator Slashes

To check historical slashes for a validator, run:

```bash
gaiacli query distribution slashes <validator_address> <start_height> <end_height>
```

#### Query Delegator Rewards

To check current rewards for a delegation (were they to be withdrawn), run:

```bash
gaiacli query distribution rewards <delegator_address> <validator_address>
```

#### Query All Delegator Rewards

To check all current rewards for a delegation (were they to be withdrawn), run:

```bash
gaiacli query distribution rewards <delegator_address>
```

### Multisig Transactions

Multisig transactions require signatures of multiple private keys. Thus, generating and signing
a transaction from a multisig account involve cooperation among the parties involved. A multisig
transaction can be initiated by any of the key holders, and at least one of them would need to
import other parties' public keys into their Keybase and generate a multisig public key
in order to finalize and broadcast the transaction.

For example, given a multisig key comprising the keys `p1`, `p2`, and `p3`, each of which is held
by a distinct party, the user holding `p1` would require to import both `p2` and `p3` in order to
generate the multisig account public key:

```bash
gaiacli keys add \
  p2 \
  --pubkey=cosmospub1addwnpepqtd28uwa0yxtwal5223qqr5aqf5y57tc7kk7z8qd4zplrdlk5ez5kdnlrj4

gaiacli keys add \
  p3 \
  --pubkey=cosmospub1addwnpepqgj04jpm9wrdml5qnss9kjxkmxzywuklnkj0g3a3f8l5wx9z4ennz84ym5t

gaiacli keys add \
  p1p2p3 \
  --multisig-threshold=2 \
  --multisig=p1,p2,p3
```

A new multisig public key `p1p2p3` has been stored, and its address will be
used as signer of multisig transactions:

```bash
gaiacli keys show --address p1p2p3
```

You may also view multisig threshold, pubkey constituents and respective weights
by viewing the JSON output of the key or passing the `--show-multisig` flag:

```bash
gaiacli keys show p1p2p3 -o json

gaiacli keys show p1p2p3 --show-multisig
```

The first step to create a multisig transaction is to initiate it on behalf
of the multisig address created above:

```bash
gaiacli tx send cosmos1570v2fq3twt0f0x02vhxpuzc9jc4yl30q2qned 1000000uatom \
  --from=<multisig_address> \
  --generate-only > unsignedTx.json
```

The file `unsignedTx.json` contains the unsigned transaction encoded in JSON.
`p1` can now sign the transaction with its own private key:

```bash
gaiacli tx sign \
  unsignedTx.json \
  --multisig=<multisig_address> \
  --from=p1 \
  --output-document=p1signature.json
```

Once the signature is generated, `p1` transmits both `unsignedTx.json` and
`p1signature.json` to `p2` or `p3`, which in turn will generate their
respective signature:

```bash
gaiacli tx sign \
  unsignedTx.json \
  --multisig=<multisig_address> \
  --from=p2 \
  --output-document=p2signature.json
```

`p1p2p3` is a 2-of-3 multisig key, therefore one additional signature
is sufficient. Any the key holders can now generate the multisig
transaction by combining the required signature files:

```bash
gaiacli tx multisign \
  unsignedTx.json \
  p1p2p3 \
  p1signature.json p2signature.json > signedTx.json
```

The transaction can now be sent to the node:

```bash
gaiacli tx broadcast signedTx.json
```

## Shells Completion Scripts

Completion scripts for popular UNIX shell interpreters such as `Bash` and `Zsh`
can be generated through the `completion` command, which is available for both
`gaiad` and `gaiacli`.

If you want to generate `Bash` completion scripts run the following command:

```bash
gaiad completion > gaiad_completion
gaiacli completion > gaiacli_completion
```

If you want to generate `Zsh` completion scripts run the following command:

```bash
gaiad completion --zsh > gaiad_completion
gaiacli completion --zsh > gaiacli_completion
```

::: tip Note
On most UNIX systems, such scripts may be loaded in `.bashrc` or
`.bash_profile` to enable Bash autocompletion:

```bash
echo '. gaiad_completion' >> ~/.bashrc
echo '. gaiacli_completion' >> ~/.bashrc
```

Refer to the user's manual of your interpreter provided by your
operating system for information on how to enable shell autocompletion.
:::
