# Introduction

BitSong Blockchain Documentation

{% hint style="warning" %}
We are moving our **documentation** to the new "[**BitSong, the blockchain for music**](https://bitsong.io/en)" website. To access the most up-to-date and complete version of our guides and articles, please visit our new [**bitsong documentation**](https://bitsong.io/en/docs) website. This old documentation site will no longer be maintained or updated, so we **strongly recommend** referring to the new [**bitsong documentation**](https://bitsong.io/en/docs) website for the latest information. If you can't find what you're looking for on the new site, please be patient as we are still in the process of migrating all of our content. Thank you for your understanding!\
\
Visit the new article <https://bitsong.io/en/docs/>
{% endhint %}

## What is BitSong?

[**BitSong**](https://bitsong.io) is a **multifunctional blockchain-based ecosystem** built to empower the music industry. It unites artists, fans, distributors in an environment where music, merchandise, and fan loyalty are assets of value. BitSong’s decentralized ecosystem of services provides the global music community with a trustless marketplace for **music streaming**, **Fan Tokens**, and **NFTs**, powered by the BTSG token.

## Brief History of BitSong

**BitSong** was conceived in 2018 by developer and entrepreneur Angelo Recca. Angelo, like many others realized that while the digitalization of music has brought many benefits to the industry, it’s also created a new set of problems around the ownership of music and attribution of royalties. He joined forces with Iulian Anghelin and BitSong was born.

The initial intention was for BitSong to become an Ethereum-based application where fans could stream music and artists could receive royalties directly. However, after discovering Cosmos and its ambition to become the “Internet of Blockchains,” Angelo and Iulian immediately recognized the full potential of becoming part of a multi-chain environment.

After launching the main BitSong blockchain in August 2020, the **bitsong-2b** mainnet went live on October 21, 2021. Featuring Fan Tokens, NFTs, and music streaming platform, all underpinned by secure, robust, battle-tested blockchain technology, the launch of BitSong marks a turning point in the ongoing development of the music industry.

## What is BTSG?

**BTSG** is the ultimate currency for music, powering all the features of the BitSong ecosystems.

Artists, music industry participants, and fans can use BTSG to:

Buy, sell, and trade Fan Tokens&#x20;

Buy, sell and trade NFTs&#x20;

Swap BTSG for other cryptocurrencies on centralized and decentralized exchanges&#x20;

Stake BTSG to a Validator to help secure the network and earn more BTSG as rewards


# BTSG


# What is BTSG ?

**BTSG** is the ultimate currency for music, powering all the features of the BitSong ecosystems.

Artists, music industry participants, and fans can use BTSG to:

Buy, sell, and trade Fan Tokens&#x20;

Buy, sell and trade NFTs&#x20;

Swap BTSG for other cryptocurrencies on centralized and decentralized exchanges&#x20;

Stake BTSG to a Validator to help secure the network and earn more BTSG as rewards


# Distribution and Tokenomics

**BTSG** is the native token of the BitSong network. It is used by the BitSong governance system to vote on blocks and improvement proposals. The amount of BTSGs staked, as well as the duration of the validator’s staking term, determines their voting power on improvement proposals.

BTSG bitsong-mainnet is a Cosmos standard token and is used not only for staking, but also for paying fees and for exchanges between artists and their fans, music providers and investors.

BTSG is the fuel for running BitSong’s entire ecosystem.

Since BitSong was initially created on Ethereum and subsequently migrated to Cosmos, BTSG is a cross-chain token. Indeed, an ERC-20 version of BTSG can be found on Ethereum.

More than 90% (104,973,699 BTSG) of the total initial supply of BTSG (116,420,850) was migrated to the bitsong-mainnet in March 2021, when bitsong-1 was launched. Almost 11.5M BTSG remained in circulation in the Ethereum ecosystem.

## Distribution

Total Initial Supply - 116,420,850 BTSG

* Crowdfunding (50%) - 58,210,425
* Team (20%) - 23,284,170
* Reserve Fund (15%) - 17,463,128
* Marketing & Partnerships (7%) - 8,149,460
* Advisors (5%) - 5,821,043&#x20;
* Bounty Contest (2%) - 2,328,417 (held in 2018 - the tokens were sent to the participants in erc-20 version)
* Airdrop Contest (1%) - 1,164,209 (held in 2018 - the tokens were sent to the participants in erc-20 version)

## Inflation and Rewards

**BTSG** inflation is determined by the amount of bonded BTSG, expressed as a percentage. If the percentage of the total BTSG supply that is bonded goes up, then the inflation rate will decrease accordingly.

Similarly, the reward percentage fluctuates as a function of the inflation rate and the percentage of bonded BTSG.

Put simply, the formula is designed such that, in case the amount of bonded BTSG decreases, participants can earn higher rewards because the inflation parameter increases the amount of newly minted BTSG. The increased rewards will attract more bonded BTSG and in turn, increase network security.

You can view the inflation rate and percentage of bonded BTSG in real time using the [**BitSong Explorer**](https://www.mintscan.io/bitsong).


# Wallets

## BTSG-supported Wallets

BitSong recommends using the Bitsong/Keplr wallet for BitSong mainnet BTSG tokens management from desktop.\
You can access our [UI Dashboard](https://wallet.bitsong.io) via Keplr and perform transfers or governance actions (recommended).

<figure><img src="/files/Kx166ClN3sbj7eNt7SKK" alt=""><figcaption></figcaption></figure>

### Keplr

Keplr is a browser extension wallet designed to support the Cosmos Internet of Blockchains. You can use Keplr to store, send, or receive mainnet-BTSG tokens. You can also stake your BTSG tokens directly to a Validator on the BitSong mainnet from your Keplr wallet.

You will need the Chrome browser (or Brave) to use the Keplr wallet. You can download the wallet from the [Chrome browser extension page](https://chrome.google.com/webstore/detail/keplr/dmkamcknogkgcdfhhbddcghachkejeap). You will then need to add the BitSong mainnet to your Keplr wallet [following these instructions.](/useful-guides/wallet/how-to-create-a-bitsong-wallet)&#x20;

### Cosmostation

#### Web Wallet

Access your account on [Cosmostation web wallet](https://wallet.cosmostation.io/cosmos) via Ledger hardware wallet or Keystation powered by Cosmostation.

<figure><img src="/files/homFYyM477yTPL8dUwrM" alt=""><figcaption></figcaption></figure>

#### Extension Wallet

[Cosmostation Wallet Extension](https://chrome.google.com/webstore/detail/cosmostation/fpkhgmpbidmiogeglndfbkegfdlnajnf?utm_source=chrome-ntp-icon) is a 100% non-custodial chrome extension wallet that supports multiple sovereign networks and inter-chain bridges.

<figure><img src="/files/tvZmarFqiVRToopUPl3v" alt=""><figcaption></figcaption></figure>

#### Mobile Wallet

Industry leading non-custodial mobile wallet designed for PoS blockchains. Explore the interchain in the palm of your hand.\
\
1\. Get it on [Google Play](https://play.google.com/store/apps/details?id=wannabit.io.cosmostaion)\
2\. Get in on [App Store](https://apps.apple.com/kr/app/cosmostation/id1459830339)

<figure><img src="/files/qsUvaVIHz6tEKgKU4qB8" alt=""><figcaption></figcaption></figure>

## Leap Wallet

Leap is a non-custodial super wallet for web3. It is already live on Cosmos & Terra 2.0, while it is expected to be deployed soon on Avalanche too.

#### Wallet Extension

BitSong is integrated with full support into Leap Wallet Extension. \
In order to manage your $BTSGs via Leap Wallet you'll need to install [Leap Wallet Web extension for Cosmos.](https://chrome.google.com/webstore/detail/leap-cosmos-wallet/fcfcfllfndlomdhbehjjcoimbgofdncg/?utm_source=website\&utm_medium=permanent-website\&utm_campaign=permanent)\
Open a new wallet or import one via the available options and start managing your BTSGs on Leap Wallet.

<figure><img src="/files/mef9lYX09LMaXrIOPOXI" alt=""><figcaption></figcaption></figure>

#### Mobile App Wallet (Full Support for BitSong)

1. Get it for [**Android**](https://www.leapwallet.io/cosmos)
2. Get it for [**iOS**](https://www.leapwallet.io/cosmos)

<figure><img src="/files/qazmbLf1SjYyy9ihJNou" alt=""><figcaption></figcaption></figure>

Once you downloaded and installed the app, you need to create or import your wallet into it.\
After you wallet is set, then all you need to do is clicking on the blockchain icon (upper right) which usually is set to Cosmos Blockchain by default and looking for BitSong in the chains list as in the image below.\
Select the BitSong Blockchain from the list and you're all set, ready to copy and distribute your bitsong wallet address.

<figure><img src="/files/G4whRfBzrJ9htSEZFEuU" alt=""><figcaption></figcaption></figure>

[![chain\_img](https://www.cosmostation.io/_next/static/media/light_play_store.ac8ff4e6.svg)](https://play.google.com/store/apps/details?id=wannabit.io.cosmostaion)[![chain\_img](https://www.cosmostation.io/_next/static/media/light_app_store.97f6e176.svg)](https://apps.apple.com/kr/app/cosmostation/id1459830339)


# Buy and Sell

## How to buy and sell BTSG

#### Swap BTSG on Osmosis

These instructions are for native-BTSG tokens.

To swap BTSG on Osmosis you’ll need to have installed the Keplr wallet.

Go to the [Assets area](https://app.osmosis.zone/assets) of the Osmosis app and connect your Keplr wallet. You can then deposit your BTSG or other IBC-enabled tokens to Osmosis using the “Deposit” option next to the relevant token.

Please note that Osmosis fees are payable in OSMO tokens. Therefore, regardless of which tokens you are swapping BTSG from or to, you will also need a sufficient OSMO balance in your wallet to cover the fees. If it’s your first swap using Osmosis, then you should first acquire a small amount of OSMO tokens before swapping to or from BTSG.

Once you have an initial deposit of IBC-enabled tokens, you can make a swap using the Trade feature on Osmosis. You can then select the token you wish to swap from or to, and the amounts. When you click “Swap,”, you’ll go to a preview window. Review the details of your swap to make sure they’re correct, and then approve your transaction.


# Liquidity Provider

## Becoming a BTSG Liquidity Provider

### Why become a BTSG Liquidity Provider?

BTSG liquidity providers play a crucial role in ensuring a continuous supply of liquidity for BTSG on decentralized exchanges. In return for depositing into BTSG pools, liquidity providers earn a share of transaction fees paid by traders who use the pool to swap BTSG tokens.

### Provide liquidity to BTSG Pools on Osmosis

These instructions are for mainnet-BTSG tokens.

To add liquidity to BTSG pools on Osmosis you’ll need to have installed the Keplr wallet. You’ll also need to have a balance of the equivalent pairs for which you want to add liquidity, e.g. BTSG and ATOM.

Go to the [“Pools” section on the Osmosis app.](https://app.osmosis.zone/pools) Scroll down until you find the BTSG pools numbered , and select “Add/Remove Liquidity.” Input the BTSG you want to add, and your other token balance will be calculated automatically. Click the “Add Liquidity” button and when prompted, approve the transaction in your Keplr wallet. You will receive LP tokens to represent your staked liquidity.

A short guide can also be found [**here**](https://docs.bitsong.io/useful-guides/how-to-add-usdbtsg-liquidity-in-osmosis-pools).

When you wish to withdraw your tokens, navigate back to the Pools section on Osmosis with your Keplr wallet connected, and you can use the “Add/Remove Liquidity” option to redeem LP tokens.

### Risks of liquidity pools

Becoming a liquidity provider comes with a certain amount of risk. Cryptocurrencies are volatile assets and when prices for tokens in a pool diverge, the liquidity provider may incur impermanent loss.

Decentralized finance protocols can also be subject to other risks, such as smart contract risk. Please ensure you research and understand these risks before depositing your funds into a liquidity pool.


# Delegators


# Delegator FAQ

{% hint style="warning" %}
We are moving our **documentation** to the new "[**BitSong, the blockchain for music**](https://bitsong.io/en)" website. To access the most up-to-date and complete version of our guides and articles, please visit our new [**bitsong documentation**](https://bitsong.io/en/docs) website. This old documentation site will no longer be maintained or updated, so we **strongly recommend** referring to the new [**bitsong documentation**](https://bitsong.io/en/docs) website for the latest information. If you can't find what you're looking for on the new site, please be patient as we are still in the process of migrating all of our content. Thank you for your understanding!\
\
Visit the new article <https://bitsong.io/en/docs/delegators/delegator-faq>
{% endhint %}

This section contains answers to some commonly-asked questions from BTSG delegators.&#x20;

### What is a delegator? <a href="#what-is-a-delegator" id="what-is-a-delegator"></a>

Delegating is an easy way for any BTSG holder to participate in securing the BitSong network and earn rewards through staking. Unlike becoming a Validator, there are low technical barriers to entry for Delegators. Delegators play an important role in safeguarding the network, by choosing Validators who behave in the best interests of the network. Delegators who stake tokens to the best-performing Validators will be best rewarded. Conversely, if a Delegator backs a Validator who misbehaves, the Validator gets slashed and the Delegator loses a share of their stake.&#x20;

Therefore, the incentives in place for Delegators help to promote a positive balance of power among BTSG holders.&#x20;

The reward structures for Validators and Delegators are slightly different due to the Validator commission. This is a percentage of revenues that the Validator takes before the rest is distributed to the Delegators in the Validator staking pool.&#x20;

Delegators can browse commission rates before staking their BTSG, and Validators can only change their commission rate under certain conditions (see [section](#choosing-a-validator) below).&#x20;

In terms of risk, a Delegator's BTSG may be slashed if their validator misbehaves. See [Risks](#risks) section for more info.

To become delegators, BTSG holders need to send a "Delegate transaction." The transaction should specify how many BTSG they want to bond and to which Validator.&#x20;

A list of Validator candidates can be found in the [BitSong Explorer.](https://explorebitsong.com/validators)&#x20;

If a Delegator wishes to unbond part or all of their stake, they should send an "Unbond transaction". There is a 21-day unbonding period, after which the bonded BTSG are released. If a Delegator simply wishes to switch their stake from one Validator to another, then they can use the "Rebond transaction" which takes effect immediately.&#x20;

### Choosing a validator <a href="#choosing-a-validator" id="choosing-a-validator"></a>

In the BitSong Explorer, Delegators can find a range of information about the Validator set, as follows:&#x20;

* **Validator's moniker**: The chosen name of the Validator candidate.
* **Validator's description**: Description provided by the validator operator.
* **Validator's website**: Link to the Validator's website if they have one.
* **Initial commission rate**: The commission rate that the Validator charges on revenues before they are distributed to Delegators&#x20;
* **Commission max change rate:** The maximum daily increase of the Validator's commission. This parameter cannot be changed by the Validator operator.
* **Maximum commission:** The maximum commission rate this Validator candidate can charge. This parameter cannot be changed by the Validator operator.
* **Minimum self-bond amount**: Minimum amount of BTSG the Validator candidate needs to have bonded at all time. If the Validator's self-bonded stake falls below this limit, their entire staking pool, including all delegated funds, will unbond automatically. This parameter acts as a safeguard for delegators. Similarly, when a Validator misbehaves, part of their total stake gets slashed. The slashing applies to the validator's self-delegated stake, as well as their delegators' stake. Therefore, Delegators can use the amount of self-bonded BTSG as a gauge of the amount of "skin in the game" on the part of a Validator. The minimum self-bond amount parameter offers a guarantee to Delegators that a Validator will always maintain their self-bonded BTSG amount above a certain level. Validators can only increase this amount, not decrease it.

### Directives of delegators <a href="#directives-of-delegators" id="directives-of-delegators"></a>

Becoming a Delegator may be technically easier than becoming a Validator, but it's not a passive job. Here are the main responsibilities of a Delegator:

* **Ensure you conduct due diligence on Validators before delegating.** A badly-behaved Validator will put your stake at risk of slashing. Therefore, due diligence is important to ensure that you can make a careful selection of Validators with the lowest risk of slashing.&#x20;
* **Actively monitor their Validator throughout the delegation period.** Delegators should continue to ensure that the Validators they've staked to have good uptime, don't double sign or become compromised, and participate in governance votes. They should also monitor the commission rate to make sure they're happy with any changes. If a Delegator is not satisfied, they can either unbond or switch to another validator (Note: Delegators do not have to wait the 21-day unbonding period to switch Validators. Rebonding to another Validator takes effect immediately).
* **Participate in governance.** Delegators should actively participate in governance. The size of their bonded stake determines the voting power. If a delegator doesn't vote, they will inherit the vote of their Validator(s). If they do vote, they override the vote of their Validator(s). Therefore, the role that Delegators can play in balancing the weight of the votes in governance cannot be overstated.&#x20;

### Revenue <a href="#revenue" id="revenue"></a>

Validators and Delegators earn rewards in exchange for their participation. Rewards are generated from two sources of revenue:

* **Block rewards:** Block rewards are generated from the inflation algorithm, creating newly-minted BTSG with each block. The algorithm is configured to encourage BTSG holders to stake. **BTSG** inflation is determined by the amount of bonded BTSG, expressed as a percentage. If the percentage of the total BTSG supply that is bonded goes up, then the inflation rate will decrease accordingly. Similarly, the reward percentage fluctuates as a function of the inflation rate and the percentage of bonded BTSG. Put simply, the formula is designed such that, in case the amount of bonded BTSG decreases, participants can earn higher rewards because the inflation parameter increases the amount of newly minted BTSG. The increased rewards will attract more bonded BTSG and in turn, increase network security. You can view the inflation rate and percentage of bonded BTSG in real time using the [**BitSong Explorer**](https://bitsong.bigdipper.live).
* **Transaction fees:** Each transaction on the BitSong network incurs fees paid in BTSG, which are distributed to Validators and Delegators according to the weight of their stake.&#x20;

### Validator Commission <a href="#validator-commission" id="validator-commission"></a>

Each Validator receives revenue paid to their Validator pool based on their total staked amount. Before the revenue is distributed to the Delegators in the pool, the Validator can apply a commission. Let's take an example.

There is a Validator who has a staking pool worth 10% of the total stake of all validators. This Validator also has a 20% self-delegated stake and applies a commission rate of 10%.&#x20;

A block comes in with the following revenue:

* 990 BTSG in block provisions
* 10 BTSG in transaction fees.

So a total of 1000 BTSG to be distributed among all staking pools.

Our Validator's staking pool represents 10% of the total stake, which means the pool receives 100 BTSG. Now let's look at how the revenue breaks down to Delegators:

* Commission = `10% * 80% * 100` BTSG = 8 BTSG
* Validator's revenue = `20% * 100` BTSG + Commission = 28 BTSG
* Delegators' total revenue = `80% * 100` BTSG - Commission = 72 BTSG

Now, each Delegator in the staking pool can claim their portion of the Delegators' total revenue.

### Risks <a href="#risks" id="risks"></a>

There are some risks of staking cryptocurrencies. While they're staked, your BTSG are locked up, and there's a 21-day unbonding period to release them.&#x20;

Furthermore, there's the risk that Validators may misbehave and incur slashing penalties. Any slashing includes the stake of their Delegators.

There is one main behavior that incurs slashing penalties, known as double-signing. If someone reports that a Validator signed two different blocks with the same chain ID at the same height, this validator will get slashed.

A Validator's track record will show their performance, including their slashing history. Therefore, it's important that Delegators perform careful due diligence on Validators before delegating. Monitoring performance is also important. If your chosen Validator is offline too often, you can simply switch to another Validator. You can also choose to offset the overall risk by staking to multiple Validators.&#x20;


# Delegator Security

{% hint style="warning" %}
We are moving our **documentation** to the new "[**BitSong, the blockchain for music**](https://bitsong.io/en)" website. To access the most up-to-date and complete version of our guides and articles, please visit our new [**bitsong documentation**](https://bitsong.io/en/docs) website. This old documentation site will no longer be maintained or updated, so we **strongly recommend** referring to the new [**bitsong documentation**](https://bitsong.io/en/docs) website for the latest information. If you can't find what you're looking for on the new site, please be patient as we are still in the process of migrating all of our content. Thank you for your understanding!\
\
Visit the new article <https://bitsong.io/en/docs/delegators/delegator-security>
{% endhint %}

As the cryptocurrency sector has grown, it's unfortunately become a target for malicious actors, including hackers, scammers, and fraudulent operators. As such, there are some risks associated with holding crypto. However, these risks can be mitigated with some understanding of the kinds of tactics that malicious actors use, and how you can protect yourself against them.&#x20;

### Social Engineering <a href="#social-engineering" id="social-engineering"></a>

Delegating is an easy way for any BTSG holder to participate in securing the BitSong network and earn rewards through staking. Unlike becoming a Validator, there are low technical barriers to entry for Delegators. Delegators play an important role in safeguarding the network, by choosing Validators who behave in the best interests of the network. Delegators who stake tokens to the best-performing Validators will be best rewarded. Conversely, if a Delegator backs a Validator who misbehaves, the Validator gets slashed and the Delegator loses a share of their stake.&#x20;

In the context of cybersecurity, social engineering attacks are ones that exploit our human vulnerabilities to launch an attack. Anywhere you have an inbox or can be contacted socially is a potential platform for attackers to attempt to launch social engineering attacks. The most common type of social engineering attack is phishing. Typically, the attacker will contact potential victims posing as a legitimate third party, and ask questions designed to gain access to passwords, private keys, or other information that would allow them to steal funds.&#x20;

Therefore, the incentives in place for Delegators help to promote a positive balance of power among BTSG holders.&#x20;

There are literally thousands of ways that attackers attempt phishing attacks, but often they play to our base instincts – by telling someone they've won something, or telling them they're about to lose something.&#x20;

The reward structures for Validators and Delegators are slightly different due to the Validator commission. This is a percentage of revenues that the Validator takes before the rest is distributed to the Delegators in the Validator staking pool.&#x20;

Here are a few basic measures that can help keep you safe:

Delegators can browse commission rates before staking their BTSG, and Validators can only change their commission rate under certain conditions (see [section](#choosing-a-validator) below).&#x20;

* **Never open attachments from people you don't know and never open links in emails from sources you don't trust. Attachments can install spyware or other kinds of malware on your c**omputers. Links can take you to compromised sites that may attempt to steal sensitive information from your computer.&#x20;
* **Make sure you always install updates to apps, browsers, and your device operating systems when they're available.** They often include important security updates designed to protect against attacks. &#x20;
* **Never buy BTSG from untrusted sources and always do your due diligence before buying BTSG from any seller or venue.**
* **If you ever receive an offer that sounds too good to be true, it usually is.** Remember that no reputable agent will ever ask you to disclose your private keys or passwords.&#x20;

In terms of risk, a Delegator's BTSG may be slashed if their validator misbehaves. See [Risks](#risks) section for more info.

### Key Management <a href="#key-management" id="key-management"></a>

To become delegators, BTSG holders need to send a "Delegate transaction." The transaction should specify how many BTSG they want to bond and to which Validator.&#x20;

You will need a suitable storage solution for your BTSG tokens, along with a means of backup. The safest way to store private keys is offline, either using a crypto wallet, or on paper or a device that never connects to the internet. Ideally, you should keep multiple copies. Some crypto users also invest in a way to protect against disasters such as fire.&#x20;

A list of Validator candidates can be found in the [BitSong Explorer.](https://explorebitsong.com/validators)&#x20;

**Never, ever share your private keys with anyone**. You don't need to share your private keys to delegate your BTSG to a Validator on BitSong.&#x20;

If a Delegator wishes to unbond part or all of their stake, they should send an "Unbond transaction". There is a 21-day unbonding period, after which the bonded BTSG are released. If a Delegator simply wishes to switch their stake from one Validator to another, then they can use the "Rebond transaction" which takes effect immediately.&#x20;

### Software Vulnerabilities <a href="#software-vulnerabilities" id="software-vulnerabilities"></a>

### Choosing a validator <a href="#choosing-a-validator" id="choosing-a-validator"></a>

Always make sure you're using the latest version of any operating system, software, application, browser, or wallet. Updates often contain important security-related changes, so updating often protects you against security threats.&#x20;

In the BitSong Explorer, Delegators can find a range of information about the Validator set, as follows:&#x20;

BitSong will always release software through official project channels. Nobody from the project will ever contact you by email or chat messages asking you to download external software or programs.&#x20;

* **Validator's moniker**: The chosen name of the Validator candidate.
* **Validator's description**: Description provided by the validator operator.
* **Validator's website**: Link to the Validator's website if they have one.
* **Initial commission rate**: The commission rate that the Validator charges on revenues before they are distributed to Delegators&#x20;
* **Commission max change rate:** The maximum daily increase of the Validator's commission. This parameter cannot be changed by the Validator operator.
* **Maximum commission:** The maximum commission rate this Validator candidate can charge. This parameter cannot be changed by the Validator operator.
* **Minimum self-bond amount**: Minimum amount of BTSG the Validator candidate needs to have bonded at all time. If the Validator's self-bonded stake falls below this limit, their entire staking pool, including all delegated funds, will unbond automatically. This parameter acts as a safeguard for delegators. Similarly, when a Validator misbehaves, part of their total stake gets slashed. The slashing applies to the validator's self-delegated stake, as well as their delegators' stake. Therefore, Delegators can use the amount of self-bonded BTSG as a gauge of the amount of "skin in the game" on the part of a Validator. The minimum self-bond amount parameter offers a guarantee to Delegators that a Validator will always maintain their self-bonded BTSG amount above a certain level. Validators can only increase this amount, not decrease it.

### Verifying Transactions <a href="#verifying-transactions" id="verifying-transactions"></a>

### Directives of delegators <a href="#directives-of-delegators" id="directives-of-delegators"></a>

All Delegators should be familiar with the basic commands and transaction types needed to participate in delegation. Please use BitSong's official documentation as a guide, also to make sure that you aren't being tricked or conned when taking advice from others. Be wary of advice from people you don't know, especially those in public forums.&#x20;

Becoming a Delegator may be technically easier than becoming a Validator, but it's not a passive job. Here are the main responsibilities of a Delegator:

**Blockchain transactions are irreversible. Always verify twice or even three times before hitting send.** Wherever possible, use QR codes and copy/paste addresses rather than manually typing them to reduce the risk of errors.

* **Ensure you conduct due diligence on Validators before delegating.** A badly-behaved Validator will put your stake at risk of slashing. Therefore, due diligence is important to ensure that you can make a careful selection of Validators with the lowest risk of slashing.&#x20;
* **Actively monitor their Validator throughout the delegation period.** Delegators should continue to ensure that the Validators they've staked to have good uptime, don't double sign or become compromised, and participate in governance votes. They should also monitor the commission rate to make sure they're happy with any changes. If a Delegator is not satisfied, they can either unbond or switch to another validator (Note: Delegators do not have to wait the 21-day unbonding period to switch Validators. Rebonding to another Validator takes effect immediately).
* **Participate in governance.** Delegators should actively participate in governance. The size of their bonded stake determines the voting power. If a delegator doesn't vote, they will inherit the vote of their Validator(s). If they do vote, they override the vote of their Validator(s). Therefore, the role that Delegators can play in balancing the weight of the votes in governance cannot be overstated.&#x20;

### Account Security <a href="#account-security" id="account-security"></a>

### Revenue <a href="#revenue" id="revenue"></a>

Attackers understand the way that humans work online, and they know that we have tendencies to be lazy around things like reusing passwords. But those kind of practices mean that any account can act as a gateway allowing access to all of your most sensitive accounts, including email, bank accounts, or social media.&#x20;

Validators and Delegators earn rewards in exchange for their participation. Rewards are generated from two sources of revenue:

There are a few actions you can take to remediate this risk:

* **Block rewards:** Block rewards are generated from the inflation algorithm, creating newly-minted BTSG with each block. The algorithm is configured to encourage BTSG holders to stake. **BTSG** inflation is determined by the amount of bonded BTSG, expressed as a percentage. If the percentage of the total BTSG supply that is bonded goes up, then the inflation rate will decrease accordingly. Similarly, the reward percentage fluctuates as a function of the inflation rate and the percentage of bonded BTSG. Put simply, the formula is designed such that, in case the amount of bonded BTSG decreases, participants can earn higher rewards because the inflation parameter increases the amount of newly minted BTSG. The increased rewards will attract more bonded BTSG and in turn, increase network security. You can view the inflation rate and percentage of bonded BTSG in real time using the [**BitSong Explorer**](https://bitsong.bigdipper.live).
* **Transaction fees:** Each transaction on the BitSong network incurs fees paid in BTSG, which are distributed to Validators and Delegators according to the weight of their stake.&#x20;
* Make sure you enable 2-factor authentication everywhere you can, and to make sure that you are using a code generator or separate hardware key as a backup, rather than SMS codes
* Refrain from using SMS as a recovery method when you can't access your accounts. Instead, use an authenticator app or hardware key, particularly if you're using crypto exchanges.&#x20;

### Validator Commission <a href="#validator-commission" id="validator-commission"></a>

### Supply Chain Attacks <a href="#supply-chain-attacks" id="supply-chain-attacks"></a>

Each Validator receives revenue paid to their Validator pool based on their total staked amount. Before the revenue is distributed to the Delegators in the pool, the Validator can apply a commission. Let's take an example.

Malicious actors will also attempt to pre-emptively attack devices by penetrating the supply chain. Only ever purchase hardware or hardware wallets directly from suppliers, or from trusted third parties. Be aware that scammers may operate as suppliers on marketplaces such as Amazon.&#x20;

There is a Validator who has a staking pool worth 10% of the total stake of all validators. This Validator also has a 20% self-delegated stake and applies a commission rate of 10%.&#x20;

### Disclaimer <a href="#disclaimer" id="disclaimer"></a>

A block comes in with the following revenue:

Please note that BitSong is early-stage software and it may be that we experience issues, updates, and bugs. Some elements of using the platform require advanced technical skills and involve risks which are outside of the control of the BitSong team. Any use of BitSong licensed software is done at your own risk and on a "AS IS" basis, without warranties or conditions of any kind, and any and all liability of BitSong for damages arising in connection to the software is excluded. Please exercise extreme caution!\`

* 990 BTSG in block provisions
* 10 BTSG in transaction fees.

So a total of 1000 BTSG to be distributed among all staking pools.

Our Validator's staking pool represents 10% of the total stake, which means the pool receives 100 BTSG. Now let's look at how the revenue breaks down to Delegators:

* Commission = `10% * 80% * 100` BTSG = 8 BTSG
* Validator's revenue = `20% * 100` BTSG + Commission = 28 BTSG
* Delegators' total revenue = `80% * 100` BTSG - Commission = 72 BTSG

Now, each Delegator in the staking pool can claim their portion of the Delegators' total revenue.

### Risks <a href="#risks" id="risks"></a>

There are some risks of staking cryptocurrencies. While they're staked, your BTSG are locked up, and there's a 21-day unbonding period to release them.&#x20;

Furthermore, there's the risk that Validators may misbehave and incur slashing penalties. Any slashing includes the stake of their Delegators.

There is one main behavior that incurs slashing penalties, known as double-signing. If someone reports that a Validator signed two different blocks with the same chain ID at the same height, this validator will get slashed.

A Validator's track record will show their performance, including their slashing history. Therefore, it's important that Delegators perform careful due diligence on Validators before delegating. Monitoring performance is also important. If your chosen Validator is offline too often, you can simply switch to another Validator. You can also choose to offset the overall risk by staking to multiple Validators.&#x20;


# Validators


# Validator Overview

### Introduction <a href="#introduction" id="introduction"></a>

BitSong is based on the Tendermint consensus engine. A set of Validators is responsible for adding new blocks of transactions to the BitSong blockchain, for which they receive rewards in BTSG tokens.&#x20;

Upon joining the network, a Validator agrees to bond BTSG tokens. The BTSG can be their own, or the Validator can have BTSG delegated or staked to them by other BTSG holders. There are currently 64 Validator slots on the BitSong network.&#x20;

Therefore, the top 64 Validator candidates with the most bonded BTSG are selected at each block to participate in the next round of block production. Their likelihood of being able to produce the next block is weighted according to the amount of their bonded BTSG.&#x20;

At each block, the entire set of Validators casts votes on the validity of  each block using their private key. The vote is then broadcast to the network.&#x20;

Validators earn BTSG as a reward for their role in securing the network. BTSG rewards are a combination of newly-minted BTSG, and a share of the transaction fees paid by the network.&#x20;

Note that Validators can set commission on the fees their delegators receive as an additional incentive. Choosing the right commission level is a balance, as the Validator must be able to remain competitive enough to attract delegators to stake their BTSG.

Warning: If Validators double-sign, are frequently offline or fail to participate in governance, their staked BTSG, including BTSG delegated to them, may be slashed. The penalty depends on the severity of the violation.

Becoming a validator comes with a set of prerequisites, including hardware and software requirements.

### Hardware <a href="#hardware" id="hardware"></a>

Validators must take appropriate steps to manage the security of their validator keys. Currently, there is no appropriate cloud solution for validator key management. Therefore, you'll need a physical location for your operation, secured with restricted access. One example would be to co-locate in secure data centers.

The premises will need to be equipped with redundant power, connectivity, and storage backups. We recommend using several redundant networking boxes for fiber, firewall, and switching, along with small servers with redundant hard drive and failover.&#x20;

It's worth remembering that bandwidth, CPU and memory requirements will increase over time. Once the BitSong blockchain becomes several years old, you'll also need large hard drives for storing the blockchain history.

### Set Up a Website <a href="#set-up-a-website" id="set-up-a-website"></a>

You will need a website to establish your presence and reputation with BTSG holders who may choose to delegate their tokens to you. It's an important channel to share information and create a storefront for your operation.&#x20;

### Seek Legal Advice <a href="#seek-legal-advice" id="seek-legal-advice"></a>

Seek legal advice if you intend to become a Validator.&#x20;

### Community <a href="#community" id="community"></a>

Join our Discord channel to connect with the BitSong Validator community:

* <https://discord.gg/CJsaaBg>


# Validator FAQ

### General Concepts <a href="#general-concepts" id="general-concepts"></a>

#### What is a Validator? <a href="#what-is-a-validator" id="what-is-a-validator"></a>

A Validator is someone who operates a full node and validates transactions to secure the BitSong blockchain in return for rewards. Validators operate a full node on the BitSong network and participate in consensus by voting on the validity of blocks. Validators also participate in governance by voting on proposals.&#x20;

#### What is Staking? <a href="#what-is-staking" id="what-is-staking"></a>

Staking is the act of depositing cryptocurrencies to help secure the BitSong blockchain, either as a Validator or Delegator. Delegators stake their BTSG tokens to a Validator for a share of the Validator rewards. Validators stake BTSG tokens, which may include their own tokens and staked tokens from Delegators, to be able to participate in the BitSong network as a Validator and earn rewards.&#x20;

Users may declare their intention to become a validator by sending a `create-validator` transaction. From there, they become validator candidates.

The total amount of staked tokens determines the weight of the Validator's voting power and the probability that they are selected to produce a block.&#x20;

Currently, only the top 64 Validators by staked BTSG will be able to participate in consensus.&#x20;

#### What is a full node? <a href="#what-is-a-full-node" id="what-is-a-full-node"></a>

Full nodes on the BitSong network are running the current version of the BitSong software to be able to validate transactions and blocks.&#x20;

Operating a full node simply means running a non-compromised and up-to-date version of the software with low network latency and with no downtime.&#x20;

BitSong welcomes any users who want to run a full node, even if they do not plan to become a Validator.&#x20;

#### What is a Delegator? <a href="#what-is-a-delegator" id="what-is-a-delegator"></a>

A Delegator is someone who delegates their BTSG tokens to a Validator to help secure the BitSong blockchain in return for a share of rewards. Unlike becoming a Validator, which has prerequisites in terms of hardware and connectivity, anyone who holds BTSG can become a Delegator.&#x20;

However, delegating does require participation from Delegators, who should actively monitor their stake and the performance of their chosen Validator(s). Delegators should also participate in governance votes, to ensure their wishes are reflected in the future development of the BitSong ecosystem.&#x20;

Delegators also bear some risk. If their chosen Validator(s) engage in behavior that goes against the interests of the network, the Validators stake may be slashed. Therefore, Delegators are advised to do their own research before staking BTSG to a Validator, and manage risk, for example, by staking to multiple Validators.&#x20;

For more information, go to the [Delegators section](/delegators).&#x20;

### Becoming a Validator <a href="#becoming-a-validator" id="becoming-a-validator"></a>

#### How to become a validator? <a href="#how-to-become-a-validator" id="how-to-become-a-validator"></a>

If someone wishes to become a Validator, then they need to send a `create-validator` transaction. They will be asked to complete the following:

* **Validator's `PubKey`:** The private key associated with this Tendermint `PubKey` is used to sign *prevotes* and *precommits*.
* **Validator's Address:** Application level address. This is the address used to identify your Validator publicly. The private key associated with this address is used to delegate, unbond, claim rewards, and participate in governance.
* **Validator's name (moniker)**
* **Validator's website (Optional)**
* **Validator's description (Optional)**
* **Initial commission rate**: The commission rate on block rewards and fees charged to delegators.
* **Maximum commission:** The maximum commission rate which this validator can charge. This parameter cannot be changed after `create-validator` is processed.
* **Commission max change rate:** The maximum daily increase of the validator commission. This parameter cannot be changed after `create-validator` is processed.
* **Minimum self-delegation:** Minimum amount of BTSG the validator needs to have bonded at all time. If the validator's self-delegated stake falls below this limit, their entire staking pool will unbond.

Once a Validator is created, BTSG holders can begin delegating to them immediately. The Validators total stake is the amount of their own bonded BTSG plus the amount of BTSG staked to them by Delegators.&#x20;

The 64 Validator candidates with the largest total stake will be selected as Validators on the BitSong network. If a Validator's total stake falls below the threshold set by the top 64 candidates, they will cease to become a Validator until their stake becomes enough to qualify for the top 64 Validator candidates again.&#x20;

Validator candidates who fail to reach the top 64 and become a Validator will no longer qualify for Validator privileges and will lose the right to earn Validator rewards.&#x20;

The total number of Validator slots available on the BitSong network may change periodically according to a governance vote.&#x20;

### Testnet <a href="#testnet" id="testnet"></a>

#### How can I join the testnet? <a href="#how-can-i-join-the-testnet" id="how-can-i-join-the-testnet"></a>

We recommend that you test your Validator setup on the Testnet before launching on the BitSong mainnet. Testnet participation also signals to the community that you're ready to become a member of the Validator network.&#x20;

You can find all relevant information about the testnet [here](https://hub.cosmos.network/main/gaia-tutorials/join-testnet.html) and [here (opens new window)](https://github.com/cosmos/testnets).

#### What are the different types of keys? <a href="#what-are-the-different-types-of-keys" id="what-are-the-different-types-of-keys"></a>

There are two types of keys:

* **Tendermint Key**: This is a unique key used to sign consensus votes.
  * It is associated with a public key `cosmosvalconspub` (Get this value with `gaiad tendermint show-validator`)
  * It is generated when the node is created with gaiad init.
* **Application key**: This key is created from `gaiad` and used to sign transactions. Application keys are associated with a public key prefixed by `cosmospub` and an address prefixed by `cosmos`. Both are derived from account keys generated by `gaiad keys add`.

Note: A validator's operator key is directly tied to an application key, but uses reserved prefixes solely for this purpose: `cosmosvaloper` and `cosmosvaloperpub`

#### What are the different states a validator can be in? <a href="#what-are-the-different-states-a-validator-can-be-in" id="what-are-the-different-states-a-validator-can-be-in"></a>

Once you create your Validator with the `create-validator` transaction, it can be in one of three states:

* `in validator set`: Validator is included in the active set of 64 and is participating in consensus. Validator is earning rewards and may be slashed if they misbehave.
* `jailed`: Validator misbehaved and is in jail. The Validator is no longer participating in the active set of 64 or earning rewards. If the jailing happened because the Validator was offline too long, they can send an `unjail` transaction to re-enter the Validator set. If they were jailed due to a double signing, the Validator cannot unjail.
* `unbonded`: Validator is not in the active set, so doesn't participate in consensus, sign blocks, or earn rewards. The Validator also cannot be slashed. Delegators can still delegate BTSG to unbonded Validators, but if they unbond, their BTSG are released immediately without any unbonding period.&#x20;

#### What is 'self-delegation'? How can I increase my 'self-delegation'? <a href="#what-is-self-delegation-how-can-i-increase-my-self-delegation" id="what-is-self-delegation-how-can-i-increase-my-self-delegation"></a>

Self-delegation is the amount of BTSG bonded from a Validators own wallet to themselves. Validators can increase this amount by sending a `delegate` transaction from your validator's `application` key.

#### Is there a minimum amount of BTSG that must be delegated to be an active (=bonded) validator? <a href="#is-there-a-minimum-amount-of-atoms-that-must-be-delegated-to-be-an-active-bonded-validator" id="is-there-a-minimum-amount-of-atoms-that-must-be-delegated-to-be-an-active-bonded-validator"></a>

The minimum is `1 btsg`.

#### How do delegators choose their validators? <a href="#how-will-delegators-choose-their-validators" id="how-will-delegators-choose-their-validators"></a>

Delegators can choose any Validator according to their own criteria. However, some important factors to consider are:

* **Amount of self-delegated BTSG:** Validators with a larger amount of self-delegated BTSG have more "skin in the game." If they misbehave and get slashed, their own funds are just as much at stake as their Delegators'.&#x20;
* **Amount of delegated BTSG:** The total amount of delegated BTSG indicates the amount of voting power and influence the Validator has in the community. A Validator with a large amount of delegated BTSG is more likely to get chosen to produce more blocks and earn more rewards, but those rewards will be shared with more other Delegators. Bigger validators also decrease the decentralisation of the network by concentrating voting power.
* **Commission rate:** The higher the commission rate, the more the Validator earns, but the lower the rewards paid to Delegators.&#x20;
* **Track record:** The track record shows data about the past performance of the Validator, allowing a Delegators to view seniority, past votes on proposals, historical average uptime and how often the node was compromised.

Validators may also take measures of their own to establish their reputation and credentials among the Delegator community. For instance, many Validators run their own websites and stake on other networks. Some have their setups audited by third parties. Delegators should conduct their own research on Validators before staking their funds.&#x20;

To read more about how to conduct due diligence as a staker, see [this blog post (opens new window)](https://medium.com/@interchain_io/3d0faf10ce6f)

### Responsibilities <a href="#responsibilities" id="responsibilities"></a>

#### Do Validators need to be publicly identified? <a href="#do-validators-need-to-be-publicly-identified" id="do-validators-need-to-be-publicly-identified"></a>

There's no requirement to identify any individual or entity operating as a Validator. Delegators are required to evaluate Validators based on their individual merits. Validators can link their Validator setup to a website, where they can choose which information they share with the public. &#x20;

#### What are the responsibilities of a Validator? <a href="#what-are-the-responsibilities-of-a-validator" id="what-are-the-responsibilities-of-a-validator"></a>

Validators have two main responsibilities:

* **Actively participate in consensus:** Validators must run the correct version of the BitSong software, ensure that servers and equipment are always online, and that Validator private keys remain secure
* **Actively participate in governance:** Validators must vote on governance proposals.

However, Validators are also part of a community and as such, participation is key. Joining the relevant groups and social channels, and participating in discussions ensures that Validators are always up-to-date with events and the current state of the ecosystem.&#x20;

#### What does 'participate in governance' involve? <a href="#what-does-participate-in-governance-entail" id="what-does-participate-in-governance-entail"></a>

BTSG holders can propose and vote on proposals regarding the development and running of the BitSong ecosystem. Examples of decisions may be to change the number of Validators in the active set or to pass a particular upgrade.&#x20;

While any BTSG holders can participate in governance, Validators play a particularly valuable role in governance and must vote on all proposals. Not only is it likely that all proposals will affect them to some degree, but more importantly, they also represent the vote of their absent Delegators.&#x20;

#### What does staking imply? <a href="#what-does-staking-imply" id="what-does-staking-imply"></a>

Staking BTSG is comparable to placing a safety deposit on validation and the overall security of the BitSong network. Anyone can choose to stake or unstake as much of their BTSG as they wish. When a Validator or Delegator wants to unstake their BTSG, they send an`unbonding` transaction.&#x20;

Then, the staked BTSG undergo a **3-week unbonding period.** During the unbonding period, the staked BTSG may be subject to slashing, if the misbehavior that prompted the slashing took place before the Delegator initiated the unbonding transaction.

Validators and Delegators are eligible to receive block rewards and a share of transaction fees, and have the right to vote on governance matters. However, if a Validator misbehaves, then their total stake is subject to slashing. As such, all the Delegators who staked BTSG to the slashed Validator will also have a proportionate share of their stake slashed.&#x20;

Therefore, it's important that Delegators only stake their BTSG to Validators who they trust to behave in a way that won't result in their funds being slashed.&#x20;

#### Does a Validator have access to the Delegator's BTSG? <a href="#can-a-validator-run-away-with-their-delegators-atoms" id="can-a-validator-run-away-with-their-delegators-atoms"></a>

When a Delegator stakes their BTSG to a Validator, they're delegating their voting power to the Validator. So Validators with the most staked BTSG will have the most influence over governance decisions.&#x20;

However, the Validator never has access to the BTSG staked to them and cannot take custody of any staked funds. To be clear, there is no way that a Validator can steal delegated funds.&#x20;

Nevertheless, Delegators may still lose funds through slashing if their Validator misbehaves.&#x20;

#### How often will a validator be chosen to propose the next block? Does it go up with the amount of bonded BTSG? <a href="#how-often-will-a-validator-be-chosen-to-propose-the-next-block-does-it-go-up-with-the-quantity-of-bo" id="how-often-will-a-validator-be-chosen-to-propose-the-next-block-does-it-go-up-with-the-quantity-of-bo"></a>

The Validator chosen to propose the next block is called the proposer. Proposers are selected deterministically, and the proportional amount of bonded BTSG determines the frequency of being selected as the proposer. So if a validator holds 10% of the total bonded BTSG across all validators, they will be selected as the block proposer 10% of the time.&#x20;

#### ~~Will validators of the Cosmos Hub ever be required to validate other zones in the Cosmos ecosystem?~~ <a href="#will-validators-of-the-cosmos-hub-ever-be-required-to-validate-other-zones-in-the-cosmos-ecosystem" id="will-validators-of-the-cosmos-hub-ever-be-required-to-validate-other-zones-in-the-cosmos-ecosystem"></a>

~~Yes, they will. If governance decides so, validators of the Cosmos hub may be required to validate additional zones in the Cosmos ecosystem.~~

### Incentives <a href="#incentives" id="incentives"></a>

#### What is the incentive to stake? <a href="#what-is-the-incentive-to-stake" id="what-is-the-incentive-to-stake"></a>

Incentives are made up of two different revenue streams:

* **Block rewards:** Each block, new BTSG are minted according to the inflation algorithm and paid as staking rewards
* **Transaction fees:** Fees to transact on the BitSong network are paid in BTSG and used as staking rewards.&#x20;

The total revenue from each stream is distributed among Validators' staking pools according to the weight of their pool. Within each pool, the revenue is distributed again to each Delegator according to their individual stake.&#x20;

Validators also apply their commission to Delegators' revenue before it is allocated.

#### What is the incentive to run a Validator ? <a href="#what-is-the-incentive-to-run-a-validator" id="what-is-the-incentive-to-run-a-validator"></a>

Validators are incentivized through revenues and responsibility. Validators earn commission, which means they earn proportionately more revenue than Delegators to reflect their additional responsibilities and overheads. &#x20;

Validators have significant responsibilities within governance because if one of their Delegators doesn't vote, the Validator inherits their vote. Therefore, Validators can hold substantial voting power depending on the size of their delegation.

#### What is the Validator's commission? <a href="#what-are-validators-commission" id="what-are-validators-commission"></a>

Before revenues are allocated to Delegators, the Validator can apply a commission to it, expressed as a percentage. Validators can choose their commission rates and change them if they wish; however, they're competing in a market for Delegators to stake their BTSG. Therefore, the appropriate commission rate is defined by the market.&#x20;

#### How are block rewards distributed? <a href="#how-are-block-rewards-distributed" id="how-are-block-rewards-distributed"></a>

Let's illustrate block reward distribution using a simplified example. We can assume we have 10 Validators with equal voting power and a commission rate of 1% each. We can also assume that the block reward is 1000 BTSG and each Validator's pool comprises 20% self-bonded BTSG.&#x20;

Reward tokens do not go directly to the proposer. Instead, they are evenly spread among validators at each block. Based on the last block produced which generated 1000 BTSG rewards, each of the ten Validator pools has a reward allocation of 100 BTSG. These 100 BTSG will be distributed according to each participant's stake:

* Commission: `100*80%*1% = 0.8 btsg`
* Validator gets: `100\*20% + Commission = 20.8 btsg`
* All delegators get: `100\*80% - Commission = 79.2 btsg`

Then, each Delegator can claim their part of the 79.2 BTSG in proportion to their stake in the validator's staking pool.

#### How are fees distributed? <a href="#how-are-fees-distributed" id="how-are-fees-distributed"></a>

Fees are similarly distributed according to the weighted model. However, there is one exception – the block proposer can earn a bonus on the fees of the block they propose, only if they include more than the strict minimum of required precommits.

A Validator proposing the next block must include at least two-thirds of the precommits of the previous block. However, Validators can earn a bonus if they include more than two-thirds of the precommits.

The amount of the bonus ranges from 1% if the proposer includes the required minimum two-thirds precommits, which is also necessary for the block to be deemed valid. The proposer can earn up to 5% if they include 100% of the precommits.

The proposer should not delay too long though, or they risk the scenario that other validators may timeout and move on to the next proposer. So, validators must strike a balance between the time it takes to gather the most signatures and the increasing risk of losing out on any bonus at all by being the proposer of the next block.&#x20;

Let's take another concrete example where we have 10 validators with equal stake. Each of them applies a 1% commission rate and has 20% of self-delegated BTSG. The next block is ready and it's about to generate 1025.51020408 BTSG in fees.

First, the 2% [Community Pool](/features-and-modules/community-pool) levy is applied. The Community Pool exists to fund community proposals, which must go through governance.&#x20;

* `2% * 1025.51020408 = 20.51020408` BTSG go to the Community.

1005 BTSG now remain. Let's assume that the proposer included 100% of the signatures in its block so it could earn the maximum bonus of 5%.

We must now solve this equation to find the reward R for each validator:

`9*R + R + R*5% = 1005 ⇔ R = 1005/10.05 = 100`

* For the proposer validator:
  * The pool obtains `R + R * 5%`: 105 BTSG
  * Commission: `105 * 80% * 1%` = 0.84 BTSG
  * Validator's reward: `105 * 20% + Commission` = 21.84 BTSG
  * Delegators' rewards: `105 * 80% - Commission` = 83.16 BTSG (each Delegator will be able to claim their portion of these rewards in proportion to their stake)
* For each non-proposer validator:
  * The pool obtains R: 100 BTSG
  * Commission: `100 * 80% * 1%` = 0.8 BTSG
  * Validator's reward: `100 * 20% + Commission` = 20.8 BTSG
  * Delegators' rewards: `100 * 80% - Commission` = 79.2 BTSG (each Delegator will be able to claim their portion of these rewards in proportion to their stake)

#### What are the slashing conditions? <a href="#what-are-the-slashing-conditions" id="what-are-the-slashing-conditions"></a>

Slashing results from misbehavior on the part of a Validator. There are currently two actions classed as misbehavior:&#x20;

* **Double signing:** If a Validator is found by someone on chain A to have signed two blocks at the same height on chain A and chain B, and if chain A and chain B share a common ancestor, then the Validator will have their stake slashed by 5% on chain A.
* **Downtime:** If a Validator is down for more than 95% of the last 10.000 blocks, they will have their stake slashed by 0.01%.

#### Do Validators need to self-delegate BTSG? <a href="#do-validators-need-to-self-delegate-atoms" id="do-validators-need-to-self-delegate-atoms"></a>

Yes, there is a requirement for Validators to self-delegate at least `1 btsg`. Validators are not obliged to self-delegate more, but they should be able to demonstrate that they have skin in the game to Delegators.&#x20;

Validators can also signal a commitment to maintaining their self-delegated BTSG by setting a minimum amount for the self-delegation. Should the self-delegated BTSG fall below the minimum, the Validator and all of its Delegators will unbond automatically.&#x20;

#### How to prevent the concentration of stake to a few top validators? <a href="#how-to-prevent-concentration-of-stake-in-the-hands-of-a-few-top-validators" id="how-to-prevent-concentration-of-stake-in-the-hands-of-a-few-top-validators"></a>

Blockchain communities usually naturally migrate to a position that preserves decentralization, as a means of self-preservation. However, there are a few other ways to help promote this position:&#x20;

* **Penalty-free re-delegation:** Delegators can easily switch their stake from one Validator to another&#x20;
* **UI warning:** Wallets can display warnings to users if they try to delegate to a Validator that already has a substantial amount of staking power.

### Technical Requirements <a href="#technical-requirements" id="technical-requirements"></a>

#### What are the hardware requirements? <a href="#what-are-hardware-requirements" id="what-are-hardware-requirements"></a>

Validators can anticipate needing one or more data center locations equipped with redundant power, networking, firewalls, HSMs, and servers.

While hardware requirements may be relatively modest at first, they may rise as network usage increases. Prospective Validators are strongly encouraged to participate in the testnet as a means of establishing the current requirements.&#x20;

#### What are software requirements? <a href="#what-are-software-requirements" id="what-are-software-requirements"></a>

In addition to running a BitSong full node, Validators should also utilize monitoring, alerting, and management solutions for their setup.

#### What are bandwidth requirements? <a href="#what-are-bandwidth-requirements" id="what-are-bandwidth-requirements"></a>

Compared to chains like Ethereum or Bitcoin, BitSong has the capacity for very high throughput.

We recommend that data center nodes only connect to trusted full nodes in the cloud or other validators that know one other socially. This relieves the data center node from needing to mitigate denial-of-service attacks which will consume bandwidth.

Ultimately, as BitSong becomes more established and acquires more users, multigigabyte per day bandwidth is plausible.

#### What are the logistical requirements of becoming a Validator? <a href="#what-does-running-a-validator-imply-in-terms-of-logistics" id="what-does-running-a-validator-imply-in-terms-of-logistics"></a>

Successful Validators are usually run by multiple highly skilled individuals who share the responsibility for providing continuous attention to the operation. It takes considerably more effort, resources, and skill than running a mining ASIC, for example.&#x20;

#### How to handle key management? <a href="#how-to-handle-key-management" id="how-to-handle-key-management"></a>

Validators will need to run a hardware security module (HSM) that supports ed25519 keys. Here are some of the potential options:

* YubiHSM 2
* Ledger Nano S
* Ledger BOLOS SGX enclave
* Thales nShield support

BitSong does not recommend one solution over another.&#x20;

#### What can validators expect in terms of operations? <a href="#what-can-validators-expect-in-terms-of-operations" id="what-can-validators-expect-in-terms-of-operations"></a>

Validators who run their operation like a tight ship will avoid unexpected unbonding or being slashed. Validators must be available to respond to attacks or outages and to be able to maintain security and isolation in the data center.&#x20;

#### What are the maintenance requirements? <a href="#what-are-the-maintenance-requirements" id="what-are-the-maintenance-requirements"></a>

Validators are required to perform regular software updates to accommodate upgrades and bug fixes. When new modules or functionality are introduced to BitSong, there may be issues that require vigilance on the part of the Validator community.&#x20;

#### How can validators protect themselves from denial-of-service attacks? <a href="#how-can-validators-protect-themselves-from-denial-of-service-attacks" id="how-can-validators-protect-themselves-from-denial-of-service-attacks"></a>

Denial-of-service attacks or DoS attacks refer to the scenario where an attacker sends a flurry of internet traffic to an IP address. In doing so, they prevent the server at the IP address from being able to connect to the internet.

In the blockchain scenario, the attacker scans the network in an attempt to discover the IP addresses of validator nodes. It then tries to disconnect them from communication by flooding them with traffic.

Validators can mitigate these risks by carefully structuring their network topology in a so-called sentry node architecture.

Validator nodes should only connect to full nodes they trust - either because they operate the nodes themselves or because the nodes are run by other validators they know socially.&#x20;

A validator node typically runs in a data center, most of which are linked directly to the networks of major cloud providers. The validator can use those links to connect to sentry nodes, which run in the cloud.&#x20;

This setup shifts the responsibility of denial-of-service from the validator's node directly to its sentry nodes. It may require new sentry nodes be set up to mitigate attacks on existing ones.

It's possible to spin up sentry nodes or change their IP addresses relatively quickly. Because the links to the sentry nodes exist in private IP space, an internet-based DoS attack does not affect them directly. Thus, this setup will ensure that validator block proposals and votes are always transmissible to the rest of the network.

For more on sentry node architecture, see [this (opens new window)](https://forum.cosmos.network/t/sentry-node-architecture-overview/454).


# Validator Security

## Validator Security <a href="#validator-security" id="validator-security"></a>

BitSong encourages Validators to run their operations independently to ensure diverse setups to increase network resilience. However, these are some general guidelines and information.&#x20;

### Key Management - HSM <a href="#key-management-hsm" id="key-management-hsm"></a>

Validator key security is absolutely paramount. If a Validator's key becomes compromised, their entire staked pool, including delegated BTSG, is at risk. Hardware security modules are hardware-based key management solutions that help to offset the risk of a breach.&#x20;

HSM modules must support `ed25519` signatures for the BitSong blockchain. The YubiHSM2 supports `ed25519` and [this yubikey library is available (opens new window)](https://github.com/iqlusioninc/yubihsm.rs). Please note that the YubiHSM can protect a private key but cannot ensure in a secure setting that it won't sign the same block twice.

We are also working on extending our Ledger Nano S application to support validator signing. This app can store recent blocks and mitigate double signing attacks.

We will update this page when more key storage solutions become available.

### Sentry Nodes (DDoS Protection) <a href="#sentry-nodes-ddos-protection" id="sentry-nodes-ddos-protection"></a>

Validators have a responsibility to ensure that the network can withstand denial of service (DoS) attacks.

Validators can mitigate these risks by carefully structuring their network topology in a so-called sentry node architecture.

Validator nodes should only connect to full nodes they trust - either because they operate the nodes themselves or because the nodes are run by other validators they know socially.&#x20;

A validator node typically runs in a data center, most of which are linked directly to the networks of major cloud providers. The validator can use those links to connect to sentry nodes, which run in the cloud.&#x20;

This setup shifts the responsibility of denial-of-service from the validator's node directly to its sentry nodes. It may require new sentry nodes to be set up to mitigate attacks on existing ones.

It's possible to spin up sentry nodes or change their IP addresses relatively quickly. Because the links to the sentry nodes exist in private IP space, an internet-based DoS attack does not affect them directly. Thus, this setup will ensure that validator block proposals and votes are always transmissible to the rest of the network.

Follow these steps to set up your sentry node architecture:&#x20;

Validators nodes should edit their config.toml:

\# Comma separated list of nodes to keep persistent connections to&#x20;

\# Do not add private peers to this list if you don't want them advertised persistent\_peers =\[list of sentry nodes]&#x20;

\# Set true to enable the peer-exchange reactor pex = false

Sentry Nodes should edit their config.toml:

\# Comma separated list of peer IDs to keep private (will not be gossiped to other peers)&#x20;

\# Example ID: 3e16af0cead27979e1fc3dac57d03df3c7a77acc\@3.87.179.235:26656 private\_peer\_ids = "node\_ids\_of\_private\_peers"

### Environment Variables <a href="#environment-variables" id="environment-variables"></a>

&#x20;


# IBC

## Official BitSong IBC Channels

| source chain-id | source channel | source denom | destination chain-id | destinaion channel | IBC token-address on destinaion chain                                |
| --------------- | -------------- | ------------ | -------------------- | ------------------ | -------------------------------------------------------------------- |
| bitsong-2b      | channel-0      | ubtsg        | osmosis-1            | channel-73         | IBC/4E5444C35610CC76FC94E7F7886B93121175C28262DDFDDE6F84E82BF2425452 |
| bitsong-2b      | channel-1      | ubtsg        | cosmoshub-4          | channel-229        | IBC/E7D5E9D0E9BF8B7354929A817DD28D4D017E745F638954764AA88522A7A409EC |
| osmosis-1       | channel-73     | uosmo        | bitsong-2b           | channel-0          | IBC/ED07A3391A112B175915CD8FAF43A2DA8E4790EDE12566649D0C2F97716B8518 |
| cosmoshub-4     | channel-229    | uatom        | bitsong-2b           | channel-1          | IBC/C4CFF46FD6DE35CA4CF4CE031E643C8FDC9BA4B99AE598E9B0ED98FE3A2319F9 |


# FAQ

**What is Bitsong?**

BitSong is a Blockchain based Ecosystem fully designed to empower the music industry. It’s a decentralized ecosystem of services providing the global community of artists, fans and music providers with a trustless music marketplace that becomes the industry’s point of reference.

**What problem does BitSong solve?**

The leading streaming music companies have been routinely accused of treating artists poorly through duplicitous contract structures and low payments. All of that has created a low-trust environment and confused artists and fans over whom to support.

**What’s the BitSong goal?**

Give back the power to the music! Our mission is to decentralize the music sector by simplifying the bureaucracy to offer artists a meritocratic, transparent, fast and intermediary-free earnings model while users gain a new way to listen to music and earn.

**Who is  BitSong for?**

* Fans;&#x20;
* Artists;&#x20;
* Record Labels;&#x20;
* Crypto investors;&#x20;
* Investors;&#x20;
* Developers.

**Why should fans listen to music or take part in BitSong?**

BitSong it’s a new way to engage with your artists. Users have a single platform for streaming/downloading music products, receive rewards for their activity, interact with artists and support them, buy NFTs, buy and sell Artist Fan Token and become music investors.

**Why should Artists join BitSong?**

Artists can tokenize their music and restore a new equilibrium where art, real engagement, and passion wins. They now have royalties in real-time and new revenue streams since they own an economy based on tokens and NFTs.

**Why should a Record Label join BitSong?**

In BitSong Labels and distributors are entirely decentralized. Opening a new label, managing talents and recruiting new artists is now easier and more efficient. Thanks to the blockchain technology now Labels and Artists earn real-time royalties and Create & sell NFTs.

**Why should I invest in BitSong?**

BitSong is an ecosystem of services aimed at the global community of artists, fans and music providers with a trustless music marketplace. BitSong aspires to become the main landmark in the music industry. You can invest in music projects, selling and buying shares, being part of the governance of BitSong and of course buying and selling BTSG crypto currency.

&#x20;**I am a developer. What can I do in BitSong?**

You can build your own dApp using high level blockchain development tools available in the BitSong Console. Follow us on [Github](https://github.com/bitsongofficial).

**I am a validator. What can I do in BitSong?**

You can run a full node to earn BTSG for validating transactions, and vote on governance proposals.

**What is a FanToken?**

It’s the Artist Coin! Artists and Labels can tokenize themselves and create their own economy in the BitSong ecosystem.

**Why should users invest in Artist or Labels FanToken?**

Engagement becomes a currency of exchange between musicians and fans who establish a relationship of trust and contribute together to the success of musical projects and products.

**Why should Artists or Record Labels create their own Fan - Token?**

Through the Fan Token system, the Artist earns everything they have always wanted and claimed: close contact with fans, having the opportunity to independently finance their own projects, acquiring the right notoriety based on the success of their brand and songs, and get the right rewards for hard work.

**Has a FanToken an economic value?**

Yes, it works the same as crypto currency! The economics value follows the BTSG index and of course the Artist progres&#x73;**.**

**What is Staking?**

Staking is like entrusting your BTSG. You can gain interest**s** just putting your BTSG into staking and earning passive incomes from it.

**Can I claim my earnings whenever I want?**

You can immediately claim your rewards anytime or request to collect your BTSG from staking, this request will be accepted in 21 days.This parameter follows the BitSong community rules.

**Is staking for everyone?**

Everybody can hold BTSG funds in their wallet, stake their coins and start to earn rewards.

**Who are Validators?**

A Validator is like a big decentralized notary for the blockchain. In BitSong we have more than 50 Validators, a really huge number compared to other blockchains. For example, if you are trying to do an incorrect action or give a wrong input, Validators will block you to protect all the BTSG owners.

**What is the Governance?**

The governance is a form of direct democracy through on-chain voting mechanisms. In BitSong rules are made by the community, who is part of the ecosystem, proposes and votes on the BitSong laws.

**What is the Community Pool?**

The Community Pool is a fund composed of 2% of the total amount of BTSG.


# Glossary

{% hint style="warning" %}
We are moving our **documentation** to the new "[**BitSong, the blockchain for music**](https://bitsong.io/en)" website. To access the most up-to-date and complete version of our guides and articles, please visit our new [**bitsong documentation**](https://bitsong.io/en/docs) website. This old documentation site will no longer be maintained or updated, so we **strongly recommend** referring to the new [**bitsong documentation**](https://bitsong.io/en/docs) website for the latest information. If you can't find what you're looking for on the new site, please be patient as we are still in the process of migrating all of our content. Thank you for your understanding!\
\
Visit the new article <https://bitsong.io/en/docs/glossary>
{% endhint %}

**Account** - A public and private keypair that “holds” your funds.

**Address/ Public key** - Used to send and receive transactions on a blockchain network. An address is an alphanumeric character string, which can also be represented as a scannable QR code. For example: bitsong1yuajbkafahg4uiuhvgv08

**Block** - Think of a blockchain as consisting of a ledger that is being constantly updated, and those changes synced between any number of different nodes.After a certain number of transactions have been added to the ledger and consensus has been reached among the nodes that the transactions are valid, then they are cryptographically locked into a “block” and officially recorded.

**Block Explorer** - An online tool to view all transactions that have taken place on the blockchain, network hash rate, and transaction growth, among other useful information. In short, a block explorer is a tool that provides detailed analytics about a blockchain network since its first day at the genesis block. We can say a block explorer acts as a search engine and browser where users can find information about individual blocks, public addresses, and transactions associated with a specific cryptocurrency.

**Block Height** - The number of blocks connected together in the blockchain. For example, Height 0 would be the very first block, which is also called the Genesis Block.

**Bots** - Automated trading software bots that execute trade orders extremely quickly, based on a preset algorithm of buy-and-sell rules.

[BTSG](/btsg/what-is-btsg) - the ultimate currency for music, powering all the features of the BitSong ecosystem

[Community Pool](/features-and-modules/community-pool) - a self-managing fund that exists to support the ongoing development of the BitSong ecosystem and community

**Confirmation** - A confirmation happens when the network has verified the blockchain transaction.

**Consensus** - The process used by a group of peers, or nodes, on a blockchain network to agree on the validity of transactions submitted to the network.

**Decentralized Application (Dapp**) - An open source, software application with backend code running on a decentralized peer-to-peer network rather than a centralized server. You may see alternate spellings: dApps, DApps, Dapps, and Đapps.

**Deflation** - Reduction of the general level of prices in an economy. May also refer to deflationary monetary policy, such as most cryptocurrecy, where there is a fixed supply of coins

**Dump** - To sell off all your coins.

**Exchange** - A place to trade cryptocurrency. Centralized exchanges, operated by companies like Coinbase and Gemini, function as intermediaries, while decentralized exchanges do not have a central authority.

**Decentralized Exchange  (DEX)**- A decentralized exchange is a platform for exchanging cryptocurrencies based on functionality programmed on the blockchain (i.e., in smart contracts). The trading is peer-to-peer, or between pools of liquidity. This is in contrast with a centralized exchange, which is more akin to a bank or investment firm that specializes in cryptocurrencies.

[Delegator](/delegators) – someone who delegates their BTSG tokens to a Validator to help secure the BitSong blockchain in return for a share of rewards

[DPoS](/features-and-modules/governance) - delegated Proof-of-Stake, or DPoS, is the governance model that BitSong uses to secure its blockchain

**Epoch** - An epoch, in general, is a measure of time, or of blockchain progression, on a given blockchain.

[Fan Tokens](/features-and-modules/fan-tokens) - the artist's cryptocurrency, Fan Tokens are a branded token allowing artists and fans to connect through a new channel of value

**Faucet** A faucet is an application, sometimes a very simple website, other times more complex, that dispenses cryptocurrency for use on test networks only.&#x20;

**Fiat** - Government-issued currency. For example, US Dollars (USD), Euros (EUR), Yuan (CNY), and Yen (JPY).

**Futures -** A futures contract is a standardized legal agreement to buy or sell a particular commodity or asset at a predetermined price at a specified time in the future. They are different from forward contracts, which can be customized for each trade and can be conducted over-the-counter, instead of being traded on an exchange.

**Gas** - A measure of the computational steps required for a transaction on the network.

**Gas Limit** - A term used on the crypto platform that refers to the maximum amount of gas the user is willing to spend on a transaction.

**Genesis block** - The initial block of data computed in the history of a blockchain network.

**Hold** - A type of passive investment strategy where you hold an investment for a long period of time, regardless of any changes in the price or markets.

[IBC](/features-and-modules/ibc) - Inter Blockchain Communication, or IBC, is a protocol that’s part of the Cosmos technology stack, allowing seamless communication between blockchains. IBC enables BitSong to interoperate with any other IBC-enabled blockchain in the Cosmos ecosystem

**Inflation** - A general increase in prices and fall in the purchasing value of money.

**InterPlanetary File System (IPFS) -** A decentralized file storage and referencing system for the Ethereum blockchain. [IFPS](https://ipfs.io/) is an open source protocol that enables storing and sharing hypermedia (text, audio, visual) in a distributed manner without relying on a single point of failure. This distributed file system enables applications to run faster, safer and more transparently.

[Keplr](/btsg/wallets#keplr) - a BTSG-compatible wallet, also compatible with other IBC-enabled blockchains in the Cosmos ecosystem

**Ledger** - An hardware wallet to secure, store and manage your crypto assets.

[Liquidity Module](broken://pages/O6cpxUVmu5FSjk0nvDOI) - enables liquidity for Fan Tokens and NFTs in the BitSong Marketplace

[Liquidity provider](/btsg/liquidity-provider) - someone who provides liquidity to a token pool on a decentralized exchange

**Mainnet** - The primary network where actual transactions take place on a specific distributed ledger. For example, The Ethereum mainnet is the public blockchain where network validation and transactions take place.

**Market Cap -** Short for Market Capitalization, this term refers to the total value held in a particular industry, market, company, or asset.&#x20;

**Max Supply** - The best approximation of the maximum amount of coins that will ever exist in the lifetime of the cryptocurrency.

**Mnemonic phrase** - A mnemonic phrase (also known as mnemonic seed, or seed phrase) is a list of words used in sequence to access or restore your cryptocurrency assets. It should be kept secret from everyone else. It is a standard in most HD wallets.

[Metamask](/btsg/wallets#metamask) - a BTSG-compatible wallet, also compatible with other Ethereum-based tokens and applications

**Mining** - A process where blocks are added to a blockchain, verifying transactions. It is also the process through which new bitcoins or some altcoins are created.

**Node (full node) -** Any computer connected to the blockchain network is referred to as a node. A full node is a computer that can fully validate transactions and download the entire data of a specific blockchain.&#x20;

[NFTs](/features-and-modules/nfts) - non-fungible tokens, or NFTs are unique digital assets enabling artists to create digital scarcity around their work and merchandise

**Peer to Peer (P2P)** - The decentralized interactions between parties in a distributed network, partitioning tasks or workloads between peers.

**Private Key -** A private key is an alphanumeric string of data that, in MetaMask, corresponds to a single specific account in a wallet. Private keys can be thought of as a password that enables an individual to access their crypto account. *Never reveal your private key to anyone, as whoever controls the private key controls the account funds. If you lose your private key, then you lose access to that account.*

**Protocol** - A set of rules that dictate how data is exchanged and transmitted. This pertains to cryptocurrency in blockchain when referring to the formal rules that outline how these actions are performed across a specific network.

**Private Key** - In cryptography, you have a keypair: the public and private key. You can derive a public key from a private key, but cannot derive a private key from a public key. The public key, therefore, is obtained and used by anyone to encrypt messages before they are sent to a known recipient with a matching private key for decryption. By pairing a public key with a private key, transactions not dependent on trusting involved parties or intermediaries. The public key encrypts a message into an unreadable format and the corresponding private key makes it readable again for the intended party, and the intended party only.

**Public address -** Is the cryptographic hash of a public key, allowing the user to use it as an address to request for payment.A public address is the cryptographic hash of a public key, allowing the user to use it as an address to request for payment.

**Scam** - A fraudulent or deceptive cryptocurrency or ICO.

**Seed (phrase) / Secret Recovery Phrase -** The seed phrase, mnemonic, or Secret Recovery Phrase is a crucial part of public blockchain technology, they all refer to a set of ordered words which correspond to determined values. These values never change, and therefore the same string of words in the same order will always produce the same number–this is the underlying functionality that allows seed phrases to back up wallets. The Secret Recovery Phrase is exactly what it sounds like: something that is secret, and should be known only to the owner of the account. If the seed phrase is given to someone else, that person has complete control over the account; they can drain it of tokens and funds, execute transactions with it, etc.

**Smart contract** - A smart contract is a computer protocol intended to facilitate, verify, or enforce a contract on the blockchain without third parties.

[Slashing](/features-and-modules/slashing) - the act of penalizing a Validator for an act deemed to be against the overall good of the blockchain

**Stable coin** - A cryptocurrency with extremely low volatility, sometimes used as a means of portfolio diversification. Examples include fiat-pegged cryptocurrency.

[Staking](/features-and-modules/staking) - the act of depositing cryptocurrencies to help secure the BitSong blockchain, either as a Validator or Delegator&#x20;

**Testnet** - An alternative blockchain developers use to test applications in a near-live environment.

**Trade Volume** - Is the amount of the cryptocurrency that has been traded in the last 24 hours.

**Transaction Fee -** A small fee imposed on some transactions sent across a blockchain network. The transaction fee is awarded to the miner that successfully hashes the block containing the relevant transaction.

**Wallet -** A designated storage location for digital assets (cryptocurrency) that has an address for sending and receiving funds. The wallet can be online, offline, or on a physical device.

[Validator](broken://pages/6EzxHKnSaNzX4ma81oi2) - someone who operates a full node and validates transactions to secure the BitSong blockchain in return for rewards

**Volatily** - A statistical measure of dispersion of returns, measured by using the standard deviation or variance between returns from that same security or market index.

**Volume** - The amount of cryptocurrency that has been traded during a certain period of time, such as the last 24 hours or more. Volume can show the direction and movement of the cryptocurrency as well as a prediction of future price and its demand.

**White paper** - A document prepared by an ICO project team to interest investors with its vision, cryptocurrency use and cryptoeconomic design, technical information, and a roadmap for how it plans to grow and succeed.

\ <br>


# Roadmap

![](/files/E00VgEUpeP93FrB0BOtq)


# Media Kit

![](/files/zMbVub9LstQnd2AvcbFR)

## A Blockchain Ecosystem to Empower the Music Industry

Artists, fans, distributors and labels in one single great, efficient and transparent channel. BitSong is the innovation that music need.

Part of the Cosmos Blockchain Ecosystem, BitSong’s decentralized network is based on a robust system of governance and a Delegated Proof-of-Stake consensus.&#x20;

#### BitSong World, you are the main character

The music industry has never been so dynamic, clear and transparent. Automated rules run the ecosystem.

![](/files/oSaqnliZsfuTo38a8HeX)

## BitSong ecosystem

#### $BTSG

BTSG is the ultimate currency for music, powering the economy of the BitSong ecosystem. Buy, sell, trade Fantokens, and NFTs on the BitSong marketplace with BTSG. Swap BTSG for other cryptocurrencies. Stake BTSG to secure the BitSong network and earn rewards.

#### Fantoken&#x20;

FanTokens let you connect with music on a whole new level. For the first time the relationship between Artists and Fans become a financiale asset. Artists can create their own Token and connect with their fans as it has never been before! Fans can explore VIP experiences, crowdfund up-and-coming talent,  seek funding for their next favoriteband tour, buy unique digital album art or discover exclusive releases.&#x20;

#### NFT

Artists can create their own NFT, Non-Fungible-Token: it is an asset, or a monetizable property that cannot be replicated in any way, but can still be bought for a specific amount of currency like any other asset. It is unique and works exactly like a collector's item and a certificate of ownership at the same time, ergo it can be bought, stored, exchanged and sold but each NFT accumulates value independently.

#### BitSong Player&#x20;

BitSong’s Player will operate with a full set of metadata from the start, meaning Aritists always receive 100% of the royalties they’re owed. Every single play. Every single time. In real time.

### Download Media BitSong Assets

{% file src="/files/y9zu6XgEG12u9jPsLh4a" %}

{% file src="/files/CYgA08BuPY8d0W7h38kQ" %}

{% file src="/files/luh1sbA0k1H9cWL5VsS4" %}

{% file src="/files/gctsBn4rSP8Offs9WqXL" %}

{% file src="/files/vaXshFT4zjJyGgjvtaOW" %}


# Links

**Website**: <https://bitsong.io/>\
**Sinfonia**: [https://sinfonia.zone](https://sinfonia.zone/)\
**Sinfonia App**: [https://app.sinfonia.zone](https://app.sinfonia.zone/)\
**Twitter:** <https://twitter.com/BitSongOfficial>\
**Twitter Hispanic**: <https://twitter.com/BitSongHispanic>\
**Twitter Sinfonia**: <https://twitter.com/sinfoniazone>\
**GitHub**: <https://github.com/bitsongofficial/>\
**Telegram announcements**: <https://t.me/BitSongOfficial>\
**Telegram community chat:** <https://t.me/bitsong_ico>\
**Discord:** <https://discord.com/invite/mZC9Yk3>\ <br>


# Install go-bitsong

{% hint style="warning" %}
We are moving our **documentation** to the new "[**BitSong, the blockchain for music**](https://bitsong.io/en)" website. To access the most up-to-date and complete version of our guides and articles, please visit our new [**bitsong documentation**](https://bitsong.io/en/docs) website. This old documentation site will no longer be maintained or updated, so we **strongly recommend** referring to the new [**bitsong documentation**](https://bitsong.io/en/docs) website for the latest information. If you can't find what you're looking for on the new site, please be patient as we are still in the process of migrating all of our content. Thank you for your understanding!\
\
Visit the new article <https://bitsong.io/en/docs/blockchain/install-go-bitsong>
{% endhint %}

This guide will explain how to install the `bitsongd` binary into your system.

On **Ubuntu** start by updating your system:

```
sudo apt update
sudo apt upgrade
```

### Install pre-requisites

On Ubuntu this can be done with the following:

```
sudo apt install git build-essential ufw curl jq --yes
```

### Install Go

Install `go` by following the [official docs](https://golang.org/doc/install). On Ubuntu, you can probably use:

```
wget -q -O - https://git.io/vQhTU | bash -s -- --version 1.19.5
```

### Install go-bitsong binary

Clone the `go-bitsong` repo, checkout and install `v0.15.0` :

```
cd $HOME
git clone https://github.com/bitsongofficial/go-bitsong
cd go-bitsong
git checkout v0.15.0
make install
```

> *NOTE*: If you still have issues at this step, please check that you have the latest stable version of GO installed.

Verify that everything is OK:

```
bitsongd version
```

`bitsongd` for instance should output something similar to:

```
0.15.0
```


# Join the Mainnet

{% hint style="warning" %}
We are moving our **documentation** to the new "[**BitSong, the blockchain for music**](https://bitsong.io/en)" website. To access the most up-to-date and complete version of our guides and articles, please visit our new [**bitsong documentation**](https://bitsong.io/en/docs) website. This old documentation site will no longer be maintained or updated, so we **strongly recommend** referring to the new [**bitsong documentation**](https://bitsong.io/en/docs) website for the latest information. If you can't find what you're looking for on the new site, please be patient as we are still in the process of migrating all of our content. Thank you for your understanding!\
\
Visit the new article <https://bitsong.io/en/docs/blockchain/join-the-mainnet>
{% endhint %}

Make sure to have the [latest go-bitsong version installed](/blockchain/install-go-bitsong). First, initialize the node.

```
bitsongd init <your_custom_moniker>
```

**Note** Monikers can contain only ASCII characters. Using Unicode characters is not supported and renders your node unreachable.

By default, the `init` command creates your `~/.bitsongd` directory with subfolders `config` and `data`. In the `config` directory, the most important files for configuration are `app.toml` and `config.toml`.

You can edit the `moniker` in the `~/.bitsongd/config/config.toml` file:

```
# A custom human readable name for this node
moniker = "<your_custom_moniker>"
```

For optimized node performance, edit the `~/.bitsongd/config/app.toml` file to enable the anti-spam mechanism and reject incoming transactions with less than the minimum gas prices:

```
# This is a TOML config file.
# For more information, see https://github.com/toml-lang/toml

###############################################################################
###                           Base Configuration                            ###
###############################################################################

# The minimum gas prices a validator is willing to accept for processing a
# transaction. A transaction's fees must meet the minimum of any denomination
# specified in this config (e.g. 0.25token1;0.0001token2).

minimum-gas-prices = "0.0025ubtsg"
```

Your full node has been initialized!

### Genesis & Seeds

#### Copy the Genesis File

Fetch the mainnet's `genesis.json` file into `bitsongd`'s config directory.

```
wget -O ~/.bitsongd/config/genesis.json https://raw.githubusercontent.com/bitsongofficial/networks/master/bitsong-2b/genesis.json
```

#### **Set persistent peers**

Your node needs to know how to find peers. You'll need to add healthy seed nodes to `$HOME/.bitsongd/config/config.toml`

```
export PEERS="e2b9971222adf71f7199c670b7e85471c447e926@157.90.255.143:26656,120740c15a8a19c232b1aa4d80b20de248b33db3@135.181.129.94:26656,d741773bc5eecbefb7b14fcca5e3e0fedd49d5a3@157.90.95.104:26656,6e93a30587671e2cecacbcbb27092809bb20249f@95.217.203.59:31656,adfe1cf240780cf8d58266171ced72fb4e9a7a6d@23.226.14.168:26656,f36d3a926ae0583e60f00e7bc54711f3cb7fe769@195.201.58.166:26656,9c9f030298bdda9ca69de7db8e9a3aef33972fba@135.181.16.236:31656,9806602afb65ba45d1048d65285d5c6e50285088@178.18.242.242:26656,4fdd438ea70927003022ecc308e36bc1924ec598@51.210.104.207:26656,3cf3effd3ecb33bdbb5c5e6528c88fde4869b97c@116.202.139.113:26656,075cf589e44c74687ef3a4df3a583f482bce57e0@46.166.143.79:26656,f9d318eaf38988ce2b65b795068d86b214866c91@141.94.170.26:26256,fa932748b327fdde6d235b28a9850f8b8bd3326a@95.217.119.101:31656,d52f6e4fe1819133474e977d7e1d73124d1f4af5@95.217.156.76:26656,5ebab02914638005773dac8026f441e06c115a44@74.207.226.176:26656,e5428ce29ccd26434828a577906ac9c413ca6a48@80.71.57.42:26656,2afc435e2246ff3f16ade85b52264367945d12b5@176.58.124.226:26656,2cd6bb75fc9279c62c0ef3af82fbe08632743472@bitsong-peer.panthea.eu:31656"
sed -i.bak -e "s/^persistent_peers *=.*/persistent_peers = \"$PEERS\"/" ~/.bitsongd/config/config.toml
```

### Synchronise the Node <a href="#synchronise-the-wallet" id="synchronise-the-wallet"></a>

Now we have to syncronise the node with the current state of the blockchain. The fastest way to achieve this is by using [state sync](https://medium.com/tendermint/tendermint-core-state-sync-for-developers-70a96ba3ee35), which we will use for this purpose.

```
sudo systemctl stop bitsong

SNAP_RPC="https://rpc.bitsong.forbole.com:443"
SNAP_RPC2="https://bitsong.stakesystems.io:2053"

LATEST_HEIGHT=$(curl -s $SNAP_RPC/block | jq -r .result.block.header.height); \
BLOCK_HEIGHT=$((LATEST_HEIGHT - 1000)); \
TRUST_HASH=$(curl -s "$SNAP_RPC/block?height=$BLOCK_HEIGHT" | jq -r .result.block_id.hash)

peers="e2b9971222adf71f7199c670b7e85471c447e926@157.90.255.143:26656,120740c15a8a19c232b1aa4d80b20de248b33db3@135.181.129.94:26656,bbfb37b3c44c8148b6af7adfa016ec8fabff69d1@121.78.247.243:16656,d741773bc5eecbefb7b14fcca5e3e0fedd49d5a3@157.90.95.104:26656,6e93a30587671e2cecacbcbb27092809bb20249f@95.217.203.59:31656,adfe1cf240780cf8d58266171ced72fb4e9a7a6d@23.226.14.168:26656,f36d3a926ae0583e60f00e7bc54711f3cb7fe769@195.201.58.166:26656,9c9f030298bdda9ca69de7db8e9a3aef33972fba@135.181.16.236:31656,9806602afb65ba45d1048d65285d5c6e50285088@178.18.242.242:26656,4fdd438ea70927003022ecc308e36bc1924ec598@51.210.104.207:26656,3cf3effd3ecb33bdbb5c5e6528c88fde4869b97c@116.202.139.113:26656,2cd6bb75fc9279c62c0ef3af82fbe08632743472@bitsong-peer.panthea.eu:31656"

sed -i.bak -e "s/^persistent_peers *=.*/persistent_peers = \"$peers\"/" $HOME/.bitsongd/config/config.toml

sed -i.bak -E "s|^(enable[[:space:]]+=[[:space:]]+).*$|\1true| ; \
s|^(rpc_servers[[:space:]]+=[[:space:]]+).*$|\1\"$SNAP_RPC,$SNAP_RPC2\"| ; \
s|^(trust_height[[:space:]]+=[[:space:]]+).*$|\1$BLOCK_HEIGHT| ; \
s|^(trust_hash[[:space:]]+=[[:space:]]+).*$|\1\"$TRUST_HASH\"|" $HOME/.bitsongd/config/config.toml

cp $HOME/.bitsongd/data/priv_validator_state.json $HOME/.bitsongd/priv_validator_state.json.backup

bitsongd tendermint unsafe-reset-all --keep-addr-book --home "$HOME/.bitsongd"

mv $HOME/.bitsongd/priv_validator_state.json.backup $HOME/.bitsongd/data/priv_validator_state.json

sudo systemctl start bitsong

sudo journalctl -u bitsong -f
```

### Enable the REST API <a href="#enable-the-rest-api" id="enable-the-rest-api"></a>

By default, the REST API is disabled. To enable the REST API, edit the `~/.bitsongd/config/app.toml` file, and set `enable` to `true` in the `[api]` section.

```
###############################################################################
###                           API Configuration                             ###
###############################################################################

[api]

# Enable defines if the API server should be enabled.
enable = false

# Swagger defines if swagger documentation should automatically be registered.
swagger = false

# Address defines the API server to listen on.
address = "tcp://0.0.0.0:1317"
```

Optionally, you can activate swagger by setting `swagger` to `true` or change the port of the REST API in the parameter `address`. After restarting your application, you can access the REST API on `YOURNODEIP:1317`.

### GRPC Configuration <a href="#grpc-configuration" id="grpc-configuration"></a>

By default, gRPC is enabled on port `9090`. In the `~/.bitsongd/config/app.toml` file, you can make changes in the gRPC section. To disable the gRPC endpoint, set `enable` to `false`. To change the port, use the `address` parameter.

```
###############################################################################
###                           gRPC Configuration                            ###
###############################################################################

[grpc]

# Enable defines if the gRPC server should be enabled.
enable = true

# Address defines the gRPC server address to bind to.
address = "0.0.0.0:9090"
```

### Background Process <a href="#background-process" id="background-process"></a>

To run the node in a background process with automatic restarts, you can use a service manager like `systemd`. To set this up run the following:

```
sudo tee /etc/systemd/system/bitsongd.service > /dev/null <<EOF  
[Unit]
Description=BitSong Network Daemon
After=network-online.target

[Service]
User=$USER
ExecStart=$(which bitsongd) start
Restart=always
RestartSec=3
LimitNOFILE=4096

[Install]
WantedBy=multi-user.target
EOF

```

Then setup the daemon

```
sudo -S systemctl daemon-reload
sudo -S systemctl enable bitsongd
```

We can then start the process and confirm that it is running

```
sudo -S systemctl start bitsongd

sudo service bitsongd status
```


# Create Validator

{% hint style="warning" %}
We are moving our **documentation** to the new "[**BitSong, the blockchain for music**](https://bitsong.io/en)" website. To access the most up-to-date and complete version of our guides and articles, please visit our new [**bitsong documentation**](https://bitsong.io/en/docs) website. This old documentation site will no longer be maintained or updated, so we **strongly recommend** referring to the new [**bitsong documentation**](https://bitsong.io/en/docs) website for the latest information. If you can't find what you're looking for on the new site, please be patient as we are still in the process of migrating all of our content. Thank you for your understanding!\
\
Visit the new article <https://bitsong.io/en/docs/blockchain/create-validator>
{% endhint %}

### Prerequisites <a href="#prerequisites" id="prerequisites"></a>

* You have completed [how to run a full BitSong node](/blockchain/join-the-mainnet), which outlines how to install, connect, and configure a node.
* You are familiar with `bitsongd`.
* you have read through [the validator FAQ](/validators/validator-faq)

### Create a new validator <a href="#id-2-create-a-new-validator" id="id-2-create-a-new-validator"></a>

To create the validator and initialize it with a self-delegation, run the following command. `key-name` is the name of the private key that is used to sign transactions.

```
bitsongd tx staking create-validator \
    --amount=5000000ubtsg \
    --pubkey=$(bitsongd tendermint show-validator) \
    --moniker="<your-moniker>" \
    --chain-id=<chain_id> \
    --from=<key-name> \
    --commission-rate="0.10" \
    --commission-max-rate="0.20" \
    --commission-max-change-rate="0.01" \
    --min-self-delegation="1"
```

{% hint style="info" %}
When you specify commission parameters, the `commission-max-change-rate` is measured as a percentage-point change of the `commission-rate`. For example, a change from 1% to 2% is a 100% rate increase, but the `commission-max-change-rate` is measured as 1%.
{% endhint %}

### Confirm your validator is active <a href="#id-3-confirm-your-validator-is-active" id="id-3-confirm-your-validator-is-active"></a>

If running the following command returns something, the validator is active.

```
bitsongd query tendermint-validator-set | grep "$(bitsongd tendermint show-validator)"
```

You are looking for the `bech32` encoded `address` in the `~/.bitsongd/config/priv_validator.json` file.

{% hint style="info" %}
Note:

Only the top **64** validators in voting power are included in the active validator set.
{% endhint %}


# Relayer

This section contains instructions on how to setup the rust relayer "hermes" and relay IBC packets between bitsong-2b and other IBC-enabled networks.

## Relayer Tutorial

Hardware specs:

* 16+ vCPUs or Intel or AMD 16 core CPU
* at least 64GB RAM
* 4TB+ nVME drives

To assist operators in setting up relayers, Bitsong provides tutorials for the following IBC relayers:

### Hermes (rust)

[https://hermes.informal.systems/](https://hermes.informal.systems)

Pre-requisites:

* latest go-version <https://golang.org/doc/install>
* Fresh Rust installation: For instructions on how to install Rust on your machine please follow the official Notes about Rust installation at <https://www.rust-lang.org/tools/install>
* build-essential, git
* openssl for rust. The OpenSSL library with its headers is required. Refer to <https://docs.rs/openssl/0.10.38/openssl/>

*It is recommended to always build binaries on dedicated machine (dev-box), as dev dependencies (rust & go) shouldn't be on your production machine*

```
sudo apt install librust-openssl-dev build-essential git
```

#### Setup full nodes & configure seeds, peers and endpoints

To successfully relay IBC packets you need to run private full nodes (custom pruning or archive node) on all networks you want to support. Since relaying-success highly depends on latency and disk-IO-rate it is currently recommended to service these full/archive nodes on the same machine as the relayer process.

Because the relaying process needs to be able to query the chain back in height for at least 2/3 of the unstaking period ("trusting period") it is recommended to use pruning settings that will keep the full chain-state for a longer period of time than the unstaking period:

*edit app.toml - note: at an average block time of 6.5sec pruning-keep-recent=400000 will result in a retained chainstate of \~30d. This will suffice for most cosmos-sdk chains with an unstaking period < 30d*

```toml
pruning="custom"
pruning-keep-recent=400000 
pruning-keep-every=0 
pruning-interval=100
```

hermes needs to be able to query the RPC- and gRPC-endpoints of your nodes, you will need to maintain a well-organized port-setup.

*edit app.toml & config.toml, choose a unique port-config for each chain, write down your port-config*

*app.toml*

```toml
[grpc]

# Enable defines if the gRPC server should be enabled.
enable = true

# Address defines the gRPC server address to bind to.
address = "0.0.0.0:7012"
```

*config.toml - choose unique pprof\_laddr port*

```toml
# pprof listen address (https://golang.org/pkg/net/http/pprof)
pprof_laddr = "localhost:7019"
```

```toml
[rpc]

# TCP or UNIX socket address for the RPC server to listen on
laddr = "tcp://127.0.0.1:7013"
```

```toml
[p2p]

# Address to listen for incoming connections
laddr = "tcp://0.0.0.0:7010"
```

*config.toml - set persistent-peers & seeds for each chain*

bitsong-2b seeds:

```
 ffa27441ca78a5d41a36f6d505b67a145fd54d8a@95.217.156.228:26656,efd52c1e56b460b1f37d73c8d2bd5f860b41d2ba@65.21.62.83:26656
```

bitsong-2b persistent-peers:

```
a62038142844828483dbf16fa6dd159f6857c81b@173.212.247.98:26656,e9fea0509b1a2d16a10ef9fdea0a4e3edc7ca485@185.144.83.158:26656,8208adac8b09f3e2499dfaef24bb89a2d190a7a3@164.68.109.246:26656,cf031ac1cf44c9c311b5967712899391a434da9a@161.97.97.61:26656,d6b2ae82c38927fa7b7630346bd84772e632983a@157.90.95.104:15631,a5885669c1f7860bfe28071a7ec00cc45b2fcbc3@144.91.85.56:26656,325a5920a614e2375fea90f8a08d8b8d612fdd1e@137.74.18.30:26656,ae2787a337c3599b16410f3ac09d6918da2e5c37@46.101.238.149:26656,9336f75cd99ff6e5cdb6335e8d1a2c91b81d84b9@65.21.0.232:26656,9c6e52e78f112a55146b09110d1d1be47702df27@135.181.211.184:36656
```

osmosis-1 seeds:

```
83adaa38d1c15450056050fd4c9763fcc7e02e2c@ec2-44-234-84-104.us-west-2.compute.amazonaws.com:26656,23142ab5d94ad7fa3433a889dcd3c6bb6d5f247d@95.217.193.163:26656,f82d1a360dc92d4e74fdc2c8e32f4239e59aebdf@95.217.121.243:26656,e437756a853061cc6f1639c2ac997d9f7e84be67@144.76.183.180:26656,f515a8599b40f0e84dfad935ba414674ab11a668@osmosis.blockpane.com:26656
```

osmosis-1 persistent-peers:

```
147d0fe101bbd9e200ccbe3d353d5e7762cb02ee@207.154.201.8:26656, 9f77af7811da143f339402394ee71e42d5e2fe61@46.101.171.174:26656, d518832e4ded0484183fef3509d9f23ebb70b528@46.101.202.54:26656, 8f67a2fcdd7ade970b1983bf1697111d35dfdd6f@52.79.199.137:26656, 00c328a33578466c711874ec5ee7ada75951f99a@35.82.201.64:26656, cfb6f2d686014135d4a6034aa6645abd0020cac6@52.79.88.57:26656, 8d9967d5f865c68f6fe2630c0f725b0363554e77@134.255.252.173:26656, 785bc83577e3980545bac051de8f57a9fd82695f@194.233.164.146:26656, 778fdedf6effe996f039f22901a3360bc838b52e@161.97.187.189:36657, 64d36f3a186a113c02db0cf7c588c7c85d946b5b@209.97.132.170:26656, 4d9ac3510d9f5cfc975a28eb2a7b8da866f7bc47@37.187.38.191:26656, 2115945f074ddb038de5d835e287fa03e32f0628@95.217.43.85:26656
```

cosmoshub-4 seeds:

```
bf8328b66dceb4987e5cd94430af66045e59899f@public-seed.cosmos.vitwit.com:26656,cfd785a4224c7940e9a10f6c1ab24c343e923bec@164.68.107.188:26656,d72b3011ed46d783e369fdf8ae2055b99a1e5074@173.249.50.25:26656,ba3bacc714817218562f743178228f23678b2873@public-seed-node.cosmoshub.certus.one:26656,3c7cad4154967a294b3ba1cc752e40e8779640ad@84.201.128.115:26656
```

cosmoshub-4 persistent-peers:

```
ee27245d88c632a556cf72cc7f3587380c09b469@45.79.249.253:26656,538ebe0086f0f5e9ca922dae0462cc87e22f0a50@34.122.34.67:26656,d3209b9f88eec64f10555a11ecbf797bb0fa29f4@34.125.169.233:26656,bdc2c3d410ca7731411b7e46a252012323fbbf37@34.83.209.166:26656,585794737e6b318957088e645e17c0669f3b11fc@54.160.123.34:26656,11dfe200894f38e411beca77928e9dd118e66813@94.130.98.157:26656
```

*please reference* [*https://github.com/cosmos/chain-registry*](https://github.com/cosmos/chain-registry) *for a maintained list of peers & seeds.*

To simplify the config process you can use Environment-Variables in the systemd file: `sudo vim /etc/systemd/system/bitsongd.service`

```
[Unit]
Description=Bitsong Daemon

[Service]
User=relay
Environment=BITSONGD_P2P_LADDR=tcp://0.0.0.0:7010
Environment=BITSONGD_RPC_LADDR=tcp://0.0.0.0:7011
Environment=BITSONGD_GRPC_ADDRESS=127.0.0.1:7012
Environment=BITSONGD_PPROF_LADDR=localhost:7019
Environment=BITSONGD_P2P_PERSISTENT_PEERS="a62038142844828483dbf16fa6dd159f6857c81b@173.212.247.98:26656,e9fea0509b1a2d16a10ef9fdea0a4e3edc7ca485@185.144.83.158:26656,8208adac8b09f3e2499dfaef24bb89a2d190a7a3@164.68.109.246:26656,cf031ac1cf44c9c311b5967712899391a434da9a@161.97.97.61:26656,d6b2ae82c38927fa7b7630346bd84772e632983a@157.90.95.104:15631,a5885669c1f7860bfe28071a7ec00cc45b2fcbc3@144.91.85.56:26656,325a5920a614e2375fea90f8a08d8b8d612fdd1e@137.74.18.30:26656,ae2787a337c3599b16410f3ac09d6918da2e5c37@46.101.238.149:26656,9336f75cd99ff6e5cdb6335e8d1a2c91b81d84b9@65.21.0.232:26656,9c6e52e78f112a55146b09110d1d1be47702df27@135.181.211.184:36656"
Environment=BITSONGD_P2P_SEEDS="ffa27441ca78a5d41a36f6d505b67a145fd54d8a@95.217.156.228:26656,efd52c1e56b460b1f37d73c8d2bd5f860b41d2ba@65.21.62.83:26656"
Environment=BITSONGD_SNAPSHOT_INTERVAL=1000
Environment=BITSONGD_P2P_MAX_NUM_INBOUND_PEERS=100
Environment=BITSONGD_P2P_MAX_NUM_OUTBOUND_PEERS=100
LimitNOFILE=500000
ExecStart=/usr/local/bin/bitsongd start --pruning custom --pruning-keep-recent 400000 --pruning-keep-every=0 --pruning-interval 100 --home --x-crisis-skip-assert-invariants
Environment=BITSONGD_LOG_LEVEL=info

Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
```

#### Build & setup Hermes

*Beware that for security reasons this step should be done 'on some remote pc'*

Make the directory where you'll place the source, clone the hermes source repository and build it using the latest release. Optional: copy binary to /usr/bin (or preferred directory for systemd execution)

```
mkdir -p $HOME/hermes
git clone https://github.com/informalsystems/ibc-rs.git hermes
cd hermes
git checkout v0.13.0
cargo install ibc-relayer-cli --bin hermes --locked
sudo cp ~/.cargo/bin/hermes /usr/bin
```

*If you have built your binary on a remote machine, move the binary to your producion environment*

Make hermes config & keys directory, copy config-template to config directory:

```
mkdir -p $HOME/.hermes
mkdir -p $HOME/.hermes/keys
cp config.toml $HOME/.hermes
```

Check hermes version & config dir setup

```
hermes version
hermes 0.13.0
```

Edit hermes config (use ports according to your port config, set filter=true to filter channels you don't relay) `vim ~/.hermes/config.toml`

```toml
# The global section has parameters that apply globally to the relayer operation.
[global]

# Specify the strategy to be used by the relayer. Default: 'packets'
# Two options are currently supported:
#   - 'all': Relay packets and perform channel and connection handshakes.
#   - 'packets': Relay packets only.
strategy = 'packets'

# Enable or disable the filtering mechanism. Default: 'false'
# Valid options are 'true', 'false'.
# Currently Hermes supports two filters:
# 1. Packet filtering on a per-chain basis; see the chain-specific
#   filter specification below in [chains.packet_filter].
# 2. Filter for all activities based on client state trust threshold; this filter
#   is parametrized with (numerator = 1, denominator = 3), so that clients with
#   thresholds different than this will be ignored.
# If set to 'true', both of the above filters will be enabled.
#filter = true # breaking in v0.11.0 where filter = true by default

# Specify the verbosity for the relayer logging output. Default: 'info'
# Valid options are 'error', 'warn', 'info', 'debug', 'trace'.
log_level = 'info'

# Parametrize the periodic packet clearing feature.
# Interval (in number of blocks) at which pending packets
# should be eagerly cleared. A value of '0' will disable
# periodic packet clearing. Default: 100
clear_packets_interval = 25

# Toggle the transaction confirmation mechanism.
# The tx confirmation mechanism periodically queries the `/tx_search` RPC
# endpoint to check that previously-submitted transactions
# (to any chain in this config file) have delivered successfully.
# Experimental feature. Affects telemetry if set to false.
# Default: true.
tx_confirmation = true


# The REST section defines parameters for Hermes' built-in RESTful API.
# https://hermes.informal.systems/rest.html
[rest]

# Whether or not to enable the REST service. Default: false
enabled = true

# Specify the IPv4/6 host over which the built-in HTTP server will serve the RESTful
# API requests. Default: 127.0.0.1
host = '127.0.0.1'

# Specify the port over which the built-in HTTP server will serve the restful API
# requests. Default: 3000
port = 3000


# The telemetry section defines parameters for Hermes' built-in telemetry capabilities.
# https://hermes.informal.systems/telemetry.html
[telemetry]

# Whether or not to enable the telemetry service. Default: false
enabled = true

# Specify the IPv4/6 host over which the built-in HTTP server will serve the metrics
# gathered by the telemetry service. Default: 127.0.0.1
host = '127.0.0.1'

# Specify the port over which the built-in HTTP server will serve the metrics gathered
# by the telemetry service. Default: 3001
port = 3001

[[chains]]
id = 'osmosis-1'
rpc_addr = 'http://localhost:7001'
grpc_addr = 'http://localhost:7002'
websocket_addr = 'ws://localhost:7001/websocket'
rpc_timeout = '10s'
account_prefix = 'osmo'
key_name = 'osmosis'
address_type = { derivation = 'osmosis' }
store_prefix = 'ibc'
default_gas = 5000000
max_gas = 15000000
gas_price = { price = 0.000, denom = 'uosmo' }
gas_adjustment = 0.1
max_msg_num = 20
max_tx_size = 2097152
clock_drift = '20s'
max_block_time = '10s'
trusting_period = '10days'
memo_prefix = ''
trust_threshold = { numerator = '1', denominator = '3' }
[chains.packet_filter]
policy = 'allow'
list = [
  ['transfer', 'channel-73']
]

[[chains]]
id = 'bitsong-2b'
rpc_addr = 'http://127.0.0.1:7011'
grpc_addr = 'http://127.0.0.1:7012'
websocket_addr = 'ws://127.0.0.1:7011/websocket'
rpc_timeout = '10s'
account_prefix = 'bitsong'
key_name = 'bitsong'
address_type = { derivation = 'bitsong' }
store_prefix = 'ibc'
default_gas = 2000000
max_gas = 4000000
gas_price = { price = 0.026, denom = 'ubtsg' }
gas_adjustment = 0.1
max_msg_num = 25
max_tx_size = 1800000
clock_drift = '10s'
max_block_time = '10s'
trusting_period = '14d'
memo_prefix = ''
trust_threshold = { numerator = '1', denominator = '3' }
[chains.packet_filter]
policy = 'allow'
list = [
 ['transfer', 'channel-0'],
 ['transfer', 'channel-1']
 ]

[[chains]]
id = 'cosmoshub-4'
rpc_addr = 'http://127.0.0.1:7021'
grpc_addr = 'http://127.0.0.1:7022'
websocket_addr = 'ws://127.0.0.1:7021/websocket'
rpc_timeout = '10s'
account_prefix = 'cosmos'
key_name = 'cosmos'
address_type = { derivation = 'cosmos' }
store_prefix = 'ibc'
default_gas = 2000000
max_gas = 3000000
gas_price = { price = 0.001, denom = 'uatom' }
gas_adjustment = 0.1
max_msg_num = 25
max_tx_size = 180000
clock_drift = '10s'
max_block_time = '10s'
trusting_period = '14days'
memo_prefix = ''
trust_threshold = { numerator = '1', denominator = '3' }
[chains.packet_filter]
policy = 'allow'
list = [
   ['transfer', 'channel-229']
 ]
```

Add your relaying-wallets to hermes' keyring (located in $HOME/.hermes/keys)

Best practice is to use the same mnemonic over all networks, do not use your relaying-addresses for anything else because it might lead to mismatched account sequence errors.

```
hermes keys restore bitsong-2b -m "24-word mnemonic seed" --hd-path m/44'/639'/0'/0/0 
hermes keys restore osmosis-1 -m "24-word mnemonic seed"
hermes keys restore cosmoshub-4 -m "24-word mnemonic seed"
```

You can validate your hermes configuration file:

```
hermes config validate
INFO ThreadId(01) using default configuration from '/home/relay/.hermes/config.toml'
Success: "validation passed successfully"
```

Create hermes service file:

```
[Unit]
Description=hermes

[Service]
User=relay
ExecStart=/usr/bin/hermes start
LimitNOFILE=500000

Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
```

Refresh service files, enable hermes on system-startup, enable all node-daemons on system-startup, start node-daemons, sync, start hermes.

*Tipp: use chainlayer quicksync to bootstrap your nodes faster:* [*https://quicksync.io/networks/osmosis.html*](https://quicksync.io/networks/osmosis.html)

```
sudo systemctl daemon-reload
sudo systemctl enable hermes.service bitsongd.service osmosisd.service gaiad.service
sudo systemctl start bitsongd osmosisd gaiad
```

Watch node-daemon output to check if your nodes are syncing:

```
journaltctl -u bitsongd -f
```

When your nodes are fully synced you can start the hermes daemon:

```
sudo systemctl start hermes && journalctl -u hermes -f
```

Hermes does a chain-health-check at startup. Watch the output to check if all connected nodes are up and synced

```
INFO ThreadId(01) using default configuration from '/home/relay/.hermes/config.toml'
INFO ThreadId(01) telemetry service running, exposing metrics at http://0.0.0.0:3001/metrics
INFO ThreadId(01) starting REST API server listening at http://127.0.0.1:3000
INFO ThreadId(01) [osmosis-1] chain is healthy
INFO ThreadId(01) [cosmoshub-4] chain is healthy
INFO ThreadId(01) [bitsong-2b] chain is healthy
...
INFO ThreadId(01) Hermes has started
```

Hermes will try & clear any unreceived packets after startup has completed.

#### Snippets

Query Hermes for unreceived packets & acknowledgements (check if channels are "clear")

```
hermes query packet unreceived-packets bitsong-2b transfer channel-0
hermes query packet unreceived-acks bitsong-2b transfer channel-0
```

```
hermes query packet unreceived-packets osmosis-1 transfer channel-73
hermes query packet unreceived-acks bitsong-1 transfer channel-73
```

Query Hermes for packet commitments:

```
hermes query packet commitments osmosis-1 transfer channel-73
hermes query packet commitments bitsong-2b transfer channel-0
```

Clear channel (only works on hermes `v0.12.0` and higher)

```
hermes clear packets omniflixhub-1 transfer channel-1
hermes clear packets osmosis-1 transfer channel-199
```

Clear unreceived packets manually. *Experimental: you'll need to stop your hermes daemon for it not to get confused with account sequences.*

```
hermes tx raw packet-recv osmosis-1 bitsong-2b transfer channel-0
hermes tx raw packet-recv bitsong-2b osmosis-1 transfer channel-73
```

**Thanks to** [**@ccclaimens**](https://twitter.com/ccclaimens) **from** [**@crypto\_crew**](https://twitter.com/crypto_crew)\*\*\*\*


# CLI Guide

{% hint style="warning" %}
We are moving our **documentation** to the new "[**BitSong, the blockchain for music**](https://bitsong.io/en)" website. To access the most up-to-date and complete version of our guides and articles, please visit our new [**bitsong documentation**](https://bitsong.io/en/docs) website. This old documentation site will no longer be maintained or updated, so we **strongly recommend** referring to the new [**bitsong documentation**](https://bitsong.io/en/docs) website for the latest information. If you can't find what you're looking for on the new site, please be patient as we are still in the process of migrating all of our content. Thank you for your understanding!\
\
Visit the new article <https://bitsong.io/en/docs/blockchain/cli-guide>
{% endhint %}

This section describes the commands available from `bitsongd`, the command line interface that connects a running `bitsongd` process.

### `add-genesis-account` <a href="#add-genesis-account" id="add-genesis-account"></a>

Adds a genesis account to `genesis.json`.

#### Syntax

```
bitsongd add-genesis-account <address-or-key-name> '<amount><coin-denominator>,<amount><coin-denominator>'
```

#### Example

```
bitsongd add-genesis-account acc1 '200000000ubtsg'
```

### `collect-gentxs` <a href="#add-genesis-account" id="add-genesis-account"></a>

Collects genesis transactions and outputs them to `genesis.json`.

#### Syntax

```
bitsongd collect-gentxs
```

Coming soon....


# Gas and Fees

{% hint style="warning" %}
We are moving our **documentation** to the new "[**BitSong, the blockchain for music**](https://bitsong.io/en)" website. To access the most up-to-date and complete version of our guides and articles, please visit our new [**bitsong documentation**](https://bitsong.io/en/docs) website. This old documentation site will no longer be maintained or updated, so we **strongly recommend** referring to the new [**bitsong documentation**](https://bitsong.io/en/docs) website for the latest information. If you can't find what you're looking for on the new site, please be patient as we are still in the process of migrating all of our content. Thank you for your understanding!\
\
Visit the new article <https://bitsong.io/en/docs/blockchain/gas-and-fees>
{% endhint %}

On BitSong mainnet, the accepted denom is `ubtsg`, where `1btsg = 1.000.000ubtsg`

Transactions on the BitSong network need to include a transaction fee in order to be processed. This fee pays for the gas required to run the transaction. The formula is the following:

$$
fees = ceil(gas \* gasPrices)
$$

The `gas` is dependent on the transaction. Different transaction require different amount of `gas`. The `gas` amount for a transaction is calculated as it is being processed, but there is a way to estimate it beforehand by using the `auto` value for the `gas` flag. Of course, this only gives an estimate. You can adjust this estimate with the flag `--gas-adjustment` (default `1.0`) if you want to be sure you provide enough `gas` for the transaction.

The `gasPrice` is the price of each unit of `gas`. Each validator sets a `min-gas-price` value, and will only include transactions that have a `gasPrice` greater than their `min-gas-price`.

The transaction `fees` are the product of `gas` and `gasPrice`. As a user, you have to input 2 out of 3. The higher the `gasPrice`/`fees`, the higher the chance that your transaction will get included in a block.

For mainnet, the recommended `gas-prices` is `0.0025ubtsg`.

### Set `minimum-gas-prices` <a href="#set-minimum-gas-prices" id="set-minimum-gas-prices"></a>

Your full-node keeps unconfirmed transactions in its mempool. In order to protect it from spam, it is better to set a `minimum-gas-prices` that the transaction must meet in order to be accepted in your node's mempool. This parameter can be set in the following file `~/.bitsongd/config/app.toml`.

The initial recommended `min-gas-prices` is `0.0025ubtsg`, but you might want to change it later.

```
# This is a TOML config file.
# For more information, see https://github.com/toml-lang/toml

###############################################################################
###                           Base Configuration                            ###
###############################################################################

# The minimum gas prices a validator is willing to accept for processing a
# transaction. A transaction's fees must meet the minimum of any denomination
# specified in this config (e.g. 0.25token1;0.0001token2).

minimum-gas-prices = "0.0025ubtsg"
```


# Pruning of State

{% hint style="warning" %}
We are moving our **documentation** to the new "[**BitSong, the blockchain for music**](https://bitsong.io/en)" website. To access the most up-to-date and complete version of our guides and articles, please visit our new [**bitsong documentation**](https://bitsong.io/en/docs) website. This old documentation site will no longer be maintained or updated, so we **strongly recommend** referring to the new [**bitsong documentation**](https://bitsong.io/en/docs) website for the latest information. If you can't find what you're looking for on the new site, please be patient as we are still in the process of migrating all of our content. Thank you for your understanding!\
\
Visit the new article <https://bitsong.io/en/docs/blockchain/pruning-of-state>
{% endhint %}

There are four strategies for pruning state. These strategies apply only to state and do not apply to block storage. To set pruning, adjust the `pruning` parameter in the `~/.bitsongd/config/app.toml` file. The following pruning state settings are available:

1. `everything`: Prune all saved states other than the current state.
2. `nothing`: Save all states and delete nothing.
3. `default`: Save the last 100 states and the state of every 10,000th block.
4. `custom`: Specify pruning settings with the `pruning-keep-recent`, `pruning-keep-every`, and `pruning-interval` parameters.

By default, every node is in `default` mode which is the recommended setting for most environments. If you would like to change your nodes pruning strategy then you must do so when the node is initialized. Passing a flag when starting `bitsongd` will always override settings in the `app.toml` file, if you would like to change your node to the `everything` mode then you can pass the `---pruning everything` flag when you call `bitsongd start`.

> Note: When you are pruning state you will not be able to query the heights that are not in your store.


# Export the state

{% hint style="warning" %}
We are moving our **documentation** to the new "[**BitSong, the blockchain for music**](https://bitsong.io/en)" website. To access the most up-to-date and complete version of our guides and articles, please visit our new [**bitsong documentation**](https://bitsong.io/en/docs) website. This old documentation site will no longer be maintained or updated, so we **strongly recommend** referring to the new [**bitsong documentation**](https://bitsong.io/en/docs) website for the latest information. If you can't find what you're looking for on the new site, please be patient as we are still in the process of migrating all of our content. Thank you for your understanding!\
\
Visit the new article <https://bitsong.io/en/docs/blockchain/export-the-state>
{% endhint %}

go-bitsong can dump the entire application state into a JSON file. This application state dump is useful for manual analysis and can also be used as the genesis file of a new network.

Export state with:

```
bitsongd export 2> [filename].json
```

You can also export state from a particular height (at the end of processing the block of that height):

```
bitsongd export --height [height] 2> [filename].json
```

If you plan to start a new network from the exported state, export with the `--for-zero-height` flag:

```
bitsongd export --height [height] --for-zero-height 2> [filename].json
```


# Verify Mainnet

{% hint style="warning" %}
We are moving our **documentation** to the new "[**BitSong, the blockchain for music**](https://bitsong.io/en)" website. To access the most up-to-date and complete version of our guides and articles, please visit our new [**bitsong documentation**](https://bitsong.io/en/docs) website. This old documentation site will no longer be maintained or updated, so we **strongly recommend** referring to the new [**bitsong documentation**](https://bitsong.io/en/docs) website for the latest information. If you can't find what you're looking for on the new site, please be patient as we are still in the process of migrating all of our content. Thank you for your understanding!\
\
Visit the new article <https://bitsong.io/en/docs/blockchain/verify-mainnet>
{% endhint %}

Help to prevent a catastrophe by running invariants on each block on your full node. In essence, by running invariants you ensure that the state of mainnet is the correct expected state. One vital invariant check is that no atoms are being created or destroyed outside of expected protocol, however there are many other invariant checks each unique to their respective module. Because invariant checks are computationally expensive, they are not enabled by default. To run a node with these checks start your node with the assert-invariants-blockly flag:

```
bitsongd start --assert-invariants-blockly
```

If an invariant is broken on your node, your node will panic and prompt you to send a transaction which will halt mainnet. For example the provided message may look like:

```
invariant broken:
    loose token invariance:
        pool.NotBondedTokens: 100
        sum of account tokens: 101
    CRITICAL please submit the following transaction:
        bitsongd tx crisis invariant-broken staking supply

```

When submitting a invariant-broken transaction, transaction fee tokens are not deducted as the blockchain will halt (invariant-broken transactions are free transactions).


# Upgrades


# From v0.8.0 to v0.10.0

This guide is exclusively for Validators and Node Operators, please pay **Maximum attention** and **Perform a backup before upgrading**!

### Stop of the node

The node will automatically stop at block height `4566000` approximately at `2022-02-08 13:12:07 UTC`. The log file will indicate that in order to continue, you must replace the `bitsongd` binary. At that point you can finish the `bitsongd` process.

```
sudo systemctl stop bitsongd
sudo systemctl disable bitsongd
```

### Backup

In the event that the update is unsuccessful, you will need to restore the previous status and install a future patch (example 0.8.1).

In order to perform the backup, you just need to copy the content present on the home directory of `go-bitsong`, in this case `~/.bitsongd`

**`Remember to have at least 50% free disk space`**

```
cp -Rv ~/.bitsongd ~/backup_bitsongd_080
```

> This operation should take 5/10 minutes, however, in the event that you're using low performance servers, the process might take up to 30/40 minutes.

### Install `golang 1.17.x`

The upgrade to `0.10.0` requires a version of `golang-1.17.x`

```
wget -q -O - https://git.io/vQhTU | bash -s -- --version 1.17.6
```

### Replace `bitsongd`

First of all we need to make sure we're using the `0.8.0` version

```
bitsongd version
# 0.8.0
```

We should get the `0.8.0` version

At this point we have to download and compile the new binary `bitsongd 0.10.0`

```
cd ~
rm -rf go-bitsong # (only in the event that a previous directory is already present)
git clone https://github.com/bitsongofficial/go-bitsong.git
cd go-bitsong
git checkout v0.10.0
make install
```

The `make install` command will compile and install the new binary.

Let's check if the binary was properly updated

```
bitsongd version
# 0.10.0
```

If we get the answer `0.10.0` the process was successffully executed and we can proceed to restart the node.

### Start `bitsongd`

```
sudo systemctl enable bitsongd
sudo systemctl start bitsongd
```

At this point the node will start performing the update of all the existing modules. Keep into consideration that the operation might take up to 30 minutes.

To view the logs:

```
sudo journalctl -u bitsongd -f
```


# From v0.10.0 to v0.11.0

This guide is exclusively for Validators and Node Operators, please pay **Maximum attention** and **Perform a backup before upgrading**!

### Stop of the node

The node will automatically stop at block height `6777500` approximately at `2022-07-11 14:00:00 UTC`. The log file will indicate that in order to continue, you must replace the `bitsongd` binary. At that point you can finish the `bitsongd` process.

```
sudo systemctl stop bitsongd
sudo systemctl disable bitsongd
```

### Backup

In the event that the update is unsuccessful, you will need to restore the previous status and install a future patch (example `v0.11.1`).

In order to perform the backup, you just need to copy the content present on the home directory of `go-bitsong`, in this case `~/.bitsongd`

**`Remember to have at least 50% free disk space`**

```
cp -Rv ~/.bitsongd ~/backup_bitsongd_0100
```

> This operation should take 5/10 minutes, however, in the event that you're using low performance servers, the process might take up to 30/40 minutes.

### Remove `golang 1.17.x`

The upgrade to `v0.11.0` requires a version of `golang-1.18.x`

```
wget -q -O - https://git.io/vQhTU | bash -s -- --remove
```

### Install `golang 1.18.x`

```
wget -q -O - https://git.io/vQhTU | bash -s -- --version 1.18.3
```

### Replace `bitsongd`

First of all we need to make sure we're using the `v0.10.0` version

```
bitsongd version
# 0.10.0
```

We should get the `0.10.0` version

At this point we have to download and compile the new binary `bitsongd 0.11.0`

```
cd ~
rm -rf go-bitsong # (only in the event that a previous directory is already present)
git clone https://github.com/bitsongofficial/go-bitsong.git
cd go-bitsong
git checkout v0.11.0
make install
```

The `make install` command will compile and install the new binary.

Let's check if the binary was properly updated

```
bitsongd version
# 0.11.0
```

If we get the answer `0.11.0` the process was successffully executed and we can proceed to restart the node.

### Start `bitsongd`

```
sudo systemctl enable bitsongd
sudo systemctl start bitsongd
```

At this point the node will start performing the update of all the existing modules. Keep into consideration that the operation might take up to 10 minutes.

To view the logs:

```
sudo journalctl -u bitsongd -f
```


# From v0.12.x to v0.13.0

This guide is exclusively for Validators and Node Operators, please pay **Maximum attention** and **Perform a backup before upgrading**!

### Stop of the node

The node will automatically stop at block height `9845000` approximately at `2023-02-03 15:45:00 UTC`. The log file will indicate that in order to continue, you must replace the `bitsongd` binary. At that point you can finish the `bitsongd` process.

```
sudo systemctl stop bitsongd
sudo systemctl disable bitsongd
```

### Backup

In the event that the update is unsuccessful, you will need to restore the previous status and install a future patch (example `v0.13.1`).

In order to perform the backup, you just need to copy the content present on the home directory of `go-bitsong`, in this case `~/.bitsongd`

**`Remember to have at least 50% free disk space`**

```
cp -Rv ~/.bitsongd ~/backup_bitsongd_0100
```

> This operation should take 5/10 minutes, however, in the event that you're using low performance servers, the process might take up to 30/40 minutes.

### Remove `golang 1.18.x`

The upgrade to `v0.13.0` requires a version of `golang-1.19.x`

```
wget -q -O - https://git.io/vQhTU | bash -s -- --remove
```

### Install `golang 1.19.x`

```
wget -q -O - https://git.io/vQhTU | bash -s -- --version 1.19.5
```

### Replace `bitsongd`

First of all we need to make sure we're using the `v0.10.0` version

```
bitsongd version
# 0.12.x
```

We should get the `0.12.x` version

At this point we have to download and compile the new binary `bitsongd 0.13.0`

```
cd ~
rm -rf go-bitsong # (only in the event that a previous directory is already present)
git clone https://github.com/bitsongofficial/go-bitsong.git
cd go-bitsong
git checkout v0.13.0
make install
```

The `make install` command will compile and install the new binary.

Let's check if the binary was properly updated

```
bitsongd version
# 0.13.0
```

If we get the answer `0.13.0` the process was successffully executed and we can proceed to restart the node.

### Start `bitsongd`

```
sudo systemctl enable bitsongd
sudo systemctl start bitsongd
```

At this point the node will start performing the update of all the existing modules. Keep into consideration that the operation might take up to 10 minutes.

To view the logs:

```
sudo journalctl -u bitsongd -f
```


# From v0.13.x to v0.14.0

This guide is exclusively for Validators and Node Operators, please pay **Maximum attention** and **Perform a backup before upgrading**!

### Stop of the node

The node will automatically stop at block height `10055000` approximately at `2023-02-17 16:57:00 UTC`. The log file will indicate that in order to continue, you must replace the `bitsongd` binary. At that point you can finish the `bitsongd` process.

```
sudo systemctl stop bitsongd
sudo systemctl disable bitsongd
```

### Backup

In the event that the update is unsuccessful, you will need to restore the previous status and install a future patch (example `v0.14.0`).

In order to perform the backup, you just need to copy the content present on the home directory of `go-bitsong`, in this case `~/.bitsongd`

**`Remember to have at least 50% free disk space`**

```
cp -Rv ~/.bitsongd ~/backup_bitsongd_0100
```

> This operation should take 5/10 minutes, however, in the event that you're using low performance servers, the process might take up to 30/40 minutes.

### Remove `golang 1.18.x`

The upgrade to `v0.13.0` requires a version of `golang-1.19.x`

```
wget -q -O - https://git.io/vQhTU | bash -s -- --remove
```

### Install `golang 1.19.x`

```
wget -q -O - https://git.io/vQhTU | bash -s -- --version 1.19.5
```

### Replace `bitsongd`

First of all we need to make sure we're using the `v0.13.1` version

```
bitsongd version
# 0.13.x
```

We should get the `0.13.x` version

At this point we have to download and compile the new binary `bitsongd 0.14.0`

```
cd ~
rm -rf go-bitsong # (only in the event that a previous directory is already present)
git clone https://github.com/bitsongofficial/go-bitsong.git
cd go-bitsong
git checkout v0.14.0
make install
```

The `make install` command will compile and install the new binary.

Let's check if the binary was properly updated

```
bitsongd version
# 0.14.0
```

If we get the answer `0.14.0` the process was successffully executed and we can proceed to restart the node.

### Start `bitsongd`

```
sudo systemctl enable bitsongd
sudo systemctl start bitsongd
```

At this point the node will start performing the update of all the existing modules. Keep into consideration that the operation might take up to 10 minutes.

To view the logs:

```
sudo journalctl -u bitsongd -f
```


# From v0.14.x to v0.15.0

This guide is exclusively for Validators and Node Operators, please pay **Maximum attention** and **Perform a backup before upgrading**!

### Stop of the node

The node will automatically stop at block height `15947000` approximately at `2024-03-15 15:30:00 UTC`. The log file will indicate that in order to continue, you must replace the `bitsongd` binary. At that point you can finish the `bitsongd` process.

```
sudo systemctl stop bitsongd
sudo systemctl disable bitsongd
```

### Backup

In the event that the update is unsuccessful, you will need to restore the previous status and install a future patch (example `v0.15.x`).

In order to perform the backup, you just need to copy the content present on the home directory of `go-bitsong`, in this case `~/.bitsongd`

**`Remember to have at least 50% free disk space`**

```
cp -Rv ~/.bitsongd ~/backup_bitsongd_0140
```

> This operation should take 5/10 minutes, however, in the event that you're using low performance servers, the process might take up to 30/40 minutes.

### Install `golang 1.19.x`

```
wget -q -O - https://git.io/vQhTU | bash -s -- --version 1.19.5
```

### Replace `bitsongd`

First of all we need to make sure we're using the `v0.14.x` version

```
bitsongd version
# 0.14.x
```

We should get the `0.1x.x` version

At this point we have to download and compile the new binary `bitsongd 0.15.0`

```
cd ~
rm -rf go-bitsong # (only in the event that a previous directory is already present)
git clone https://github.com/bitsongofficial/go-bitsong.git
cd go-bitsong
git checkout v0.15.0
make install
```

The `make install` command will compile and install the new binary.

Let's check if the binary was properly updated

```
bitsongd version
# 0.15.0
```

If we get the answer `0.15.0` the process was successffully executed and we can proceed to restart the node.

### Start `bitsongd`

```
sudo systemctl enable bitsongd
sudo systemctl start bitsongd
```

At this point the node will start performing the update of all the existing modules. Keep into consideration that the operation might take up to 10 minutes.

To view the logs:

```
sudo journalctl -u bitsongd -f
```


# From v0.17.0 to v0.18.0

This guide is exclusively for Validators and Node Operators, please pay **Maximum attention** and **Perform a backup before upgrading**!

### Ensure Minimum Gas Config is set

```sh
export DAEMON_HOME=$HOME/.bitsongd
sed 's/^minimum-gas-prices = .*/minimum-gas-prices = "0.01ubtsg"/' $DAEMON_HOME/config/app.toml > temp_file && mv temp_file $DAEMON_HOME/config/app.toml
```

### Stop of the node

The node will automatically stop at block height `19818776` approximately at `2024-11-29 16:52:00 UTC`. The log file will indicate that in order to continue, you must replace the `bitsongd` binary. At that point you can finish the `bitsongd` process.

```
sudo systemctl stop bitsongd
sudo systemctl disable bitsongd
```

### Backup

In the event that the update is unsuccessful, you will need to restore the previous status and install a future patch (example `v0.18.x`).

In order to perform the backup, you just need to copy the content present on the home directory of `go-bitsong`, in this case `~/.bitsongd`

**`Remember to have at least 50% free disk space`**

```
cp -Rv ~/.bitsongd ~/backup_bitsongd_0180
```

> This operation should take 5/10 minutes, however, in the event that you're using low performance servers, the process might take up to 30/40 minutes.

### Verify that you are currently running the correct version (v0.17.0) of `bitsongd`:

```sh
bitsongd version --long
# name: go-bitsong
# server_name: bitsongd
# client_name: bitsongcli
# version: 0.17.0
# commit: 6caaf5fdba8e7ce41e8a9d44654c141f85c9c38f
# build_tags: netgo,ledger
```

### Make sure your chain halts at the right block: `19818776`

```sh
perl -i -pe 's/^halt-height =.*/halt-height = 19818776/' ~/.bitsongd/config/app.toml
```

then restart your node `systemctl restart bitsongd`

### After the chain has halted, make a backup of your `.bitsongd` directory

```sh
cp -Rf ~/.bitsongd ./bitsongd_backup
```

**NOTE**: It is recommended for validators and operators to take a full data snapshot at the export height before proceeding in case the upgrade does not go as planned or if not enough voting power comes online in a sufficient and agreed upon amount of time. In such a case, the chain will fallback to continue operating `bitsong-1`.

### Update Go

```sh
wget -q -O - https://git.io/vQhTU | bash -s -- --remove
wget -q -O - https://git.io/vQhTU | bash -s -- --version 1.22.9
```

#### Option A: Install Go-Bitsong binary

```sh
cd go-bitsong && git pull && git checkout v0.18.0
make build && make install 
```

### Verify you are currently running the correct version (v0.18.0) of the `go-bitsong`:

```sh
bitsongd version --long | grep "cosmos_sdk_veresion/|commit\|version:"
# commit: 50b4082736a68cdde098cf36edd7c7a70d9fdae6
# cosmos_sdk_version: v0.47.8
# version: 0.18.0
```

#### Option B: Downloading Verified Build:

```sh
# set target platform
export PLATFORM_TARGET=amd64
 # delete if exists
rm -rf bitsongd_linux_$PLATFORM_TARGET.tar.gz
# download 
curl -L -o ~/bitsongd-linux-$PLATFORM_TARGET.tar.gz https://github.com/bitsongofficial/go-bitsong/releases/download/v0.18.0/bitsongd-linux-$PLATFORM_TARGET.tar.gz
# verify sha256sum 
sha256sum bitsongd-linux-$PLATFORM_TARGET.tar.gz
# Output: d3d0da91a01c473351dc57b2ed357aa8ea378a51672eec87112501bc9a53add6  bitsongd-linux-amd64.tar.gz
# Output: 1696cf491224603136c32bf747610c0863754f73502523347524d9f1ef5b687f  bitsongd-linux-arm64.tar.gz

# decompress 
tar -xvzf bitsongd-linux-$PLATFORM_TARGET.tar.gz 

## move binary to go bin path
sudo mv build/bitsongd-linux-$PLATFORM_TARGET /usr/local/go/bitsongd

## change file ownership, if nessesary 
sudo chmod +x /usr/local/go/bitsongd

## confirm binary executable works 
bitsongd version --long 

# build_tags: netgo,ledger
# commit: 50b4082736a68cdde098cf36edd7c7a70d9fdae6
# cosmos_sdk_version: v0.47.8
# go: go version go1.23.3 darwin/$PLATFORM_TARGET
# name: go-bitsong
# server_name: bitsongd
# version: 0.18.0
```


# Application Testing

Review existing test coverage options, and learn how to write new tests with open-source tooling used for Bitsong.

<table><thead><tr><th>Library </th><th width="338">Description </th><th>Type</th><th>Example</th></tr></thead><tbody><tr><td><a href="https://github.com/bitsongofficial/go-bitsong/blob/main/app/testing/test_suite.go#L15">Bitsong Test Suite</a></td><td>Targets specific keepers functions in Go</td><td>Go Test</td><td>Link</td></tr><tr><td><a href="https://interchaintest-docs.vercel.app/">InterchainTest (ICT)</a></td><td>Multi-node &#x26; multi-network tests. Used for CI tests.</td><td>Docker</td><td><a href="https://github.com/bitsongofficial/go-bitsong/blob/main/e2e/basic_start_test.go">Link</a></td></tr><tr><td>LocalBitsong</td><td>Deploy a local instance of Bitsong</td><td>Docker</td><td>Link</td></tr><tr><td><a href="https://orchestrator.abstract.money/quick_start.html">Cw-Orchestrator</a></td><td>Multi-chain scripting library</td><td>Rust / Kubernetes</td><td>Link</td></tr></tbody></table>


# Fan Tokens

## What are Fan Tokens?

Fan tokens are a brand new phenomenon already making waves in the sports sector. A fan token is a cryptocurrency issued for the benefit of star performers — whether that’s a world-famous rock band, or an up-and-coming solo talent — and their fans.

Why does the music industry need fan tokens? Because they allow any act or artist to create their own economy, generating new ways to monetise their music and brand, and providing a unique and innovative channel to engage with fans.

BitSong’s Fan Token module allows artists to mint their own branded tokens for any purpose. But here are a few ways that they can be used:

Create a loyalty program allowing fan token holders privileged access to exclusive content such as unreleased materials or behind-the-scenes interviews&#x20;

Crowdfund a tour or studio album and revenue-sharing with token holders&#x20;

Give fans the opportunity to vote, for example, on the song lineup for a gig or on the cities for an upcoming tour&#x20;

Accept fan tokens as payment for NFTs

The BitSong Fan Token module enables any artist to start minting their own fan tokens and list them within a few minutes, for low fees. BitSong also stands apart from other fan token platforms by offering the opportunity to link BitSong Fan Tokens to social profiles, such as Twitter.

### Abstract

This document specifies the *fantoken* module of the BitSong chain.

The *fantoken* module enables the BitSong chain to support fan tokens, allowing actors in the content creation industry to create their economy. In this sense, they can generate new ways to monetize their music and brand and provide a unique and innovative channel to engage with fans. Thanks to this module, players from the content creation universe can start minting their *fan tokens* (which are **fungible tokens**) and listing them within a few minutes for low fees.

#### An example: Fan tokens in the music Industry

In the music industry, for example, *fan tokens* enable to empower a lot of different scenarios. For instance, it is possible to use them to crowdfund a tour or an album, or even to access exclusive content. The potential of such a system is very massive and, with these few examples, you can imagine what a contribution this tool can make to a world teeming with content creators.

#### Fan tokens in BitSong

Based on the concept of the **ERC-20 Standard**, BitSong *fan tokens* enable the user to a new way of **value exchanging**. Here, through tokens issued by a particular entity, the fans can deeply interact with their influencers or idols.

We can identify each *fan token* through its `denom`. Moreover, even if its `denom` allow the global identification of the token, each *fan token* is also equipped with a `name` and a `symbol`, which helps in its recognition. The `name` and the `symbol` of a *fan token*, together with a `uri` and an `authority` (i.e., the address of the wallet which is able to manage those data) are part of the `metadata` of the *fan token*.

More specifically:

* **denom** is calculated by the tendermint crypto hash function through the *block height* of the transaction, the first *minter*, the *symbol*, and the *name*. For this reason, it is *unique*;
* **symbol** is defined by the user and can be any string matching the pattern `^[a-z0-9]{1,64}$`, so any lowercase string containing letters and digits with a length between 1 and 64 characters. *It cannot be empty*;
* **name**, on the other hand, is also defined by the user but it can be any string containing max 128 characters. *It can also be empty*.

Finally, thanks to the *fantoken* module, users on BitSong can:

* manage *fan tokens*, issuing, minting, burning, and transferring them;
* build applications that use the *fan tokens* API to create completely new and custom artists' economies.

Features that may be added in the future are described in Future Improvements.

### Concepts

#### Conventions

By looking at numbers, we separate the decimals by point and the thousands by comma. For instance, the number *one thousand two hundred thirty-four and fifty-six hundredths*, is written as:

![formula](https://render.githubusercontent.com/render/math?math=%5Ccolor%7Bgray%7D1,234.56)

#### Fan token

Fan tokens, conceptually based on the [ERC-20 Standard](https://ethereum.org/it/developers/docs/standards/tokens/erc-20), are **fungible tokens** issued for fan communities. They borns to create new connections between fans and any content creator, like star performers, actors, designers, musicians, photographers, writers, models, influencers, etc. They enable the growth of a private and (most importantly) custom economy creating new channels for fans' engagement. *Fan tokens* have enormous potential. By using them, you can build myriad applications allowing fans a deeper interaction in the artistic life of their top performers.

To provide you with some examples, you can think that it is possible to use them for creating loyalty programs to provide privileged access to exclusive content. To allow your fan to crowdfund a tour or studio album and share part of the revenue with your fans. To enable your fans with the opportunity to vote on the cities for an upcoming tour. Or even to accept *fan tokens* as payment for NFTs.

In the design of the *fan token* functionalities, big part of the reasonings were based on the [OpenZeppelin standard](https://docs.openzeppelin.com/contracts/4.x/api/token/erc20). For example, the concept of *burning* the tokens lowering the `totalSupply` directly derives from the standard [documentation](https://docs.openzeppelin.com/contracts/4.x/api/token/erc20#ERC20-_burn-address-uint256-).

A **fan token** is characterized by:

| Attribute   | Type             | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| ----------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| denom       | `string`         | It is an hash calculated on the first `Minter`, the `Symbol`, the `Name` and the `Block Height` of the issuing transaction of the *fan token*. It is the hash identifying the *fan token* and is used to prevent the creation of identical tokens. Moreover, to fastly identify a *fan token* from its `denom`, it starts with the prefix `ft`.                                                                                                                                                                                                     |
| max\_supply | `sdk.Int`        | It is chosen once by the user. It is the maximum supply value of mintable tokens from its definition. It is expressed in micro unit (![formula](https://render.githubusercontent.com/render/math?math=%5Ccolor%7Bgray%7D%5Cmu=10%5E%7B-6%7D)). For this reason, to indicate a maximum supply of ![formula](https://render.githubusercontent.com/render/math?math=%5Ccolor%7Bgray%7D456) tokens, this value must be equal to ![formula](https://render.githubusercontent.com/render/math?math=%5Ccolor%7Bgray%7D456%5Ccdot10%5E%7B6%7D=456,000,000). |
| Minter      | `sdk.AccAddress` | It is the address of the minter for the *fan token*. It can be changed to trasfer the minting ability of the token during the time.                                                                                                                                                                                                                                                                                                                                                                                                                 |
| metadata    | `Metadata`       | It is generated once and it is made up of `Name`, `Symbol`, `URI` and `Authority` (i.e., is the address of the wallet which is able to perform edits on the `URI`). More specifically, the URI contains a link to a resource with a set of information linked to the *fan token*.                                                                                                                                                                                                                                                                   |

**Metadata** are characterized by:

| Attribute | Type             | Description                                                                                                                                                                                                                                                                                                                                  |
| --------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name      | `string`         | It is chosen once by the user. It should correspond to the long name the user want to associate to the symbol (e.g., Dollar, Euro, BitSong). It can also be empty and its max length is of 128 characters.                                                                                                                                   |
| symbol    | `string`         | It is chosen once by the user and can be any string matching the pattern `^[a-z0-9]{1,64}$`, i.e., any lowercase string containing letters and digits with a length between 1 and 64 characters. It should follow the ISO standard for the [alphabetic code](https://www.iso.org/iso-4217-currency-codes.html) (e.g., USD, EUR, BTSG, etc.). |
| uri       | `string`         | It is a link to a resource which contains a set of information linked to the *fan token*. It can also be empty and its max length is of 512 characters.                                                                                                                                                                                      |
| authority | `sdk.AccAddress` | It is the address of the authority for the *fan token* `metadata` managment. It can be changed to trasfer the ability of changing the metadata the token during the time.                                                                                                                                                                    |

#### Lifecycle of a fan token

It is possible to entirely represent the lifecycle of a fan token through Finite State Machine (FSM) diagrams. We will present two representations:

* the first refers to the fan token **object**. We can compare such a definition with that of currency (e.g., Euro, Dollar, BitSong);
* the second, instead, is referred to the lifecycle of the fan token **instance**. Such definition is comparable with that of coin/money (e.g., the specific 1 Euro coin you could have in your pocket at a particular moment in time).

We can describe the lifecycle of a fan token **object** through two states.

Referring to the figure above, as detailed in the documentation, to "create" the fan token, we need to **issue it**. This operation leads to the birth of the object and thus to its first state, state *1*. Here, the token is related to a `minter`, who is able to mint the token to different wallets, and an `authority`, that is responsible for managing the `metadata`. It is important to recall that some operations are reversible, while some others are not. For example, reaching the max-supply through minting operations, can be reverted by burning tokens. While, for example, the selection of an empty address for the minter (which strictly means **disable minting** operations) is a **irreversible** operation.

Referring to the lifecycle of a fan token **instance**, it is possible to identify two states.

Concerning to the figure above, when the fan token object is issued, we can **mint** it. Minting leads to the birth of a new instance, moving the fan token instance to state *1*. In this state, the token can be:

* **traded**, which produces the changing of the owner of the instance, without modifying the landing state. To make it clearer, it can be considered as the simple exchange of money between two users. This does not modify the landing state;
* **burned**, which produces a state change to the state *2*, where the authority cannot operate on the fan token instance anymore.

#### Uniqueness of the denom

The *denom* is calculated on first `Minter`, `Symbol`, `Name` and `Block Height` of the issuing transaction of the fan token.

```go
func GetFantokenDenom(height int64, minter sdk.AccAddress, symbol, name string) string {
	bz := []byte(fmt.Sprintf("%d%s%s%s", height, minter.String(), symbol, name))
	return "ft" + tmcrypto.AddressHash(bz).String()
}
```

The *denom* of every fan token starts with the prefix `ft`. Follows a **hash** of `Block Height`, first `Minter`, `Symbol` and `Name` of the *fan token*. This *denom* is used as base denom for the fan token, and, for this reason, it should be **unique**. In this sense, since the hash depends both on the first `Minter` and the `Block Height`, multiple fan tokens with the same name and symbol can co-exist even created by the same address but they must be created from transactions in different blocks.

## State

The `fantoken` module keeps track of **parameters** and **fan tokens**.

```
Params:			types.Params
FanTokens:		[]types.FanToken
```

### Params

In the state definition, we can find the **Params**. This section corresponds to a module-wide configuration structure that stores system parameters. In particular, it defines the overall fantoken module functioning and contains the **issueFee**, **mintFee** and **burnFee** for the *fan token*. Such an implementation allows governance to decide the issue fee, but also the mint and burn fees the users have to pay to perform these operations with the tokens, in an arbitrary way - since proposals can modify it.

```go
type Params struct {
	IssueFee	sdk.Coin
	MintFee		sdk.Coin
	BurnFee		sdk.Coin
}
```

### Fantoken

The state contains a list of **Fantokens**. They are fan tokens (fungible tokens deriving by the ERC-20 Standard), and their state information is:

* **Denom**, that corresponds to the identifier of the fan token. It is a `string`, automatically calculated on the first `Minter`, `Symbol`, `Name` and `Block Height` of the issuing transaction of the *fan token* as explained in concepts, and *cannot change* for the whole life of the token;
* **MaxSupply**, that represents the upper limit for the total supply of the tokens. More specifically, it is an `integer number`, expressed in micro unit (![formula](https://render.githubusercontent.com/render/math?math=%5Ccolor%7Bgray%7D%5Cmu=10%5E%7B-6%7D)) as explained in concepts, that *cannot change* for the whole life of the token and which corresponds to the maximum number the supply can reach in any moment;
* **Minter**, which corresponds to the address of the current `minter` for the token. It is an address and *can change* during the token lifecycle thanks to the **minting ability transfer**. When the `minter` address is set to an empty value, the token can be minted no more;
* **MetaData**, which contains metadata for the *fan token* and is made up of the `Name`, the `Symbol`, a `URI` and an `Authority` as described in concepts.

More specifically, the `metadata` *can change* during the life of the token according to:

* **URI** can be changed by the `authority`. It can be changed until when the authority is available;
* **Authority** which can be transferred by the current authority until when the `authority` itself is not set to an empty value.

```go
type FanToken struct {
	Denom		string
	MaxSupply	sdk.Int
	Minter		string
	MetaData	types.Metadata
}

type Metadata struct {
	Name		string
	Symbol      string
	URI         string
	Authority	string
}
```

## Messages

Messages (`msg`s) are objects that trigger state transitions. Messages are wrapped in transactions (`tx`s) that clients submit to the network. The BitSong SDK wraps and unwraps `fantoken` module messages from transactions.

### MsgIssue

The `MsgIssue` message is used to issue a new *fan token*. It takes as input `Symbol`, `Name`, `MaxSupply` (expressed in micro unit (![formula](https://render.githubusercontent.com/render/math?math=%5Ccolor%7Bgray%7D%5Cmu=10%5E%7B-6%7D)) as explained in concepts), `Authority` (i.e., the address of the wallet which is able to modify the `metadata` of the *fan token*), `URI` (which is a link to the `fan token` metadata) and the `Minter` (i.e., the address of the wallet which is able to mint the *fan token*). Thanks to these values, the module can verify if the `Authority` and the `Minter` are valid addresses for the issue of a new token (they are not a blocked addresses or module accounts) and also verifies the values for the `name` (which can be any strings with max 128 characters, even the empty one), the `symbol` (that must match the regex `^[a-z0-9]{1,64}$`) and the `uri` (which can be any strings with less than 513 characters, even the empty one). At this point, it proceeds with token issuing and emitting of corresponding events. More specifically, the **module deduct the `issuing fee` from the `minter` wallet**, calculates the `denom`, generates the `metadata`, and finally creates the *fan token*. At this point, an `EventIssue` event is emitted.

```go
type MsgIssue struct {
	Symbol			string
	Name			string
	MaxSupply		sdk.Int
	Authority		string
	URI				string
	Minter			string
}
```

### MsgDisableMint

The `MsgDisableMint` message is used to **irreversibly** disable the minting ability for an existing *fan token*. It takes as input `Denom` and `Minter` (described in fan token definition). Thanks to these values, the module can verify whether the modifications are lawful (i.e., requested by the `Minter` and in accord with the state transition definition). The message permits to change the "*mintability*" of the *fan token*. In particular, at the issuing, the *fan token* can be minted (in fact the `Minter` address is a value different from an empty one). Later on, during the lifecycle of the *fan token*, the `minter` can disable the possibility to mint new tokens (check the relative docs for more details). In such a scenario, it is possible to disable the mintability, by set an empty value as the address for the new `minter`) and, this operation, causes the `MaxSupply` of the token to be updated at the current value of the supply. At this point, an `EventDisableMint` event is emitted.

```go
type MsgDisableMint struct {
	Denom			string
	Minter			string
}
```

### MsgMint

The `MsgMint` message is used to mint an existing *fan token*. It takes as input `Recipient`, `Coin`, and `Minter` (all described in fan token definition except the `Coin`, which is an object made up of the `denom` of the *fan token* to mint and its quantity, expressed in micro unit). In such a message, the `Recipient` is not required and its default value is the same of `Minter`. Thanks to these values, the module can verify whether the minting operation is lawful (i.e., requested: by the minter, on a mintable *fan token*, and for a quantity that allow to do not overcome the maximum supply), recalling that only the minter for of the *fan token* can mint the token to any specified account. At this point, the token is minted, the supply is increased, the coins are sent to the recipient, the **module deduct the `mint fee` from the `minter` wallet** and an `EventMint` event is emitted.

```go
type MsgMint struct {
	Recipient		string
	Coin			sdk.Coin
	Minter			string
}
```

### MsgBurn

The `MsgBurn` message is used to burn *fan token*. It takes as input `Coin`, and `Sender` (as above, the `Coin` is an object made up of the `denom` of the *fan token* to burn and its quantity, expressed in micro unit, while `Sender` must be equal to the user who want to burn the tokens). The module can verify whether the burning operation is lawful (i.e., the sender has a sufficient amount of token, in other words check if `sender balance` > `amount to burn`). At this point, the token is burned, the supply is lowered, the **module deduct the `burn fee` from the `owner` wallet** and an `EventBurn` event is emitted. In such a way, that specific token ends its lifecycle, as shown in the relative docs.

```go
type MsgBurn struct {
	Coin	sdk.Coin
	Sender	string
}
```

### MsgSetAuthority

The `MsgSetAuthority` message is used to transfer or disable the ability to change the metadata of a *fan token*. It takes as input `Denom`, `oldAuthority`, and `newAuthority` (`Denom` is described in fan token definition, `old` and `new` `Authorities` are respectively the actual and the new addresses of the wallet who are able to change the metadata of the token). When the `newAuthority` is an empty address, the capability to change the metadata is **irreversibly** disabled. The module can verify whether the operation is lawful (i.e., the requesting account is actually the authority for the *fan token*, the *fan token* metadata can be changed and the destination account is neither blocked nor a module account). At this point, if the `newAuthority` is a *not empty* address, it becomes the new token authority. On the other hand, the *fan token* metadata cannot be changed anymore. Anyway, an `EventSetAuthority` event is emitted. This operation enable the **authority transfer** transition described in the lifecycle of a fan token.

```go
type MsgTransferAuthority struct {
	Denom		string
	oldAuthority	string
	newAuthority	string
}
```

### MsgSetMinter

The `MsgSetMinter` message is used to transfer the ability to mint a *fan token*. It takes as input `Denom`, `oldMinter`, and `newMinter` (`Denom` is described in fan token definition, `old` and `new` `Minters` are respectively the actual and the new addresses of the wallet who are able to mint the token). When the `newMinter` is an empty address, it works as the `MsgDisableMint`. The module can verify whether the operation is lawful (i.e., the requesting account is actually the minter for the *fan token*, the *fan token* can be minted and the destination account is neither blocked nor a module account). At this point, if the `newMinter` is a *not empty* address, it becomes the new token minter. On the other hand, the *fan token* cannot be minted anymore. Anyway, an `EventSetMinter` event is emitted. This operation enable the **minter transfer** transition described in the lifecycle of a fan token.

```go
type MsgSetMinter struct {
	Denom		string
	oldMinter	string
	newMinter	string
}
```

### MsgSetUri

The `MsgSetMinter` message is used to modify the URI in the *fan token* metadata. It takes as input `Denom`, new `URI`, and `Authority` (`Denom` and `URI` are described in fan token definition, `Authority` is the actual address of the wallet who is able to modify the *fan token* metadata). The module can verify whether the operation is lawful (i.e., the requesting account is actually the authority for the *fan token*, the *fan token* metadata can be changed and the new uri is a valid one, as described in Fan Token parameters definition). At this point, an `EventSetUri` event is emitted.

```go
type MsgSetUri struct {
	Denom		string
	URI		string
	Authority	string
}
```

## Events

The fantoken module emits the following events:

### EventIssue

| Type                                | Attribute Key | Attribute Value                      |
| ----------------------------------- | ------------- | ------------------------------------ |
| message                             | action        | `/bitsong.fantoken.v1beta1.MsgIssue` |
| bitsong.fantoken.v1beta1.EventIssue | denom         | {denom}                              |

### EventDisableMint

| Type                                      | Attribute Key | Attribute Value                            |
| ----------------------------------------- | ------------- | ------------------------------------------ |
| message                                   | action        | `/bitsong.fantoken.v1beta1.MsgDisableMint` |
| bitsong.fantoken.v1beta1.EventDisableMint | denom         | {denom}                                    |

### EventMint

| Type                               | Attribute Key | Attribute Value                     |
| ---------------------------------- | ------------- | ----------------------------------- |
| message                            | action        | `/bitsong.fantoken.v1beta1.MsgMint` |
| bitsong.fantoken.v1beta1.EventMint | recipient     | {recipient}                         |
| bitsong.fantoken.v1beta1.EventMint | coin          | {coin}                              |

### EventBurn

| Type                               | Attribute Key | Attribute Value                     |
| ---------------------------------- | ------------- | ----------------------------------- |
| message                            | action        | `/bitsong.fantoken.v1beta1.MsgBurn` |
| bitsong.fantoken.v1beta1.EventBurn | sender        | {sender}                            |
| bitsong.fantoken.v1beta1.EventBurn | coin          | {coin}                              |

### EventSetAuthority

| Type                                            | Attribute Key  | Attribute Value                             |
| ----------------------------------------------- | -------------- | ------------------------------------------- |
| message                                         | action         | `/bitsong.fantoken.v1beta1.MsgSetAuthority` |
| bitsong.fantoken.v1beta1.EventTransferAuthority | denom          | {denom}                                     |
| bitsong.fantoken.v1beta1.EventTransferAuthority | old\_authority | {old\_authority}                            |
| bitsong.fantoken.v1beta1.EventTransferAuthority | new\_authority | {new\_authority}                            |

### EventSetMinter

| Type                                         | Attribute Key  | Attribute Value                          |
| -------------------------------------------- | -------------- | ---------------------------------------- |
| message                                      | action         | `/bitsong.fantoken.v1beta1.MsgSetMinter` |
| bitsong.fantoken.v1beta1.EventTransferMinter | denom          | {denom}                                  |
| bitsong.fantoken.v1beta1.EventTransferMinter | old\_minter    | {old\_minter}                            |
| bitsong.fantoken.v1beta1.EventTransferMinter | new\_authority | {new\_minter}                            |

### EventSetUri

| Type                                 | Attribute Key | Attribute Value                       |
| ------------------------------------ | ------------- | ------------------------------------- |
| message                              | action        | `/bitsong.fantoken.v1beta1.MsgSetUri` |
| bitsong.fantoken.v1beta1.EventSetUri | denom         | denom}                                |

## Parameters

Fantoken module parameters.

| Key      | Type     | Value                                   |
| -------- | -------- | --------------------------------------- |
| IssueFee | sdk.Coin | {"denom": "ubtsg", "amount": "1000000"} |
| MintFee  | sdk.Coin | {"denom": "ubtsg", "amount": "0"}       |
| BurnFee  | sdk.Coin | {"denom": "ubtsg", "amount": "0"}       |

## Client

### Transactions

The `transactions` commands allow users to `issue`, `mint`, `burn`, `disable minting`, `transfer minting and editing capabilities` for *fan tokens*.

```
bitsongd tx fantoken --help
```

#### issue

```
bitsongd tx fantoken issue \
    --name "fantoken name" \
    --symbol "bitangel" \
    --max-supply 100000000000 \
    --uri "ipfs://...." \
    --from <key-name> -b block --chain-id <chain-id> --fees <fee>
```

#### mint

```
bitsongd tx fantoken mint [amount][denom] \
    --recipient <address> \
    --from <key-name> -b block --chain-id <chain-id> --fees <fee>
```

#### burn

```
bitsongd tx fantoken burn [amount][denom] \
    --from <key-name> -b block --chain-id <chain-id> --fees <fee>
```

#### set-authority

```
bitsongd tx fantoken set-authority [denom] \
    --new-authority <address> \
    --from <key-name> -b block --chain-id <chain-id> --fees <fee>
```

#### set-minter

```
bitsongd tx fantoken set-minter [denom] \
    --new-minter <address> \
    --from <key-name> -b block --chain-id <chain-id> --fees <fee>
```

#### set-uri

```
bitsongd tx fantoken set-uri [denom] \
    --uri <uri> \
    --from <key-name> -b block --chain-id <chain-id> --fees <fee>
```

#### disable-mint

```
bitsongd tx fantoken disable-mint [denom] \
    --from <key-name> -b block --chain-id <chain-id> --fees <fee>
```

### Query

The `query` commands allow users to query the `fantoken` module.

```
bitsongd q fantoken --help
```

#### denom

```
bitsongd q fantoken denom <denom>
```

#### authority

```
bitsongd q fantoken authority <address>
```

#### params

```
bitsongd q fantoken params
```


# Merkledrop

As of upgrade v018, the x/merkletree module has been deprecated in replace for a CosmWasm implementation.


# NFTs

## What are NFTs?

NFTs, or non-fungible tokens, are already whipping up a storm across the entire entertainment industry. NFTs are tokens linked to provably scarce or unique digital assets such as an image file, a video clip, or a piece of music.

So how are NFTs transforming the music industry? The creative opportunities are almost endless, but here are a few ways.

Create unique digital artwork to accompany your music or gigs&#x20;

Issue autographs and signed photographs as NFTs&#x20;

Drop a song or album as an exclusive, limited-edition release only available in NFT format&#x20;

Print gig tickets as NFTs, and require entrants to send their tokens to a burn address to redeem them on the day&#x20;

Explore innovative, cross-marketing efforts in a digital metaverse

BitSong allows any artist to create their own NFTs backed by music, art, video clips, or any kind of digital media you choose. In the BitSong ecosystem, NFTs can be traded for BTSG or for the artist Fan Token.

What’s more, because BitSong runs on its own, energy-efficient proof-of-stake blockchain, our green credentials are sound.


# Marketplace


# CosmWasm

## What is CosmWasm?[​](https://docs.cosmwasm.com/docs/1.0/#what-is-cosmwasm) <a href="#what-is-cosmwasm" id="what-is-cosmwasm"></a>

CosmWasm is a smart contracting platform built for the Cosmos ecosystem. Simply put, it's the Cosmos (Cosm) way of using WebAssembly (Wasm) hence the name.

CosmWasm is written as a module that can plug into the Cosmos SDK. This means that anyone currently building a blockchain using the Cosmos SDK can quickly and easily add CosmWasm smart contracting support to their chain, without adjusting existing logic.

[Rust](https://www.rust-lang.org/) is currently the most used programming language for CosmWasm, in the future, it is possible to have different programming languages like [AssemblyScript](https://www.assemblyscript.org/)

The purpose of this documentation is to give a deep dive into the technology for developers who wish to try it out or integrate it into their products. Particularly, it is aimed at Go developers with experience with the Cosmos SDK, as well as Rust developers looking for a blockchain platform.

Read more about [CosmWasm](https://docs.cosmwasm.com/docs/1.0/)


# Install rust

Rust is the main programming language used for CosmWasm smart contracts. While WASM smart contracts can theoretically be written in any programming language, CosmWasm libraries and tooling work best with Rust.

First, [**install rustup**](https://rustup.rs/).

Then run the following commands:

```bash
# 1. Set 'stable' as the default release channel:
rustup default stable
cargo version
# If this is lower than 1.50.0+, update
rustup update stable

# 2. Add WASM as the compilation target:
rustup target list --installed
rustup target add wasm32-unknown-unknown

# 3. Install the following packages to generate the contract:
cargo install cargo-generate --features vendored-openssl
cargo install cargo-run-script
```


# Deploy a Smart Contract

### **Clone cw-template**

For this example, we will use the [cw-template](https://github.com/bitsongofficial/cw-template) repo with counter example.

```bash
cargo generate --git https://github.com/bitsongofficial/cw-template.git --name my-first-contract
```

Select `false`

```bash
🔧   Destination: /home/angelo/Progetti/my-first-contract ...
🔧   Generating template ...
? 🤷   Would you like to generate the minimal template?
The full template includes some example logic in case you're new to CosmWasm smart contracts.
The minimal template assumes you already know how to write your own logic, and doesn't get in your way. ›
❯ false
  true
```

```bash
cd my-first-contract
```

### **Compile the wasm contract**

To deploy smart contracts, you must compile the code and make it an executable wasm binary file. We will compile the wasm contract with stable toolchain.

Compile using the command below:

```bash
# Set 'stable' as the default release channel:
rustup default stable
cargo wasm
```

After this compiles, it should produce a file in `target/wasm32-unknown-unknown/release/my_first_contract.wasm`. If you check the size of the file by using the `ls -lh` command, it shows around `1.9M`. This is a release build, but not stripped of all unneeded code. To produce a much smaller version, you can run this which tells the compiler to strip all unused code out:

```bash
RUSTFLAGS='-C link-arg=-s' cargo wasm
```

This produces a file about `155K`. To reduce gas costs, the binary size should be as small as possible. This will result in a less costly deployment, and lower fees on every interaction. Also, if you don’t use compilation optimization, CosmWasm smart contract will not be deployed well due to `exceeds limit` error.

### **Optimized Compilation**

You can do further optimization using [rust-optimizer](https://github.com/CosmWasm/rust-optimizer). **rust-optimizer** produces reproducible builds of CosmWasm smart contracts and does heavy optimization on the build size, using binary stripping and `wasm-opt`.

```bash
docker run --rm -v "$(pwd)":/code \
    --mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \
    --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \
    cosmwasm/rust-optimizer:0.12.8
```

Binary file will be at `artifacts/my_first_contract.wasm` folder and its size will be about `130K`, which is more smaller than when only `RUTFLAGS` was used.

### **Store to BitSong Cosmwasm Testnet**

We have the wasm binary executable ready. Now it is time to store the code to the **BitSong Cosmwasm Testnet**.

```bash
RES=$(bitsongd tx wasm store artifacts/my_first_contract.wasm --from mywallet --gas-prices 0.1ubtsg --gas auto --gas-adjustment 1.3 -y --output json -b block)
```

* `bitsongd tx wasm store` : upload a wasm binary
* `--from` : name or address of private key with which to sign.
* `--gas-prices` : gas prices in decimal format to determine the transaction fee.
* `--gas` : gas limit to set per-transaction. set to “auto” to calculate sufficient gas automatically
* `--gas-adjustment` : adjustment factor to be multiplied against the estimate returned by the tx simulation.
* `-y` : to skip tx broadcasting prompt confirmation.
* `--output` : output format.
* `-b` : transaction broadcasting mode

Once that is complete, you can get the `CODE_ID` easily using `jq`.

`jq` is an open source that helps extract data from JSON. Install it according to your OS using the following command:

```bash
# Linux
sudo apt-get install jq

# Mac
brew install jq
```

Run the following command to set the `CODE_ID` as a variable:

```bash
# get CODE_ID
CODE_ID=$(echo $RES | jq -r '.logs[0].events[-1].attributes[1].value')
echo $CODE_ID
```

#### **Instantiate the contract**

We can now create an instance of this wasm contract. First, set the initial state of the instance in the `INIT` variable and run the `instantiate command`.

```bash
# set the initial state of the instance
INIT='{"count":100}'

# instantiate the contract
bitsongd tx wasm instantiate $CODE_ID "$INIT" \
    --from mywallet --label "my first contract" --gas-prices 0.025ubtsg --gas auto --gas-adjustment 1.3 -b block -y --no-admin
```

* `bitsongd tx wasm instantiate` : instantiate a wasm contract using **CODE\_ID** of the uploaded binary.
* `--label` : human-readable name for this contract in lists.
* `--no-admin` : you must set this explicitly if you don’t want an admin.

Get the contract address using the command following:

```bash
CONTRACT_ADDR=$(bitsongd query wasm list-contract-by-code $CODE_ID --output json | jq -r '.contracts[0]')
echo $CONTRACT_ADDR
```

#### **Query the contract**

Now, let’s see if the contract we deployed works well.

#### **Get contract’s count**

Send a `get_count` query to check the count value. The previously set `INIT` state is output as it is.: `{"data":{"count":100}}`

```bash
QUERY='{"get_count":{}}'
bitsongd query wasm contract-state smart $CONTRACT_ADshDR "$QUERY" --output json
```

The output will be

```json
{"data":{"count":100}}
```

* `bitsongd query wasm contract-state smart` : calls contract with given address with query data and prints the returned result

### **Execute the Contract**

#### **Increment contract’s count**

This time, let’s send an `increment` transaction that increases the count value by +1. Because the transaction changes the internal state of the contract, you must pay gas fees.

If you run the `get_count` query again after sending the `increment` transaction, you can see that +1 has increased from the previous count value.

```bash
TRY_INCREMENT='{"increment": {}}'
bitsongd tx wasm execute $CONTRACT_ADDR "$TRY_INCREMENT" --from mywallet --gas-prices 0.025ubtsg --gas auto --gas-adjustment 1.3 -y
```

#### **Reset contract’s count**

Lastly, let’s send a `reset` transaction. Like increment, reset transaction also changes the internal state of contract, so you must pay gas fees.

```bash
RESET='{"reset": {"count": 0}}'
bitsongd tx wasm execute $CONTRACT_ADDR "$RESET" --from mywallet --gas-prices 0.025ubtsg --gas auto --gas-adjustment 1.3 -y
```


# Propose to Upload Cosmwasm Contracts


# IBC

Inter Blockchain Communication

## What is IBC?

Inter Blockchain Communication, or IBC, is a protocol that’s part of the Cosmos technology stack, allowing seamless communication between blockchains. It’s designed to overcome one of the core challenges of legacy public blockchains, which is that they were built to operate as silos, with no opportunity to transfer data or tokens between platforms.

IBC enables BitSong to interoperate with any other IBC-enabled blockchain in the Cosmos ecosystem. Furthermore, with innovations such as the Gravity Bridge, IBC is also being used to power bridges to non-Cosmos blockchain ecosystems like Ethereum.

In practice, IBC allows BTSG to become listed on any Cosmos DEX such as Gravity DEX or Osmosis or others that will be deployed in the future. It will also allow anyone holding NFTs, Fan Tokens, or BTSG, the opportunity to use them in applications on other compatible blockchains.

For instance, as the Cosmos DeFi ecosystem develops, someone could use the value stored in their BitSong-issued NFTs as collateral to take out a loan. Please note that this documentation will be updated as and when such integrations become available to users.

IBC is also a critical enabler for the Liquidity Module.

### IBC Message Lifecycle

* Sending a packet (Source chain)
* Receiving a packet (Destination chain)
* Sending an acknowledgement (Destination chain)
* Receiving an acknowledgement (Source chain)

### Light Clients &#x20;

#### Expired Clients&#x20;

#### Upgrading Clients&#x20;

#### Supported Light Clients&#x20;

### IBC Token Hashes

### IBC & CosmWasm


# Auth

This document specifies the auth module of the Cosmos SDK.

The auth module is responsible for specifying the base transaction and account types for an application, since the SDK itself is agnostic to these particulars. It contains the ante handler, where all basic transaction validity checks (signatures, nonces, auxiliary fields) are performed, and exposes the account keeper, which allows other modules to read, write, and modify accounts.


# Bank

The bank module is responsible for handling multi-asset coin transfers between accounts and tracking special-case pseudo-transfers which must work differently with particular kinds of accounts (notably delegating/undelegating for vesting accounts). It exposes several interfaces with varying capabilities for secure interaction with other modules which must alter user balances.

In addition, the bank module tracks and provides query support for the total supply of all assets used in the application.


# Crisis

The crisis module halts the blockchain under the circumstance that a blockchain invariant is broken. Invariants can be registered with the application during the application initialization process.


# Community Pool

## What is the BTSG Community Pool?

The BitSong Community Pool is a self-managing fund that exists to support the ongoing development of the BitSong ecosystem and community.

2% of all BTSG created by BitSong network validators is directed into the Community Pool, meaning that the Pool receives new BTSG every five seconds.

Any BTSG holder can make a proposal, and every BTSG holder can vote on it.

## What Kind of Proposals Are Possible?

Any proposal is possible, so get creative! Here are a few ideas to get started:

Let’s launch a contest for artists with BTSG prize money&#x20;

Let’s sponsor a music festival&#x20;

Let’s add a new feature to BitSong&#x20;

Let’s support a charitable collaboration between artists on BitSong Let’s re-invest some of the fund to generate passive returns

## How to Submit a Community Pool Proposal

Community Pool proposals follow the standard governance process. Please see the section on “Participating in BitSong governance” for information.


# Consensus

Functionality to modify CometBFT's ABCI consensus params.

***

source : <https://github.com/cosmos/cosmos-sdk/blob/v0.47.8/x/consensus/README.md>&#x20;


# Distribution

This simple distribution mechanism is how Bitsong passively distribute rewards between validators and delegators.

The mechanism operates as follows. Collected rewards are pooled globally and divided out passively to validators and delegators. Each validator has the opportunity to charge commission to the delegators on the rewards collected on behalf of the delegators. Fees are collected directly into a global reward pool and validator proposer-reward pool. Due to the nature of passive accounting, whenever changes to parameters which affect the rate of reward distribution occurs, withdrawal of rewards must also occur.

* Whenever withdrawing, one must withdraw the maximum amount they are entitled to, leaving nothing in the pool.
* Whenever bonding, unbonding, or re-delegating tokens to an existing account, a full withdrawal of the rewards must occur (as the rules for lazy accounting change).
* Whenever a validator chooses to change the commission on rewards, all accumulated commission rewards must be simultaneously withdrawn.

#### Concepts

In Proof of Stake (PoS) blockchains, rewards gained from transaction fees are paid to validators. The fee distribution module fairly distributes the rewards to the validators' constituent delegators.&#x20;

Rewards are calculated per period. The period is updated each time a validator's delegation changes, for example, when the validator receives a new delegation. The rewards for a single validator can then be calculated by taking the total rewards for the period before the delegation started, minus the current total rewards.

The commission to the validator is paid when the validator is removed or when the validator requests a withdrawal. The commission is calculated and incremented at every `BeginBlock` operation to update accumulated fee amounts.

The rewards to a delegator are distributed when the delegation is changed or removed, or a withdrawal is requested. Before rewards are distributed, all slashes to the validator that occurred during the current delegation are applied.

### Reference Counting

In F1 fee distribution, the rewards a delegator receives are calculated when their delegation is withdrawn. This calculation must read the terms of the summation of rewards divided by the share of tokens from the period which they ended when they delegated, and the final period that was created for the withdrawal.

Additionally, as slashes change the amount of tokens a delegation will have (but we calculate this lazily, only when a delegator un-delegates), we must calculate rewards in separate periods before / after any slashes which occurred in between when a delegator delegated and when they withdrew their rewards. Thus slashes, like delegations, reference the period which was ended by the slash event.

All stored historical rewards records for periods which are no longer referenced by any delegations or any slashes can thus be safely removed, as they will never be read (future delegations and future slashes will always reference future periods). This is implemented by tracking a `ReferenceCount` along with each historical reward storage entry. Each time a new object (delegation or slash) is created which might need to reference the historical record, the reference count is incremented. Each time one object which previously needed to reference the historical record is deleted, the reference count is decremented. If the reference count hits zero, the historical record is deleted.

### Begin Block

At each `BeginBlock`, all fees received in the previous block are transferred to the distribution `ModuleAccount` account. When a delegator or validator withdraws their rewards, they are taken out of the `ModuleAccount`. During begin block, the different claims on the fees collected are updated as follows:

* The reserve community tax is charged.
* The remainder is distributed proportionally by voting power to all bonded validators

### Messages

#### MsgSetWithdrawAddress

#### MsgWithdrawDelegatorReward

#### WithdrawValidatorCommission

#### MsgUpdateParams

### Hooks

#### Create or modify delegation distribution

#### Validator Created

#### Validator removed

#### Validator is slashed

### CLI

### GRPC

***

Source: <https://github.com/cosmos/cosmos-sdk/tree/main/x/distribution>&#x20;


# Evidence

Evidence is an implementation of a Cosmos SDK module, per [ADR 009](https://docs.cosmos.network/master/docs/architecture/adr-009-evidence-module.html), that allows for the submission and handling of arbitrary evidence of misbehavior such as equivocation and counterfactual signing.

The evidence module differs from standard evidence handling which typically expects the underlying consensus engine, e.g. Tendermint, to automatically submit evidence when it is discovered by allowing clients and foreign chains to submit more complex evidence directly.

All concrete evidence types must implement the `Evidence` interface contract. Submitted `Evidence` is first routed through the evidence module's `Router` in which it attempts to find a corresponding registered `Handler` for that specific `Evidence` type. Each `Evidence` type must have a `Handler` registered with the evidence module's keeper in order for it to be successfully routed and executed.

Each corresponding handler must also fulfill the `Handler` interface contract. The `Handler` for a given `Evidence` type can perform any arbitrary state transitions such as slashing, jailing, and tombstoning.


# Governance

## BitSong Governance

BitSong’s decentralized network is based on a robust system of governance and a Delegated Proof-of-Stake (DPoS) consensus.

### BitSong DPoS Governance Overview

In 2014, Daniel Larimer developed the Delegated Proof of Stake (DPoS) mechanism as a variation on the Proof-of-Stake consensus. DPoS has since been adopted and adapted by several networks, including BitSong.

BitSong DPoS allows users to commit their balances as votes, which are used to elect a fixed number of delegates to validate incoming transactions on the blockchain. As such, validators manage blockchain operations on behalf of their delegators, guaranteeing security and consensus.

The DPoS model tends to reduce latency and increase the performance of a network, meaning it can process more transactions per second. This is mainly due to the fact that it allows consensus to be reached with a lower number of validating nodes. Currently, there are 64 validators on the BitSong mainnet.

[Visit the BitSong mainnet explorer.](https://explorebitsong.com/)

Changes to the BitSong network and its rules are subject to governance votes. Examples of decisions that may be put to a governance vote include mainnet upgrades, changes to voting periods, changes to the size of the validator set, or allocation of Community Pool funds.

### Role of Validators

The BitSong Network relies on a set of validators that are responsible for committing new blocks in the blockchain. These validators participate in the consensus protocol by broadcasting votes which contain cryptographic signatures signed by each validator's private key.

Validator candidates can bond their own BTSG and have BTSG delegated or staked to them by BTSG token holders.

The BitSong Network currently has slots for 64 validators, but over time this will increase to 100 validators, subject to a governance vote. Validators are selected according to the total amount of bonded BTSG – whether the BTSG is staked from the validators own wallet, or delegated to them by delegators.

The top 64 validator candidates with the most stake will become BitSong Network validators. At every block, a validator is chosen to sign that block, based on their voting power (determined by the amount of bonded tokens) at the time of the block. Validators with higher voting power will sign blocks more often than validators with lower voting power.

Validators and their delegators will earn BTSG as block provisions and tokens as transaction fees through execution of the Tendermint consensus protocol. Initially, transaction fees will be paid in BTSG. Note that validators can set commission on the fees their delegators receive as additional incentive. Choosing the right commission level is a balance, as the validator must be able to remain competitive enough to attract delegators to stake their BTSG.

Warning: If validators double-sign, are frequently offline or fail to participate in governance, their staked BTSG, including BTSG delegated to them, may be slashed. The penalty depends on the severity of the violation.

Becoming a validator comes with a set of prerequisites, including hardware and software requirements.

### Role of Delegators

Delegating your BTSG to a validator on the BitSong mainnet provides a relatively straightforward way to help secure the network and earn BTSG rewards. It requires no hardware setup, although there are some installation requirements.

As a delegator, your role is to choose a validator or validators and stake your BTSG to them. Your rewards may vary according to various factors, including the amount of BTSG staked to your chosen validator(s) and the commission your chosen validator(s) charge.

Rewards are liquid, meaning you can decide what to do with them. You could re-delegate them for a compound effect, or spend them in the BitSong music ecosystem, or trade them for crypto or fiat currencies.


# Mint

The minting mechanism was designed to:

* allow for a flexible inflation rate determined by market demand targeting a particular bonded-stake ratio
* effect a balance between market liquidity and staked supply

In order to best determine the appropriate market rate for inflation rewards, a moving change rate is used. The moving change rate mechanism ensures that if the % bonded is either over or under the goal %-bonded, the inflation rate will adjust to further incentivize or disincentivize being bonded, respectively. Setting the goal %-bonded at less than 100% encourages the network to maintain some non-staked tokens which should help provide some liquidity.

It can be broken down in the following way:

* If the inflation rate is below the goal %-bonded the inflation rate will increase until a maximum value is reached
* If the goal % bonded (67% in BitSong) is maintained, then the inflation rate will stay constant
* If the inflation rate is above the goal %-bonded the inflation rate will decrease until a minimum value is reached


# Staking

Staking in a dPos (Delegated Proof of Stake) blockchain refers to the act of holding a certain amount of cryptocurrency in a wallet to support the network's operation and earn rewards for doing so. In a dPos blockchain, instead of traditional mining, token holders can vote for network validators or "delegates" who are responsible for processing and validating transactions on the blockchain.

By staking tokens, users can participate in the network's governance and decision-making process, as well as earn rewards for their contribution. The amount of rewards earned depends on various factors such as the amount of tokens staked, the length of time they are staked, and the percentage of total network tokens being staked.

Staking in a dPos blockchain typically requires a user to lock up their tokens for a certain period of time, during which they cannot be spent or transferred. However, this lockup period can vary depending on the specific blockchain protocol and its rules.

Overall, staking in a dPos blockchain allows users to participate in the network's operation and governance, while also earning rewards for their contribution and helping to secure the blockchain network.


# Slashing

In a dPos (Delegated Proof of Stake) blockchain, slashing refers to the penalty imposed on network validators or "delegates" who violate network rules or fail to perform their duties properly. Slashing is a mechanism designed to ensure that network validators are incentivized to act in the best interest of the network and avoid malicious behavior.

When a delegate is found to have violated network rules, such as double-spending, fraud, or failing to validate transactions, they can be subjected to a penalty, which typically involves the loss of a portion of their staked tokens. This loss of tokens is known as slashing.

The amount of tokens that are slashed depends on the severity of the violation and the specific rules of the blockchain protocol. In some cases, a validator may be removed from the network.

Slashing serves as a deterrent against malicious behavior by network validators, as it imposes a significant financial penalty for improper conduct. This, in turn, helps to ensure the security and stability of the blockchain network and the trust of its users.

Overall, slashing is an important mechanism in a dPos blockchain to ensure that network validators act in the best interest of the network, and to maintain the integrity and security of the blockchain.

#### Slashing Parameters on BitSong:

* Signed Blocks Window - **10,000**
* Min Signed Per Window - **5.00%**
* Downtime Jail Duration - **3600s**
* Slash Fraction Doublesign - **5.00%**
* Slash Fraction Downtime - **1.00%**


# Upgrade

Upgrade is an implementation of a Cosmos SDK module that facilitates smoothly upgrading a live Cosmos chain to a new (breaking) software version. It accomplishes this by providing a `BeginBlocker` hook that prevents the blockchain state machine from proceeding once a pre-defined upgrade block height has been reached.

The module does not prescribe anything regarding how governance decides to do an upgrade, but just the mechanism for coordinating the upgrade safely. Without software support for upgrades, upgrading a live chain is risky because all of the validators need to pause their state machines at exactly the same point in the process. If this is not done correctly, there can be state inconsistencies which are hard to recover from.


# bitsongJS


# cw-orchestrator

## Speed up your development with cw-orchestrator

### Introduction

cw-orchestrator is the most advanced scripting, testing, and deployment framework for CosmWasm smart-contracts. It makes it easy to write cross-environment compatible code for cw-multi-test, Osmosis Test Tube, Starship (alpha), and live networks, significantly reducing code duplication and test-writing time.

Get ready to change the way you interact with contracts. The following steps will allow you to write clean code such as:

```rust
counter.upload()?;
counter.instantiate(&InstantiateMsg { count: 0 }, None, &[])?;

counter.increment()?;

let count = counter.get_count()?;
assert_eq!(count.count, 1);
```

In this quick-start guide, we will review the necessary steps in order to integrate `cw-orch` into a simple contract crate. We review integration of rust-workspaces (multiple contracts) at the end of this page.

> **NOTE**: *Additional content*
>
> If you're moving quicker than everybody else, we suggest looking at [a before-after review of this example integration](https://github.com/AbstractSDK/cw-orch-counter-example/compare/e0a54b074ca1a894bb6e58276944cf2013d152f2..main). This will help you catch the additions you need to make to your contract to be able to interact with it using cw-orchestrator.

**Video Workshop**

If you prefer watching a video, you can follow the workshop below:

{% embed url="<https://youtu.be/IZ5_r9JEoUs>" %}

### Summary

* Speed up your development with cw-orchestrator
  * Introduction
  * Summary
  * Single Contract Integration
    * Adding `cw-orch` to your `Cargo.toml` file
    * Creating an Interface
    * Interaction helpers
    * Using the integration
  * Integration in a workspace
    * Handling dependencies
    * Creating an interface crate
    * Integrating single contracts
  * More examples and scripts

### Single Contract Integration

#### Adding `cw-orch` to your `Cargo.toml` file

To use cw-orchestrator, you need to add `cw-orch` to your contract's TOML file. Run the command below in your contract's directory:

```shell
cargo add cw-orch
```

Alternatively, you can add it manually in your `Cargo.toml` file as shown below:

```toml
[dependencies]
cw-orch = {version = "0.27.0" } # Latest version at time of writing
```

> **NOTE**: Even if you include `cw-orch` in your dependencies here, it won't be included in your `wasm` contract.

#### Creating an Interface

When using a single contract, we advise creating an `interface.rs` file inside your contract's directory. You then need to add this module to your `lib.rs` file. This file should not be included inside you final wasm. In order to do that, you need to add `#[cfg(not(target_arch = "wasm32"))]` when importing the file.

```rust
#[cfg(not(target_arch = "wasm32"))]
mod interface;
```

Then, inside that `interface.rs` file, you can define the interface for your contract:

```rust
use cw_orch::{interface, prelude::*};

use crate::msg::{ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg};

pub const CONTRACT_ID: &str = "counter_contract";

#[interface(InstantiateMsg, ExecuteMsg, QueryMsg, MigrateMsg, id = CONTRACT_ID)]
pub struct CounterContract;

impl<Chain> Uploadable for CounterContract<Chain> {
    /// Return the path to the wasm file corresponding to the contract
    fn wasm(_chain: &ChainInfoOwned) -> WasmPath {
        artifacts_dir_from_workspace!()
            .find_wasm_path("counter_contract")
            .unwrap()
    }
    /// Returns a CosmWasm contract wrapper
    fn wrapper() -> Box<dyn MockContract<Empty>> {
        Box::new(
            ContractWrapper::new_with_empty(
                crate::contract::execute,
                crate::contract::instantiate,
                crate::contract::query,
            )
            .with_migrate(crate::contract::migrate),
        )
    }
}
```

Learn more about the content of the interface creation specifics in the official [`cw-orch`documentation](https://orchestrator.abstract.money/contracts/interfaces.html#creating-an-interface)

> **NOTE**: It can be useful to re-export this struct to simplify usage (in `lib.rs`):
>
> ```rust,ignore
> #[cfg(not(target_arch = "wasm32"))]
> pub use crate::interface::CounterContract;
> ```

#### Interaction helpers

cw-orchestrator provides a additional macros that simplify contract calls and queries. The macro implements functions on the interface for each variant of the contract's `ExecuteMsg` and `QueryMsg`.

Enabling this functionality is very straightforward. Find your `ExecuteMsg` and `QueryMsg` definitions (in `msg.rs` in our example) and add the `ExecuteFns` and `QueryFns` derive macros to them like below:

```rust
#[cw_serde]
#[derive(cw_orch::ExecuteFns)] // Function generation
/// Execute methods for counter
pub enum ExecuteMsg {
    /// Increment count by one
    Increment {},
    /// Reset count
    Reset {
        /// Count value after reset
        count: i32,
    },
}

#[cw_serde]
#[derive(cw_orch::QueryFns)] // Function generation
#[derive(QueryResponses)]
/// Query methods for counter
pub enum QueryMsg {
    /// GetCount returns the current count as a json-encoded number
    #[returns(GetCountResponse)]
    GetCount {},
}

// Custom response for the query
#[cw_serde]
/// Response from get_count query
pub struct GetCountResponse {
    /// Current count in the state
    pub count: i32,
}
```

Make sure to derive the `#[derive(cosmwasm_schema::QueryResponses)]` macro on your query messages !

Find out more about the interaction helpers in the official [`cw-orch`documentation](https://orchestrator.abstract.money/contracts/interfaces.html#entry-point-function-generation)

> **NOTE**: Again, it can be useful to re-export these generated traits to simplify usage (in `lib.rs`):
>
> ```rust,ignore
> pub use crate::msg::{ExecuteMsgFns as CounterExecuteMsgFns, QueryMsgFns as CounterQueryMsgFns};
> ```

#### Using the integration

Now that all the setup is done, you can use your contract in tests, integration-tests or scripts.

Start by importing your crate, in your `[dev-dependencies]` for instance:

```toml
counter-contract = { path = "../counter-contract"}
```

You can now use:

```rust
use counter_contract::{
    msg::InstantiateMsg, CounterContract, CounterExecuteMsgFns, CounterQueryMsgFns,
};
use cw_orch::{anyhow, prelude::*};

// From https://github.com/CosmosContracts/juno/blob/32568dba828ff7783aea8cb5bb4b8b5832888255/docker/test-user.env#L2
const LOCAL_MNEMONIC: &str = "clip hire initial neck maid actor venue client foam budget lock catalog sweet steak waste crater broccoli pipe steak sister coyote moment obvious choose";
pub fn main() -> anyhow::Result<()> {
    std::env::set_var("LOCAL_MNEMONIC", LOCAL_MNEMONIC);
    dotenv::dotenv().ok(); // Used to load the `.env` file if any
    pretty_env_logger::init(); // Used to log contract and chain interactions

    let network = networks::LOCAL_JUNO;
    let chain = DaemonBuilder::new(network).build()?;

    let counter = CounterContract::new(chain);

    counter.upload()?;
    counter.instantiate(&InstantiateMsg { count: 0 }, None, &[])?;

    counter.increment()?;

    let count = counter.get_count()?;
    assert_eq!(count.count, 1);

    Ok(())
}
```

### Integration in a workspace

In this paragraph, we will use the `cw-plus` repository as an example. You can review:

* [The full integration code](https://github.com/AbstractSDK/cw-plus) with `cw-orch` added
* [The complete diff](https://github.com/cosmwasm/cw-plus/compare/main...abstractsdk:main) that shows you all integration spots (if you want to go fast)

#### Handling dependencies

When using workspaces, you need to add `cw-orch` as a dependency on all crates that include `ExecuteMsg` and `QueryMsg` used in your contracts. You then add the `#[derive(ExecuteFns)]` and `#[derive(QueryFns)]` macros to those messages.

Refer above to Adding `cw-orch` to your `Cargo.toml` file for more details on how to do that.

For instance, for the `cw20_base` contract, you need to execute those 2 steps on the `cw20-base` contract (where the `QueryMsg` are defined) as well as on the `cw20` package (where the `ExecuteMsg` are defined).

#### Creating an interface crate

When using workspace, we advise you to create a new crate inside your workspace for defining your contract's interfaces. In order to do that, use:

```shell
cargo new interface --lib
cargo add cw-orch --package interface 
```

Add the interface package to your workspace `Cargo.toml` file

```toml
[workspace]
members = ["packages/*", "contracts/*", "interface"]
```

Inside this `interface` crate, we advise to integrate all your contracts 1 by 1 in separate files. Here is the structure of the `cw-plus` integration for reference:

```path
interface (interface collection)
├── Cargo.toml
└── src
    ├── cw1_subkeys.rs
    ├── cw1_whitelist.rs
    ├── cw20_base.rs
    ├── cw20_ics20.rs
    └── ..
```

When importing your crates to get the messages types, you can use the following command in the interface folder.

```shell
cargo add cw20-base --path ../contracts/cw20-base/
cargo add cw20 --path ../packages/cw20
```

#### Integrating single contracts

Now that you workspace is setup, you can integrate with single contracts using the above section

### More examples and scripts

You can find more example interactions on the `counter-contract` example directly in the `cw-orchestrator` repo:

* Some examples [showcase interacting with live chains](https://github.com/AbstractSDK/cw-orchestrator/blob/main/contracts/counter/examples/deploy.rs).
* Some other examples show [how to use the library for testing your contracts](https://github.com/AbstractSDK/cw-orchestrator/tree/main/contracts/counter/tests).

> **FINAL ADVICE**: Learn more and explore our [full `cw-orch`documentation](https://orchestrator.abstract.money/contracts/interfaces.html#entry-point-function-generation).


# Sinfonia

[**Sinfonia**](https://app.sinfonia.zone/) is a cutting-edge dApp (Decentralised Application) that enables users to create and manage music [**FanTokens**](broken://pages/CjnJZbdzCtVn8HA97pJZ) and [**NFT**](broken://pages/LfPzVOw4xa3UeZZw1uAx)s on the [**BitSong**](https://bitsong.io/) and Osmosis Blockchains. With its user-friendly platform, Sinfonia is revolutionizing the music industry by bridging the gap between **Web2** and **Web3** technologies, empowering artists and music industry players with a range of innovative tools to enhance their projects.\
\
[**Read Full Documentation of Sinfonia!**](https://docs.sinfonia.zone/)


# BitSong Studio

The Web3 Music Hub

<figure><img src="/files/ZvzmVJ50ReKrD1nhQQN6" alt=""><figcaption><p>BitSong Studio</p></figcaption></figure>

## [Visit BitSong Studio](https://bitsong.studio) ->


# Bitsong Accounts

Accounts, owned by, account owners

***

### Introduction

In their primitives, accounts are a unique on-chain identity, controlled by a pair of keys, one secret & one public. Public keys are safe to share to the public, **however private keys are not**, as they are used used to ***sign*** arbitrary data, in such a manner that **generates a value mathematically provable** **to have been created by the private key**. This ***signature*** occurs without revealing the private key itself, and is the basic principle that the foundation of cryptography is built upon.

## Types Of Accounts

Below are a few types of accounts keys can currently control on Bitsong:

### A. Base Account

This is a default account on Bitsong, controlled by a single key-pair. These accounts can perform any action possible on Bitsong by broadcasting a prepared message with a signature hash of the message, generated by the private key.

The following cryptographic key algorithms are supported by default, and can be generated using any library, not just Bitsong's:

| Key Algorithm                                                                                     | Common use                                                |
| ------------------------------------------------------------------------------------------------- | --------------------------------------------------------- |
| [**Secp256k1**](https://en.bitcoin.it/wiki/Secp256k1)                                             | Bitcoin, Ethereum, Cosmos                                 |
| [**Ed25519**](https://github.com/allinbits/cosmos-sdk/blob/master/crypto/keys/ed25519/ed25519.go) | Cosmos Validator Consensus Keys, Solana, Cardano, Stellar |

*More native key algorithm support coming soon. Our CosmWasm module supports creating contracts with various key-algorithm verification libraries, which are very useful for quick programmability for additional algorithm support.*

### B. Multi-Signature / DAO's

These accounts are almost identical to Base Accounts, however their differences exist in how actions are authorized by the account. Unlike base accounts, where only a signature generated from the single key-pair is required to authorize actions, Multi-signature accounts require `x of n` signatures in order for actions or messages to be performed by the account.

#### Membership based

DAO's and multi-signature accounts are programmable, meaning there are infinite ways to configure what keys are accepted, and how. For example, a DAO can have a **membership based configuration,** meaning a specific list of addresses are authorized to submit their signature. Another example is having a system where only **owners of a specific token** are able to submit their signature, creating a more fluid approach to who gets to decide on when actions are performed. These tokens can be fungible, or non-fungible, and can be programmed to further customize how actions are performed on behalf of a membership-based DAO.

### C. Interchain Accounts

Interchain account allows any account on Bitsong to generate and control an account, on any other chain interoperable with the Interchain Account feature. This unlocks access to applications specific to other sovereign blockchains, without the need for any intermediary or centralized transaction processor. To learn more about Interchain Accounts, checkout the [official documentation](https://ibc.cosmos.network/main/apps/interchain-accounts/overview.html).

### D. Other - Module Accounts

Keys cannot necessarily control these accounts, unless implemented however these type of account should not be left out to highlight. Module accounts are generated, owned and used by network application.  Module's accounts do not necessarily rely on a signature hash generated by a private key for the account, but is previously programmed for what transactions it is authorized on to perform, gated by customizable logic.&#x20;

An example is the [governance module ](/features-and-modules/governance)address, which is only able to authorize actions upon consensus determined through its voting workflow.

### Further Info

To learn more about accounts on Bitsong, you can reference the [accounts section in the interchain academy tutorials](https://tutorials.cosmos.network/academy/2-cosmos-concepts/2-accounts.html).

#### Up Next

With the primitives of accounts reviewed, let's go on to introduce [Grammos](/products/bitsong-accounts/grammos), a Telegram Bot for 1-click account creation and management.


# Grammos

### Introduction

The [Grammos app](https://t.me/grammos_bot/app) can be invited into any Telegram channel. Users can prompt Grammos to create a new account. When this occurs:

1. A new key pair is generated on the users device
2. The private key is then sharded into `n` pieces, and encrypted on the users device
3. These encrypted shards are then sent to `n` databases, where they are kept for retrieval when a user desires to sign a message with this new key

{% hint style="info" %}
This shared key storage technique is called [MPC](https://www.fireblocks.com/what-is-mpc/), or multi-party-compute.
{% endhint %}

### Things to consider

* **Possible collusion of storage providers:** An inherent risk with this MPC's, requires the trust assumption that the storage providers will not collude with each other to share the encrypted key shards with each other, making it possible to access the private key.

### Future Goals

* **Fully on-chain implementation:** Implementation where users can choose their validator set to participate in the MPC setup will provide a fully on chain distributed key sharding, compatible with platforms other than Telegram.

#### Up Next  Abstract Accounts on Bitsong&#x20;


# Abstract Accounts on Bitsong

Abstract getting messages from A to B.

*Bitsong Accounts are the Abstract Framework and is frequently being iterated, thanks to the* [***Abstract***](https://abstract.money/en-US) ***team efforts!***

### Problem

Over the past decade, our technological landscape has revealed keeping this private key secure is a tremendous limiting factor for the adoption of sovereign oriented solutions cryptography provides, where attack vectors such as wallet drainers and large scale phishing campaigns constantly lurk. Specifically, the nature of key pairs requires the owner of the key-pair to keep the secret key... well, secret.

### Solution Ideas

* A programmable ecosystem with libraries compatible with Bitsong and other cryptographic authentication libraries
* An environment of applications for users to interact with these tooling to improve the limitations and tradeoffs that come with sovereign key management

## &#x20;A2B - Abstract Accounts on Bitsong

These accounts are programmable, on chain wallets. These wallets hold funds that its owner has access to, the applications that can be installed into the account, and programmed in a way that unlocks creating a better UX for cross chain interacting with Bitsong.

### Ownership Methods

As an owner of a A2B (Abstract Account on Bitsong), one can configure the account by sending messages to the contracts. The owner of the account can be a wallet, multi-sig or any other ownership structure, allowing you to customize your ownership structure to fit your needs. An account has an initial owner upon its creation. Below are the various forms of ownership methods currently supported:

#### Monarchy

A single entity that has full control over the Account. This entity may be a wallet, DAO, or even a specific NFT token.

#### Multi-Signature

A multi-signature owned account is one that in order to approve an action to be performed by the account, requires a subset of signatures to approve the action. This subset is specific to the multi-signature structure that owns the account, such as a cw-3 multisig.

Here are a few terms you need to know about when configuring your multi-sig:

* **Voter weight** 🏋️‍♂️: The weight that the voter has when voting on a proposal.
* **Threshold** 📊: The minimal % of the total weight that needs to vote YES on a proposal for it to pass.

#### Sub-Accounts

A Sub account is an A2B that is owned by another A2B. This can be helpful to mitigate concerns of experimental apps accessing funds from the main account.

As a result of this structure, complex multi-account systems can easily be transferred between governance systems by simply changing the owner of the top-level account.

### Interchain Bitsong Accounts

An Interchain Bitsong Account (IBA) is an A2B that is owned by another A2B which is located on a different chain. The goal of IBA's is for any user making use of Bitsong to access the benefits of the IBC protocol, without sacrificing any functionality, in order to mitigate the limitation that arises from the low-level implementation of the IBC protocol.

To learn how to create your IBA, [click here.](/products/bitsong-accounts/abstract-accounts-on-bitsong/guides/create-an-iba)

### Account Modules, Adapters, and Services

A module is a smart-contract that can be installed on an A2B to extend the account’s capabilities. There are different forms of modules:

* **App**: Modules that add a functionality, exposing new entry-points for you or your users.
* **Adapter**: Modules that act as a standard interface between your Account and external services.
* **Standalone**: Modules that are not directly integrated with an A2B.
* **Service**: Reference to a smart-contract or module that is externally maintained.

You can delve deeper into the [module documentation here](/products/bitsong-accounts/abstract-accounts-on-bitsong/developers/iba/modules).

### Technical Implementation (Code Infrastructure)

#### [Abstract Name Service](https://github.com/AbstractSDK/abstract/tree/main/framework/contracts/native/ans-host)

**Purpose:** A name service that enables chain-agnostic action execution by storing commonly retrieved data such as assets, contracts, and IBC channels.

Further information on the Abstract Name Service can be [found here.](/products/bitsong-accounts/abstract-accounts-on-bitsong/infrastructure/name-service)

#### [Registry](https://github.com/AbstractSDK/abstract/tree/main/framework/contracts/native/registry)

**Purpose:** A registry for modules and accounts. It exposes namespace claiming, module registrations, and detailed querying of modules by namespace, name, and version.

Specifics regarding use of the registry contract is[ located here](#registry)

#### [Module Factory](https://github.com/AbstractSDK/abstract/tree/main/framework/contracts/native/module-factory)

**Purpose:** Facilitates installing modules on an Account.

Learn more about the Module Factory contract [here.](/products/bitsong-accounts/abstract-accounts-on-bitsong/infrastructure/modules#module-factory)

### Additional Services

#### Abstract SDK

Abstract-SDK is the rust libraries to interface directly with the A2B contract framework from other smart contracts. An Abstract specific library will be included in the development pipeline, so in the meantime feel free to reference the specific [rust crate library documentation](https://docs.rs/abstract-sdk/latest/abstract_sdk/).

#### Abstract.js

Abstract.Js is the Typescript library for developing front-end UI compatible with the Bitsong Account framework. A A2B specific library will be included in the development pipeline, so in the meantime feel free to reference the specific [js package documentation](https://js.abstract.money/).

#### [App Template](https://github.com/AbstractSDK/templates)

The App Module Template is a starting point for developing apps that enable features or transform A2B into standalone products. An A2B specific template will be included in the development pipeline, so in the meantime feel free to reference the [template located here](https://github.com/AbstractSDK/templates).

#### [Cw-Orchestrator](https://orchestrator.abstract.money/quick_start.html)

Cw-orchestrator is a comprehensive toolset designed to streamline the development, testing, and deployment of CosmWasm smart contracts. It provides a set of advanced features and macros that enable developers to create more efficient, scalable, and maintainable smart contracts. Think of it like a Swiss Army knife that makes it easier to write, test, and deploy smart contracts.

**Key Features**

**Automated testing:** Cw-orchestrator simplifies the testing process by providing a set of pre-built testing tools and frameworks. This enables developers to write more comprehensive tests, ensuring that their contracts behave as intended.\
\
**Deployment automation:** When cw-orchestration scripts are written, they are able to be used for deployment of both mock and production chain environments, making it easier to deploy smart contracts to the blockchain. This feature saves time and reduces the risk of human error during the deployment process.\
\
**Collaboration tools:** Cw-orchestrator enables developers to publish their libraries, making it easier for teams to collaborate on complex projects. This feature promotes code reuse, reduces duplication of effort, and facilitates knowledge sharing within the developer community.

To learn more about cw-orchestrator, checkout the [documentation here](https://orchestrator.abstract.money/).

***

### Sources

This documentation is a heavily modified, direct reference to the official [Abstract Account Documentation.](https://docs.abstract.money)


# developers

This next section is a technical reference guide to the Abstract Account implementation.&#x20;


# getting-started

Prepare your development environment with tools used during development.

## Setting up the environment

Before you get started, you will need to set up your development environment. This guide will walk you through the process of doing just that.

### Rust

To work with the SDK you will need a Rust toolchain installed on your machine. If you don’t have it installed, you can find installation instructions on the [official Rust website](https://www.rust-lang.org/tools/install).

### WASM

Additionally, you will need the WASM compile target installed to build WASM binaries. You will need `rustup`, which you got when installing Rust on the previous step. To install it the WASM compile target, run:

```sh
$ rustup target add wasm32-unknown-unknown
> installing wasm32-unknown-unknown
```

### Docker

[Docker](https://www.docker.com/) is used to create a containerized environment for facilitating reproducible builds. Specifically we’ll be using [Cosmwasm Optimizer](https://github.com/CosmWasm/optimizer).

### Git

You will also need `git` installed to clone our template repository. You can find instructions for installing `git` on your operative system [here](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git).

### Using the Template

Now we’ll get you set up with the [Bitsong Abstract App](https://github.com/AbstractSDK/templates) template which contains:

* A scaffold app module with:
  * A basic contract
  * `cw-orchestrator` interface and deployment script
* Integration tests
  * A set of just commands that will help you in your development.

### Contract file structure

The template contains a scaffold contract that you can use as a starting point for your own contract. The contract is located in the `src` directory and is structured as follows:

* `contract.rs`: Top-level file for your module. It contains the type definition of you module and the const builder that constructs your contract. It also contains a macro that exports your contract’s entry points. You can also specify the contract’s dependencies here.
* `error.rs`: Error types that your contract can return.
* `msg.rs`: Custom message types that your contract can receive. These messages also have `cw-orchestrator` macros attached to them which comes in useful when you are writing your integration tests.
* `state.rs`: State types that your contract will use to store state to the blockchain.
* `interface.rs`: Interface that your contract will use to interact with the `cw-orchestrator` library.
* `replies/`: Reply handlers that your contract will use to handle replies.
* `handlers/`: Message handlers that your contract will use to handle the different messages it can receive.

### Tools used in the template


# dependencies

Details on crate dependencies

## Dependencies

A dependency is a package of software that a developer relies on to implement his/her own application. By relying on this external code, the developer doesn’t need to implement the dependency’s functionality themselves, reusing an building with existing features.&#x20;

{% hint style="info" %}
These can be thought of as VST plugins for the audio engineers out there ;)
{% endhint %}

Bitsongs Abstract Accounts allows you to add other smart contracts as dependencies to your module. Doing so enables you to keep your app’s complexity low and focus on the core functionality of your module while leveraging the functionality of battle-tested code.

We’ll cover how to declare your dependencies and then how to ensure you have them installed them before you try to install your own module.

### Declaring Dependencies

Declaring a dependency is a two-step process:

1. **Specify the dependency**\
   First, you specify the dependency itself using the `StaticDependency` struct. The struct contains the ID for the module you wish to depend on, as well as an array of version requirements. The formatting and assertion of these requirements are identical to [Cargo’s version requirement functionality](https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html).

```rust
use bitsong_app::std::STORAGE;
use abstract_app::std::objects::dependency::StaticDependency;

const USB_DEP: StaticDependency = StaticDependency::new(STORAGE, &[">=0.6.9"]);
```

2. **Add dependency to module**\
   Once configured, you can add the dependency to your module using the `with_dependencies` method on the `App` struct. This method takes a slice of `StaticDependency` structs and asserts that all dependencies are met when the module is instantiated.

```rust
const APP: MIPFSApp = MIPFSApp::new(STORAGE, MODULE_VERSION, None)
// ...
.with_dependencies(&[USB_DEP]);
```

You can now safely start using the APIs that should be included in any of your dependencies.

### Dependency Installation

Before you can install your own module you must install all your module’s dependencies. To do this we provide a `DependencyCreation` trait that you should implement for your module. The goal of the trait is to enable you to configure which dependencies should be installed and with which parameters.

Here’s an example using the dollar-cost-average app that depends on CronCat and a DEX adapter.

```rust
const APP: PaymentApp = PaymentApp::new(APP_ID, APP_VERSION, None)
    .with_instantiate(handlers::instantiate_handler)
    .with_execute(handlers::execute_handler)
    .with_query(handlers::query_handler)
    .with_migrate(handlers::migrate_handler)
    // Specify dependencies
    .with_dependencies(&[DEX_DEPENDENCY]);
```

With these specified, our abstract-client crate can install all your modules and their dependencies when you install your app, like so:

```rust
    let accounti: Account<MockBech32> = client.account_builder().build()?;

    // Install an app
    let app: Application<MockBech32, MockAppI<MockBech32>> =
        accounti.install_app::<MockAppI<MockBech32>>(&MockInitMsg {}, &[])?;
```

The next section goes deeper into the `abstract-client` and how you can use it create accounts, publish modules and install your modules.

### Module Dependency Assertion


# client

## Abstract Client

As previously mentioned you can use the `abstract-client` package to interact with any instance of   Abstract, including Bitsong's implementation. For this example we’ll use the `Mock` environment for simplicity. However, the same functions can be used for any `CwEnv`.

{% hint style="info" %}
&#x20;You can read the [`abstract-client` documentation](https://docs.rs/abstract-client/latest/abstract_client/) for more information.&#x20;
{% endhint %}

#### Example

```rust
    // Create environment
    let env: MockBech32 = MockBech32::new("mock");
    let sender: Addr = env.sender_addr();

    // Build the client
    let client: AbstractClient<MockBech32> = AbstractClient::builder(env.clone()).build_mock()?;
```

These three lines:

1. Created a mock environment to deploy to.
2. Deployed `Abstract` to that environment and returned a client. You can then start using the client to do all sorts of things. For example, you can set and query balances easily.

```rust
    let coins = &[Coin::new(50u128, "btsg"), Coin::new(20u128, "btc")];

    // Set a balance
    client.set_balance(&sender, coins)?;

    // Add to an address's balance
    client.add_balance(&sender, &[Coin::new(50u128, "btsg")])?;

    // Query an address's balance
    let btsg_balance = client.query_balance(&sender, "btsg")?;

    assert_eq!(btsg_balance.u128(), btsg);
```

Then, you can use the client to create a `Publisher` to publish an App to the platform.

```rust
    // Create a publisher
    let publisher: Publisher<MockBech32> = client
        .account_builder()
        .namespace(Namespace::from_id(TEST_MODULE_ID)?)
        .build()?
        .publisher()?;

    // Publish an app
    publisher.publish_app::<MockAppI<MockBech32>>()?;
```

Now that the App is published anyone can create an `Account` and install it!

```rust
    let accounti: Account<MockBech32> = client.account_builder().build()?;

    // Install an app
    let app: Application<MockBech32, MockAppI<MockBech32>> =
        accounti.install_app::<MockAppI<MockBech32>>(&MockInitMsg {}, &[])?;
```

Et voila! You’ve just deployed `Abstract` and an App to a mock environment. You can now start testing your module.

The `Account` object also has some useful helper methods:

```rust
    // Get account info
    let account_info: AccountInfo = accounti.info()?;
    // Get the owner
    let owner: Addr = accounti.owner()?;
    // Add or set balance
    accounti.add_balance(&[Coin::new(100u128, "btsg")])?;
    // ...
```

You can explore more of its functions in the [type’s documentation](https://docs.rs/abstract-client/latest/abstract_client/struct.Account.html).


# sdk

## Account SDK

This rust crate account is an abstraction programming toolbox that allows you to easily control an Bitsong Abstract Accounts, as well as create your own APIs that can be used by other developers to interact with your unique application.  This is like a mixing setup with multiple effect racks, but for Abstract Accounts on Bitsong!

### APIs

Abstract API objects are Rust structs that expose some smart contract functionality. Such an API object can only be constructed if a contract implements the traits that are required for that API. Access to an API is automatically provided if the trait constraints for the API are met by the contract.

### How It Works

As you’re aware, `abstract-sdk` crate is a toolbox for developers to create composable smart contract APIs. It does this through a combination of supertraits and blanket implementations, two concepts that are native to the Rust language.

{% hint style="info" %}

**Supertraits** are Rust traits that have one or multiple trait bounds, while a **blanket implementation** is a Rust trait implementation that is automatically implemented for every object that meets that trait’s trait bounds. The Abstract SDK uses both to achieve its modular design.

For more information about traits, supertraits and blanket implementations, check out the Rust documentation:

* [Traits](https://doc.rust-lang.org/book/ch10-02-traits.html)
* [Supertraits](https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters)
* [Blanket Implementations](https://doc.rust-lang.org/book/ch10-02-traits.html#implementing-a-trait-on-a-type)
  {% endhint %}

### Usage

Add `abstract-sdk` to your `Cargo.toml` by running:

```sh
cargo add abstract-sdk
```

Then import the prelude in your contract. This will ensure that you have access to all the traits which should help your IDE with auto-completion.

```rs
use abstract_sdk::prelude::*;
```

### Creating Your Own API

### Appendix

#### Available API Objects

The following API objects are available in the Abstract SDK:

* [Bank](https://docs.rs/abstract-sdk/latest/abstract_sdk/struct.Bank.html)
* [Executor](https://docs.rs/abstract-sdk/latest/abstract_sdk/struct.Executor.html)
* [Apps](https://docs.rs/abstract-sdk/latest/abstract_sdk/struct.Apps.html)
* [Adapters](https://docs.rs/abstract-sdk/latest/abstract_sdk/struct.Adapters.html)
* [IbcClient](https://docs.rs/abstract-sdk/latest/abstract_sdk/struct.IbcClient.html)
* [ModuleRegistry](https://docs.rs/abstract-sdk/latest/abstract_sdk/struct.ModuleRegistry.html)
* [Modules](https://docs.rs/abstract-sdk/latest/abstract_sdk/struct.Modules.html)
* [AccountRegistry](https://docs.rs/abstract-sdk/latest/abstract_sdk/struct.AccountRegistry.html)


# iba

Accounts on chains, owned by accounts on another chain.

## Interchain Bitsong Accounts

### Setting Up An IBA

Users must install the `ibc-client` contract on their account to enable IBC. To do so they can call the `ExecuteMsg::InstallModules` endpoint with the `abstract:ibc-client` module ID.

#### (Optional) Create an account on the remote chain

After the initialization step, the account is ready to send messages across IBC. However, if you wish, you can customize the remote account metadata before sending any messages. The following message is executed on the `account` contract:

```rust
pub enum AccountExecuteMsg {
    ExecuteOnModule {
        module_id: "abstract:ibc-client",
        exec_msg: IbcClientExecuteMsg {
            Register {
                host_chain: "destination-chain",
                // Customizable parameters
                base_asset: None,
                namespace: None,
                install_modules: vec![],
            },
            ...,
        }
    }
    ...,
}
```

{% hint style="info" %}
&#x20;*Remember that this step is optional as accounts are created automatically when sending the first message across IBC.*
{% endhint %}

### Account ID structure

The remote Interchain IBA Account will have the same account sequence but will have a different trace. Let’s take an example. A account on Bitsong with account sequence 69 wants to create accounts on Osmosis and Stargaze.

* Their account ID on Bitsong is `local-69`.
* Their account ID on Osmosis is `bitsong-69`.
* Their account ID on Stargaze is `bitsong-69` as well!

Remote accounts can create other remote accounts, and their traces will be chained. For instance, the `bitsong-69` account on Osmosis can create an account on Stargaze which will have the ID `bitsong>osmosis-69`. This gives the ability to trace ICAAs back to their origin chain.

*For a even more complex example, a bitsong account that was created on Osmosis to Stargaze to Neutron to Juno, the account id on Juno would be*

*`osmosis>stargaze>neutron>-bitsong-69`.*

### Sending messages on remote accounts

With or without a pre-existing remote Account, Abstract Accounts are able to send messages on remote Accounts. The `account_msgs` will be executed in order on the remote account.

```rust
pub enum AccountExecuteMsg {
    ExecuteOnModule {
        module_id: "abstract:ibc-client",
        exec_msg: IbcClientExecuteMsg {
            RemoteAction{
                host_chain: "destination-chain",
                action: HostAction{
                    Dispatch{
                        account_msgs: Vec<AccountExecuteMsg { ... }>
                    },
                    ...,
                }
            },
            ...,
        }
    }
    ...,
}
```

Note that the two instances of the `AccountExecuteMsg` enum are the exact same type. This allows you to send multi-hop IBC messages. However, multi-hop transactions (of these kind) are not really something you would use often, unless you’re using another chain as a routing chain.

### Specification of Interchain Bitsong Accounts

It is recommended to review the technical specification for the Abstract Account framework [here](https://docs.abstract.money/ibc/account-ibc.html#specification-of-interchain-abstract-accounts). We will review the primary components in these documentation.

#### General mechanism

IBC capabilities for accounts are allowed by the `ibc-client<->ibc-host` pair. The `ibc-client` is responsible for authenticating the sender and sending packets across IBC to the `ibc-host`. The `ibc-host` is responsible for receiving packets and routing the packet to the corresponding contract on the remote chain. Under the hood, the `client-host` connection is handled by a [Polytone](https://github.com/DA0-DA0/polytone/wiki) channel. This allows IBA Accounts to be interoperable with other protocols, more resilient to IBC constraints.

You see that an IBA Interchain connection is uni-directional. You need 2 connections to be able to interact bi-directionnally with an account. Up until today however, only a local account can act on a distant account and not the other way around. Here is an examples using AccountId between bitsong and osmosis:

* `local-69` on bitsong CAN control `bitsong-69` on osmosis via IBC
* `bitsong-69` on osmosis CAN’T control `local-69` on bitsong

#### Account creation

IBA Accounts are traditional Bitsong Abstracts Accounts controlled by the `ibc-host`. The `ibc-host` is the admin of the account and routes any packet sent by a remote account on the corresponding local account. When creating an account, it is simply registered by the `ibc-host` using the account-factory just like any other account.

When an action is triggered by a remote account, the `ibc-host` does the following verifications:

* If an local account already exists on-chain for the remote account, it just dispatches the message to the account.
* If no account exists, it creates one with default metadata and THEN dispatches the messages to this new account.

The Account creation process is therefore not mandatory when interacting with IBA Accounts. This is why when you create an Bitsong Abstract Account, you automatically have an account on every connected chains!

#### Data Structures

Interchain Bitsong Account communication is done via a single message structure:

```rust
pub enum IbcHostExecuteMsg{
    /// Allows for remote execution from the Polytone implementation
    #[cw_orch(fn_name("ibc_execute"))]
    Execute {
        account_id: AccountId,
        /// The address of the calling account id. This is used purely for the send-all-back method.
        /// We include it in all messages none-the-less to simplify the users life
        account_address: String,
        action: HostAction,
    },
    ...,
}
```

* `account-id` is the id of the local account calling the action.
* `account_address` is the address of the local account calling the action.
* `action` is the action that should be executed by the ibc-host on the remote account:

```rust
/// Callable actions on a remote host
#[cosmwasm_schema::cw_serde]
pub enum HostAction {
    /// Dispatch messages to a remote Account.
    /// Will create a new Account if required.
    Dispatch {
        account_msgs: Vec<account::ExecuteMsg>,
    },
    /// Can't be called by an account directly. These are permissioned messages that only the IBC Client is allowed to call by itself.
    Internal(InternalAction),
    /// Some helpers that allow calling dispatch messages faster (for actions that are called regularly)
    Helpers(HelperAction),
}

#[cosmwasm_schema::cw_serde]
#[non_exhaustive]
pub enum InternalAction {
    /// Registers a new account from a remote chain
    Register {
        name: Option<String>,
        description: Option<String>,
        link: Option<String>,
        namespace: Option<String>,
        install_modules: Vec<ModuleInstallConfig>,
    },
}

#[cosmwasm_schema::cw_serde]
#[non_exhaustive]
pub enum HelperAction {
    SendAllBack,
}
```

### Acknowledgement and Callback

IBC works with 4 steps:

1. Sending a packet (Source chain)
2. Receiving a packet (Destination chain)
3. Sending an acknowledgement (Destination chain)
4. Receiving an acknowledgement (Source chain)

We have already covered the 2 first steps with the sections above. We cover the 2 lasts steps in this section.

Step 3 (sending an ack), is handled by Polytone. They catch any error that could happen during contract execution and send back an acknowledgement reflecting the state of the contract execution on the remote chain. This is handled through the [Callback](https://docs.rs/polytone/latest/polytone/callbacks/enum.Callback.html) struct.

For Step 4, Polytone allows for sending a message to the initial sender of the IBC interaction after the packet was successfully received in the remote chain. Abstract DOESN’T use this feature for user actions, so callbacks are not possible when using Interchain Abstract Accounts. If you are a module developer, check out the Module IBC section that allows for callbacks.

### Cross chain trace

Because accounts created across chains using the IBA protocol are controlled by an account located on a remote chain, the account that is calling the action needs to be related to the account on the remote chain. This is done through the [AccountId](https://docs.rs/abstract-std/latest/abstract_std/objects/account/struct.AccountId.html) struct. The IBC-host module leverages the `AccountId::trace` field of this struct. An account is either `AccountTrace::Local` or `AccountTrace::Remote`. When a `PacketMsg` is sent across an IBC channel, the account id is transformed on the receiving chain in the following manner:

* If it was `AccountTrace::Local` before transfer, it turns into an `AccountTrace::Remote` account with one chain in the associated vector being the chain calling the `PacketMsg` `(PacketMsg::client_chain)`
* If it was `AccountTrace::Remote` before transfer, it stays remote and the client\_chain field is pushed to the associated vector.

This allows full traceability of the account creations and calls.


# modules

Programmable contracts owned and verifiable by accounts, with full IBC support.

## Interchain Module Communication

Imagine an Bitsong Account module “X” on a chain. This module wants to send a message to another module “Y” on a remote chain. The module on the remote chain wants to ensure that the message was sent by module X.

In order to do so, the developer could attempt to send his message through the user’s Account using the Account IBC infrastructure. However, using this method it is impossible for module Y to verify that the content of the message was indeed sent by the origin module X. Executing actions through the Account is great for permissionless actions (like depositing assets into a protocol) but is unsuited for permissioned entry-points. So what now?

### Secure Interchain Module Communication

To allow modules to send messages securely to other modules across IBC, Interchain Module Communication is used. IMC allows developers to send messages from a module directly to another module on a different chain. The module that receives the IBC message can then access the source module details. This way IMC allows interoperable permissioned actions between all Abstract modules.

### Sending a message

In order to send a message, a module needs to interact with the `ibc-client` module. You can use the [`IbcClient API` ](https://docs.rs/abstract-sdk/latest/abstract_sdk/struct.IbcClient.html)to interact with the `ibc-client`. The example below shows how the ping-pong app sends a message to an instance of itself on another chain.

```rust
    // a. define the module to send the ibc msg
    let self_module_info = module.module_info()?;
    // b. access the ibc-client 
    let ibc_client: IbcClient<_> = module.ibc_client(deps.as_ref());
    // c. define the modules ibc action as a cosmos msg 
    let ibc_action: CosmosMsg = ibc_client.module_ibc_action(
        opponent_chain.clone(),
        self_module_info,
        // Start by playing a Ping
        &PingPongIbcMsg {
            hand: PingOrPong::Ping,
        },
        Some(Callback::new(&PingPongCallbackMsg::Pinged {
            opponent_chain,
        })?),
    )?;
```

* `opponent_chain` is the `TruncatedChainId` of the destination chain where the app is expected to be installed.
* `target_module` describes the module on which the message will be executed on the remote chain. In this case, it is another instance of the ping-pong app.
* `msg` is the message that will be executed on the remote module via a custom endpoint. We explain in the section about receiving a message how this message is used by the targeted module.
* `callback_info` is used to request a callback once the packet has been received and acknowledged. We explain more about this behavior in the acks and callbacks section

### Receiving a message

In order for a module to receive a message coming from a remote Module, it needs to implement the `module-ibc` endpoint. The function signature for this endpoint is:

```rust
pub fn module_ibc(
deps: DepsMut, 
env: Env, 
module: Module, 
source_module: ModuleIbcInfo, 
msg: Binary) -> Result<Response, Error>;
```

The `deps`, `env` and `module` variables are identical to the execute endpoint and should be clear to you by now. If not here are some links to more documentation:

* `deps` and `env` are described in the [`CosmWasm documentation`](https://docs.cosmwasm.com/)
* `module` (or `App` or `Adapter` usually) are described in the [Account SDK section](/products/bitsong-accounts/abstract-accounts-on-bitsong/developers/sdk) of the docs

The `msg` variable contains the msg constructed by the module on the source chain. In this case the `PingPongIbcMsg`.

The `source_module` variable contains information about the module that sent the message, as well as the source chain information. This information can be used to assert the source of a message, like so:

```rust
pub fn receive_module_ibc(
    deps: DepsMut,
    env: Env,
    module: App,
    source_module: ModuleIbcInfo,
    msg: Binary,
) -> AppResult<Response> {
    let this_module_info = module.module_info()?;
    ensure_eq!(
        source_module.module,
        this_module_info,
        AppError::NotPingPong {
            source_module: source_module.module.clone()
        }
    );
    let ping_msg: PingPongIbcMsg = from_json(msg)?;
}
```

For example, the above code will return an error if the source module doesn’t match the receiving module. This way only other ping-pong apps can call this ping-pong app!

### Callbacks

As mentioned callbacks can be added to the IBC flow progress or revert your contract’s state depending on the packets execution result.

#### Callback Execution

If a callback was requested when sending a module IBC message, the callback will be executed wether the execution was successful or not. A callback message will be executed on the ̀ibc\_callback endpoint of the calling module. The function signature for this endpoint is:

```rust
pub fn ibc_callback(deps: DepsMut, env: Env, module: Module, callback: Callback, result: IbcResult,) -> Result<Response, Error>;
```

The callback variable contains a `msg: Binary` that is the encoded callback message that was provided to the callback on construction. In the ping-pong case this was `PingPongCallbackMsg::Pinged`.

The `result` contains the result data from the IBC packet execution. You can match against this result to assert that the remote execution was successful and roll back state if it was not.


# testing

## Testing Your Module

### Integration Testing

Integration testing your contract with the account contracts involves deploying your contract and any of its dependencies to a mock bitsong environment, and any other environment where you want to test actions with. To make this as easy as possible, an `abstract-client` package is available that you can use to deploy on any of your modules to a mock environment. We will cover this client in the next section.

### Local Daemon Testing

Once you have confirmed that your module works as expected you can spin up a local node and deploy  A2B + your app onto the chain. You can do this by running the `local_daemon` example, which uses a locally running Bitsong daemon to deploy to. At this point you can also test your front-end with the contracts.

{% hint style="info" %}
Testing your application on a local daemon is difficult if it depends on other protocols, and those protocols don’t make use of `cw-orchestrator` as there is no easy way to deploy them to the local daemon, except manually.&#x20;
{% endhint %}

### Unit-testing

The lowest level of testing is unit testing. Unit tests allow you to easily test complex, self-contained logic. Because unit tests should be self-contained, any queries made to other contracts need to be mocked. These mocks act as “query catchers”, allowing you to specify a response for a specific query.

Sadly constructing these mock queries is time-consuming and involves a lot of boilerplate. Additionally, there are queries that your module should always support as they are part of its base implementation. For those reasons we created an `abstract-testing` package.

The `abstract-testing` provides you with some small abstractions that allow you to mock Smart and Raw queries with ease.

#### Mock Querier

The abstract-testing package contains a [MockQuerierBuilder](https://docs.rs/abstract-testing/latest/abstract_testing/struct.MockQuerierBuilder.html). It uses the common builder pattern to allow for efficient mock construction. Let’s see how!

**Mocking Raw Queries**

Instead of manually mapping the key-value relation and it’s types, we can use the available contract storage types. Using the storage types ensures that the mock and its data operations are the same as in the actual implementation. It also saves us a lot of work related to key serialization.

**Items and Maps**

The MockQuerierBuilder also provides a `with_items` and `with_maps` function. These functions allow you to easily mock `Item` and `Map` datastores.

This approach allow you to easily map `Item` and `Map` datastores.

```rust
let contract_address = api.addr_make("bitsong1...");
let querier = MockQuerierBuilder::default()
    .with_raw_handler(&contract_address, |key: &str| {
        // Example: Let's say, in the raw storage, the key "KEY" maps to the value "VALUE"
        match key {
            "KEY" => to_json_binary("VALUE").map_err(|e| e.to_string()),
            _ => to_json_binary("").map_err(|e| e.to_string()),
        }
    })
    .build();
```

**Abstract Querier**

The easiest and best way to start using the querier is to use the `AbstractMockQuerierBuilder::mocked_account_querier_builder()` method. This method sets up a mock querier with an initial Bitsong Abstract Account.

## IBC Application Testing

One of the hardest steps in building an interchain application is testing. Due to the complexity of IBC and Cosmos SDK chains there are some trade-offs to consider in your approach to testing.

### Testing Tools

This section aims to provide you with a high-level overview of the available testing tools and how to use them. That way you can make an informed decision on which tool is best for your application’s needs.

#### Mock IBC Testing

he easiest way to test your CosmWasm IBC application is by using [cw-orchestrator’s mock IBC environment](https://orchestrator.abstract.money/interchain/integrations/mock.html). This testing environment allows you to connect multiple `Mock` instances over a virtual IBC connection. Relaying is simulated and you can test your application’s IBC logic without needing to deploy it to a live chain.

**Type: `MockBech32Interchain`**

**Advantages:**

* Easy to set up and use.
* Very fast to execute.
* Easily configurable.

**Disadvantages:**

* Does not support custom Cosmos SDK modules.
* Not end-to-end.
* Can’t make use of existing on-chain infrastructure.

#### Starship

[Starship](https://docs.cosmology.zone/starship) is a kubernetes-based Cosmos SDK environment spawner. It allows you to spin up multiple Cosmos SDK blockchain networks and connect them together. It includes a relayer, faucet and block explorer. Allowing you to test your application in a more realistic environment.

**Type: `Starship`**

**Advantages:**

* Access to Cosmos SDK modules from your smart contract.
* End-to-end testing.
* Can be made available for front-end testing.

**Disadvantages:**

* Slow to execute.
* Requires more setup and knowledge to use.
* Can only run for limited time due to resource constraints.

#### Testnet

The final option is to deploy your application to a testnet. Doing this will ensure your application is tested in a real-world environment and makes it possible to start sharing what you’ve built with others. However, this approach is the most time-consuming and requires the most setup.

**Advantages:**

* Real-world testing.
* Can be shared with others.
* Can be used for marketing purposes.

**Disadvantages:**

* Slow to execute.
* Requires running your own relayer (or partnering with a relayer service).
* Testnets are often unstable.

## Testing Bitsong Apps

### Local & Mock Environments

For local and mock environments, the `AbstractInterchainClient::deploy_on` function exists. This function can take a `MockBech32Interchain` or `Starship` argument and it will deploy the Bitsong Abstract contracts to the environment and set up the necessary IBC connections.

```rust
let interchain = MockBech32InterchainEnv::new(
        vec![("bobnet-1", "bitsong"), ("uni-5", "juno")],
    );
let abstract_interchain = AbstractInterchainClient::deploy_on(&interchain);
// single-chain client
let bitsong_abstract: AbstractClient = abstract_interchain.client("bobnet-1");
```

### Testnet/Mainnet Environments

Abstract maintains deployments for a few testnets and for most mainnets, as well as Bitsong. Instead of re-deploying Bitsong Abstract to these networks you can make use of the `load_from` function on `AbstractInterchainClient`. To do this, first construct an `InterchainDaemon` object with the chains you’d like to use.

```rust
let interchain = DaemonInterchain::new(vec![
        (LOCAL_JUNO, None),
        (LOCAL_BITSONG, None)
    ], &ChannelCreationValidator)?;

let abstract_interchain = AbstractInterchainClient::load_from(&interchain);
// single-chain client
let bitsong_abstract: AbstractClient = abstract_interchain.client("bobnet-1");
```


# deployment

Deploying your modules to A2B

## Module Deployment

Deploying your module is an easy 3-step process: Module Uploading, Registration and Schema Linking. Let’s go over each step in detail.

### Module Uploading

Uploading your module involves first compiling your module as a WASM binary and then uploading it to the network(s) you want your module to be available on. This will yield you a code\_id that is a unique identifier for your module on the network.

#### Compiling your module

Once you have confirmed that your module works as expected you can spin up a local node and deploy Abstract + your app onto the chain. You need Docker installed for this step.

You can compile your module by running the following command:

```sh
$ just wasm
> Compiling to WASM...
```

{% hint style="info" %}
The WASM optimizer uses a docker container to compile your module. If you don’t have docker installed you can install it from [here](https://docs.docker.com/get-started/get-docker/).&#x20;
{% endhint %}

This should result in an `artifacts` directory being created in your project root. Inside you will find a `my_module.wasm` file that is your module’s binary.

#### Publish your module

Before attempting to publish your app you need to add your mnemonic to the `.env` file. Permissionless publishing of modules may only take place on testnet. Make sure this account has funds. If you don’t, the deployment will fail.

**Publish to testnet**

```sh
$ just publish bobnet-1
> Deploying module...
```

This will use the module’s `examples/publish.rs` script to deploy the module to the uni-1 network. The script will also attempt to register the module on the Abstract Registry, hence the mnemonic used in the script should be the same as the one you used to create the account and register the namespace.

**Publish to mainnet**

```sh
# todo: script to propose to register module on the Abstract Registry
```

The resulting code-id of your contract should now be in the `state.json` file created for you.

### JSON Schema Linking

To improve the user-experience for developers using your module we recommend linking your module’s JSON schema to the Bitsong Registry.

{% hint style="warning" %}
You need to install [github cli](https://cli.github.com/) for this step.

Follow [these install instructions](https://github.com/cli/cli#installation) as per your operating system needs.
{% endhint %}

To link your module’s schema you can run the following command:

```sh
$ just publish-schemas <namespace> <name> <version>
> Publishing schemas...
```

### Module Installation


# guides


# create-an-account

## How To Create A Bitsong Abstract Account Contract

## Bitsong Studio

## Abstract Account Console

## Bitsongd CLI&#x20;


# create-a-sub-account

Create an A2B that only permits another A2B ownership level access

### Requirements


# create-an-iba

create an account on another chain, owned by your Bitsong Account

## Creating An Interchain Bitsong Account

### Requirements


# install-a-module

## Installing Modules

### Requirements


# migrate ownership

## How to Migrate Account Ownership

### Requirements


# tokenized-account

## Creating A NFT Owned Account

### Things to Consider

* **Contract Level Admins**: The nature of CosmWasm NFTs generally consist of a single contract that contains the internal state of a collection of NFTs. If there is a contract-level admin to this contract, this may introduce a scenario where the admin of the collection may be authorized to perform actions for a specific token within the collection, such as transfer ownership of the token, or perform actions on behalf of the token owner. \
  \
  **This is a large attack surface area, and should be mitigated by keeping conscious of which collections are used, and what specific ownership features are possible.** [**BS721-Accounts**](https://github.com/permissionlessweb/bs-accounts/tree/minimal-bs-accounts) **is a NFT collection set that is built specifically designed to mitigate this risk.**<br>
* **Potential Unwanted Authorizations**: Another common feature of CosmWasm NFT contracts is the ability to authorize any wallet to perform an action including a specific token within a collection. This is useful in specific scenarios, however exploitative in others.\
  \
  For example, an on-chain application that consist of a smart contract and Front End UI may include an authorization message to perform specific functions required. This may introduce unwanted risk of losing account ownership if the token bound as an owner of a Bitsong account is mistakenly authorized. **Be conscious about what messages you are authorizing with you accounts!**

### Requirements

The following is required to create a NFT-based Bitsong Abstract Smart-contract System:

* &#x20;A form of authentication
* A bs721-account collection-token


# infrastructure


# indexer

## Account Indexer

Thanks to both the DAO-DAO & Abstract teams, we have a [reference implementation](https://github.com/AbstractSDK/dao-dao-indexer/tree/adair/abstract) of an historical indexer for coverage of the entire Bitsong Account framework.

### Overview


# modules

## Account Modules

### Module Factory

The Module Factory is a contract that allows Account owners to install and manage Account Modules for their Bitsong Account.

### Module-IDs

Every module is uniquely identified by a module ID. This ID is a string that follows the following format:

```rust
<namespace>:<name>
```

The namespace is a string that resembles the publishing domain of a module developer, while the name is the name of the module itself. For example, the `bitsong:usb` module is an App module developed by Bitsong where `bitsong` is the namespace and `usb` is the name of the module.

Additionally each module has a SEMVER version number that can be used to uniquely identify a specific version of a module, or just get the latest version. Module IDs and their versions are used to install modules on an Bitsong Account.

### Apps

An App module adds or alters the functionality of an Bitsong Account, exposing new functions to you and/or your users.

**Each App module instance is exclusive to a single Bitsong Account, meaning the instance is created and owned by the Account.** This level of control extends to the management of upgrades, maintenance, and any customization that might be required for the specific use case of the application.

Because each Account has its own instance of an App, App modules can be tightly integrated with the Account’s existing infrastructure. This includes the ability to interact directly with other modules (including Apps) installed on the same account, enabling powerful synergies and cross-module functionality.

#### Adapters

Adapters serve as standard interfaces that facilitate communication between your Bitsong Account and various external services.

#### Standalone

A Standalone module is any contract that is not directly integrated with Bitsong Accounts. These contracts don’t have to conform to the expected APIs of other module types.

#### Service

A Service module is not a module type per se, but rather a way to categorize a smart-contract that provide a service to the Bitsong Account ecosystem.


# name-service

## Abstract Name Services

The Abstract Name Service is an on-chain data store of the most important address space related data of the blockchain it is deployed on.

The ANS is a smart contract that stores the following data:

* **Assets**: The most relevant assets on the local blockchain.
* **Contracts**: Contracts related to certain protocols or applications that could be dynamically resolved. ***This could be used to store the address for an asset-pair for a DEX.*** \
  *For example, `bitsong/akt,btsg` could be resolved to the address of a bitsong pool that allows you to swap bitsong for akash.*
* **Channels**: IBC channel data to map a protocol + destination chain to a channel id. This allows for dynamic IBC transfers without having to know the channel id beforehand.

### Resolving Entries

The information provided by the ANS is great to have. However, directly calling CosmWasm smart queries on the ANS contract can make your code messy and significantly raise gas usage. For this reason, we offer three methods to efficiently and dependably execute low-gas queries on the ANS contract.

There are three ways to resolve your entry into its matching value.

#### `AbstractNameService Trait (Recommended)`

Both App and Adapter objects implement the AbstractNameService trait which allows you to resolve entries.

```rs
let btsg_name = AssetEntry::new("btsg");
let btsg_asset_info = my_app.name_service(deps).query(&btsg_name)?;
```

#### `Resolve Trait`

Entries that are resolvable by the Abstract Name Service implement the `Resolve` trait which gives them the ability to be resolved by ANS explicitly.

```rs
let ans_host = my_app.ans_host(deps)?;
let btsg_name = AssetEntry::new("btsg");
let btsg_asset_info = btsg_name.resolve(&deps.querier, &ans_host)?;
```

#### `AnsHost Object`

You can also load or create an `AnsHost` struct. This struct is a simple wrapper around an Addr and implements methods that perform raw queries on the wrapped address.

```rs
let ans_host = AnsHost {address: "btsg1...."};
let btsg_name = AssetEntry::new("btsg");
let btsg_asset_info = ans_host.query_asset(deps, &btsg_name)?;
```


# registry

## Registry

The Registry contract acts as the registry for all modules and accounts within the A2B platform. Bitsong Accounts can use it to claim namespaces and register their modules. The Registry contract allows modules to be queried by its namespace, name, and version, returning its reference which may be a code id or address.

### Namespaces

An account’s namespace is a unique identifier that is used to provide a publishing domain for modules and a human readable name for any Bitsong Account. Namespaces are claimed by an account and can be used to publish modules. Namespaces are unique and can only be claimed once. An account can only claim one namespace.

### Propose Modules

Developers that wish to publish modules to the Bitsong Account platform need to call ProposeModules on the Registry contract. The modules will subsequently be reviewed by the A2B platform for registration.

**Modules cannot be registered without their namespaces being claimed by an Account. This is to prevent malicious actors from registering modules under trusted namespaces.**

{% hint style="info" %}
&#x20;For mainnet deployment proposed modules are reviewed by the Bitsong Governance. To get them approved, reach out to us on Discord. For testnet deployment there is no review process.
{% endhint %}


# interchain

Interchain Bitsong Account

## Interchain Bitsong Accounts

### Overview

Interchain Bitsong Accounts (IBA) are built with use of making of [The Interchain Thesis](https://tutorials.cosmos.network/academy/1-what-is-cosmos/), which includes the [Application Specific Network Thesis](https://maven11.substack.com/p/the-application-specific-chain-thesis).

Bitsong Abstract Account provides multiple IBC capabilities to every module. Within the framework, there are two ways to interact with other blockchains through IBC:

1. InteA2Br=ch. a. i. tsong Account IBC interaction
2. Interchain Bitsong AccounA2Bt Module IBC interaction

We start by giving an overview of these two mechanisms before diving in further on how you should use them as a developer and finally dive into the specific mechanism that makes them work.

### Interchain Applications

Imagine you're a logistics manager, tasked with shipping products to customers across different countries, each with its own unique customs regulations, tax laws, and delivery requirements. You'd want to design a single, unified shipping system that can adapt to each country's specific needs, without having to recreate the system from scratch for every new market.

In the context of blockchain, a similar challenge arises when building applications that need to operate across multiple blockchains, each with its own distinct characteristics, rules, and requirements. This is where the concept of an **interchain application** comes in.

**An interchain application is a decentralized application that can operate seamlessly across multiple blockchains, using Inter-Blockchain Communication (IBC) to enable communication and interaction between different chains.** Just like the shipping system, an interchain application can be designed to adapt to the unique requirements of each blockchain, without having to rebuild the application from scratch for every new chain.

The benefits of an interchain application include:

* **Interoperability:** The ability to operate across multiple blockchains, enabling seamless interaction between different chains.
* **Flexibility:** The ability to handle chain-specific logic through dependencies, making it easier to adapt to changing requirements.
* **Scalability:**

***

### Account IBC interaction

IBA Accounts are able to send messages to other blockchains to execute actions. This allows any A2B to create accounts on remote chains. This way, users create 1 account on their home chain and are able to execute any action on any IBC-connected chain. This kind of interaction can be likened to Cosmos’s Interchain Account (ICA) functionality. Use cases include:

* Executing actions on remote chains without having to care about the remote gas coin
* Cross-chain DCA strategies
* Cross-chain email …
* Whatever permission-less application you can think of

Limitations:

* This capability doesn’t allow modules to interact with one-another in a permissioned manner. Because all messages are sent via the account directly they could be modified by the user. - This means that the receiving module, on the other chain, can’t be sure about the source of the message.
* Account execution doesn’t allow for IBC callbacks. This means that the result of IBC message execution sent via this route can’t be used to trigger following actions directly.

Learn more about Account IBC interactions

### Module IBC interaction

Module IBC allows modules to send messages directly to any other module present on a remote chains, mitigating limitations present with Account IBC interaction. This allows permissioned execution because the receiving module can verify and trust the origin of IBC packet. Uses cases include:

* Distributed Interchain Name Service
* Cross-chain NFTs
* Cross-chain payments without cross-chain tokens
* Every IBC application can be built using Abstract !

After a message is successfully executed via IBC, callbacks can be executed on the sender module to execute code depending on the result of the original message. You can think of this mechanism as an asynchronous version of the [`reply`](https://docs.cosmwasm.com/docs/smart-contracts/message/submessage/#handling-a-reply) mechanism over IBC.

Learn more about Account IBC interactions

IBC is a key feature of this framework and, as the ecosystem grows, the capabilities continue to improve and expand.


# DAO DAO

DAO DAO is the premiere interchain application for creating & participating in DAO's.

## DAO DAO: <https://daodao.zone/bitsong>

### Introduction

DAODAO introduced native support for Bitsong during Q2 2024, following [governance approval ](https://www.mintscan.io/bitsong/proposals/36)of funding the deployment & support!&#x20;

### How DAOs Work

DAO's can be created by defining its initial configurations, and then instantiating the set of smart contracts deployed on Bitsong. This can be done through the [DAO DAO UI](https://daodao.zone/dao/create?chain=bitsong-2b), or even through other custom methods of calling Bitsong. These set of contracts source code is [open source and verifiable](https://github.com/DA0-DA0/dao-contracts/releases), bringing certainty that DAOs on Bitsong perform as the official source code public.

Because DAO DAO DAOs operate by smart contracts on a blockchain, they are transparent by default. This means that votes, the voting power of members, and actions a DAO takes are all publicly auditable. This can help provide trust that DAO members are being good stewards of their communities.

With a DAO created, participants can choose how to collaborate, iterate and curate their DAO and on-chain actions. Each DAO has a treasury and is essentially a shared wallet between its members, where actions performed by this wallet requires a level of agreement between its users.

### Types of DAOs

#### [Membership Based](https://docs.daodao.zone/introduction/whats-a-dao#members-multisig-replacement)

Each account has a membership and voting power.

#### [Fungible Token Based](https://docs.daodao.zone/introduction/whats-a-dao#tokens)

Each account has a membership and voting power based on stake of a specific token. [This include Bitsongs Fantoken modules.](/features-and-modules/fan-tokens)

#### [Non-Fungible Token Based](https://docs.daodao.zone/introduction/whats-a-dao#nfts)

Each account has a membership and voting power based on stake of a specific NFT collection.

### Advanced Voting Configurations

DAOs are completely programmable, meaning that members can customize and even extend its DAOs configuration, allowing for the DAO to form to what the DAO members need.

#### [SubDAOs & SubDAO Admins](https://docs.daodao.zone/dao-management/subdaos/what)

SubDAOs are DAOs with other DAOs set with admin level permissions.

#### [Vetoable DAO](https://docs.daodao.zone/dao-governance/manage-vetoable-daos)

Vetoable DAOs can have proposals veto'd by an external source. &#x20;

### [IBC & DAO's](https://docs.daodao.zone/dao-management/dao-treasury/how-to-manage-cross-chain-tokens)

DAOs can have accounts on any chain, thanks to [Polytone](https://github.com/DA0-DA0/polytone).

### Additional Features

#### [Application Widget](https://daodao.zone/dao/juno10h0hc64jv006rr8qy0zhlu4jsxct8qwa0vtaleayh0ujz0zynf2s2r7v8q/apps?url=https%3A%2F%2Fdaodao.zone)

A Browser-in-browser experience to form msgs to propose for the DAO to perform.

#### Rewards & Revenue Mechanisms

[Vesting](https://github.com/DA0-DA0/dao-contracts/tree/development/contracts/external/cw-vesting), [reward distribution](https://github.com/DA0-DA0/dao-contracts/tree/development/contracts/distribution/dao-rewards-distributor#readme), and retroactive compensation are all features available for DAOs using DAODAO.

### Notifications

[Telegram Bot ](https://github.com/DA0-DA0/telegram-notifier-cf-worker) Get notifications about DAO proposal via Telegram&#x20;

[Discord Bot:](https://github.com/DA0-DA0/discord-notifier-cf-worker) Get notifications about DAO proposals via Discord Bot

### Join The DAO-DAO Community

* [Discord](https://discord.gg/MZdzZvKubt)
* [Twitter](https://x.com/Da0_Da0)

***

### Sources

* [DAO-DAO docs](https://docs.daodao.zone)
* [DAO Contracts](https://github.com/Da0-Da0/dao-contracts)


# Wallet


# How to Create a BitSong wallet

This is a guide on how to create a new BitSong wallet for users who don't have one yet.

We are using as example Keplr but in the "[**Wallets**](/btsg/wallets)" section you have other valid options as well.

1. Make sure you have installed the **Keplr** browser extension. If you don't already have it, then you can download the extension and install it from [**here**](https://chrome.google.com/webstore/detail/keplr/dmkamcknogkgcdfhhbddcghachkejeap?hl=en)**.**

![](/files/SLQFj9OT9dza3d8nkLJJ)

**2**. Once you have your Keplr extension installed, open it. In the new window that opens, select "*Create a new wallet*."

![](/files/qmtoA699Fjt4dajm6SLi)

**3**. This is probably the most important step! Select the type of Mnemonic Key you want for your wallet (12 or 24 words). Then make sure you *save it and keep it safe* since it is the only way to import or recover your wallet in case of need.&#x20;

**Remember: NO MNEMONIC PHRASE, NO MONEY**!

So name your wallet, set a password, and proceed.

![](/files/n1hyRqacYD3Mb0ZmfGBI)

**4**. You have now your brand-new Cosmos Wallet ready to use!

![](/files/JYCkSTdrTuqkBXVp0ndR)

**5**. Now let's get your new BitSong Wallet address. Go to <https://wallet.bitsong.io/> and among the options in the first window, select "*Keplr Browser Extension,*" per the image below.&#x20;

![](/files/LgPp8CGs72BoVjoOfBhh)

**6**. Wallet.bitsong will then execute Keplr and will ask you to **add and connect the bitsong-2b** chain. You must approve both actions by signing them with Keplr.

![](/files/C6XTRbJbnQPfYu5HYdnT)

**7**. Congratulations, you just created your new BitSong Wallet! You can see the new wallet address on lower left.

![](/files/1FzUVXLcDdaSr8GOzuea)

**8**. Open the Keplr extension and from the list of available chains, scroll down until you find "***BitSong Mainnet***" and select it.

![](/files/AuQ0IalfSyuRB0OCGYz8)

**9**. Make sure that the BitSong wallet address shown in Keplr is the same as the one shown in wallet.bitsong.io.

![](/files/K6H2idXMKGNPIBspZiul)

Your are now all set! Your BitSong wallet is ready to interact with the BitSong Blockchain.

Governance operations must be performed within the <https://wallet.bitsong.io> interface and signed with Keplr.


# How to Import Your BitSong Wallet

This is a quick guide on how to import a BitSong wallet for users who have set up a wallet on the previous version of the BitSong mainnet.

We are using as example Keplr but in the "[**Wallets**](/btsg/wallets)" section you have other valid options as well.\
\
**1.** Make sure you have installed the **Keplr** browser extension. If you don't already have it, then you can download the extension and install it from [**here**](https://chrome.google.com/webstore/detail/keplr/dmkamcknogkgcdfhhbddcghachkejeap?hl=en)**.**

![](/files/SLQFj9OT9dza3d8nkLJJ)

**2.** Once you have your Keplr extension installed, open it. In the new window that opens, select "*Import existing account*."

![](/files/AZzyWZKpN1mLxy9dVdbd)

**3.** This is probably the most important step! Insert your BitSong mainnet Mnemonic Key. Then you can name your wallet, set a password, and proceed.&#x20;

![](/files/JVP4IW6djzmmMNDaUJH6)

**4.** You have now your Cosmos Wallet ready to use!

![](/files/tfxzEdZ5EYOKOzWO8Njo)

**5.** Go to <https://wallet.bitsong.io/> and among the options in the first window, select "*Keplr Browser Extension,*" per the image below.&#x20;

![](/files/LgPp8CGs72BoVjoOfBhh)

**6.** Wallet.bitsong will then execute Keplr and will prompt you to **add and connect the bitsong-2b** chain. You must approve both actions by signing them with Keplr.

![](/files/C6XTRbJbnQPfYu5HYdnT)

**7**. Open the Keplr extension. and from the list of available chains, scroll down until you find "***BitSong Mainnet***" and select it.

![](/files/AuQ0IalfSyuRB0OCGYz8)

**8.** Congratulations, you have just imported your BitSong Wallet! You can see the wallet address on lower left of the page.

![](/files/1FzUVXLcDdaSr8GOzuea)

**9.** Make sure that the BitSong wallet address shown in Keplr is the same as the one shown wallet.bitsong.io.

![](/files/K6H2idXMKGNPIBspZiul)


# Staking


# How to Stake $BTSG

This is a simple Guide to Stake your $BTSG using the BitSong Wallet

1. Go to your BitSong Wallet at [*wallet.bitsong.io*](https://wallet.bitsong.io/) and Log in.&#x20;

![](/files/SQp77Qe6A5AuAbulTIwT)

2\. On your wallet Click on "**Validators**", in the left Menù.<br>

![](/files/lltlMmuUhfxw2JKuG3cC)

3\. Choose the Validator you prefer and click on "**Stake"**.\ <br>

![](/files/LI1h8U9uMifwffhb7yg5)

4\. Select the amount you want to Stake and click on "**Send**".\ <br>

![](/files/R3X8jJokiOBXbMUuFOGy)

5\. Confirm your transaction on Keplr. \ <br>

![](/files/itbWq9SjTUR5fwq5oMK9)

You have correctly Stake your *$BTSG.*\ <br>

![](/files/gwjFRtWaNYEkXSOfHg7C)


# Sinfonia


# Sinfonia User's Guide

BitSong is thrilled to formally announce the launch of our Fan Token Platform “Sinfonia”, along with an exquisite new web page and a sneak peek of the features and user interface!

In this guide you will find Sifonia’s main features and how to use them:

Go to the website and log in with your wallet, if you don't have a wallet, see [our guide](/useful-guides/wallet/how-to-create-a-bitsong-wallet).

![](https://lh5.googleusercontent.com/nnT5p3HHWQeAvEGAnWA3U20fANmSfIExLt9JzYb06C8-41aSYTync0kvpBhSnCpvGgpXhi_KXQuZj3eyzf6YHJH2Up4ymg0772-JRr5XHu6M9REupycxb6M2NFevvo5Kqn1-FHQ5)

On the **Dex** page you will see the fan tokens present on Sinfonia, the price and the market cap.

![](https://lh6.googleusercontent.com/RnXyA0FlacXPN4ih4SGVXkdPbR-B1ibXGC0mB_cs0a1Eg9xhjxkyblIhNVXErJjIeppa25qKTIJTSNxz9-E_zLv8xmJRLH972KPgUF8EKwyTeYGDfh3geCwMf7zz-8TW05saq13p)

To have an overview of your assets, make transactions and start using Sinfonia, go to the **Assets Page**.

![](https://lh3.googleusercontent.com/vm2xqNqZTjiAlFk0AbTo_oo0Dd045amEGkxlhsTId4DSkAOCGJZzo08TmqfhAN8b80fyWqX7i20IYzVFLCtjkhm8dF2Zxx9p66xC5kGVctar8TCqyCaeUDTrRXDhour_U46oxYDr)

To start using Sinfonia *you will need to transfer your tokens from the BitSong chain to the Osmosis chain.* To do so, open the menu as shown in the image.

![](https://lh4.googleusercontent.com/U7I-yUXnkqtLZQRngCLPhFVPqQAO9WVgFqcr6ncbw3V7w7bRytHgy3Cm_ozVOd5fK86CKSyuZYsjBVbb7oqqZc3Wpy-v0R7teq5cjzHPfUwHeqZy41wDY7T0DqhM1CQxVfc9hV9z)

Now click on the two arrows as shown in the image.

![](https://lh5.googleusercontent.com/oajA2nSbGnRdTgMxrbv2hCt4C3bcTByYvPJa-7TYUGH4J-Qq2fBLr0U1TUO0Q914hTRGO6HMJDspRYieiBwFAE5cm-Mte0r_CavsTeb48LwJQVTrlNWDc0Eg8mYbSXlwco4zraDI)

Now you can transfer your assets from the BitSong Chain to the Osmosis Chain.

![](https://lh3.googleusercontent.com/iuXnGd629xlN8gHbYDEAyM36rUaN3s1MIf2JTUvHQ9U0LrzKvHWIV6jwbByfNV3TZRMGOiUhFrVWuNTrHB0VcPzfOHGByiiGZwL1mQJqrf60f-GSkbqzXoInD5F7w1vTnPD4ah8R)

Insert the amount you want to import and click on Transfer. The amount you have transferred is now available on Sinfonia.

On the **Pools Page** you can view the Pools enabled on Sinfonia.

![](https://lh5.googleusercontent.com/l9HFysrrpQ8s4MNzwn9Oz4AMrq5mneNne7aP5578nXNLYAzzSLrpz725028Fz7cugWLp-PvqmMKfesjSzVp3xreemmeivwvS7yXxCs2yqXuXghbFtzkrjP_1hiISgt236ckRPAw4)

Click on the **Pool** you prefer to view the details.

![](https://lh3.googleusercontent.com/UYxir6c5iz_MyersbtnCAu4SrQ5v9lwN4Oj7NDJ4oiEixXmTy6hc7Ni1YULMAH1Er3htneEWWTDB7YtXJQjua2_VLiNstu0xwQgh3ZnFXwRZfVGFopAQFMDvWQMRxmjFy76XBNWZ)

On the Sinfonia Pools, like on the Osmosis Pools, you can Provide Liquidity and earn Rewards.&#x20;

On this page you can see:&#x20;

* The Pool composition;&#x20;
* The Liquidity on the the Pool;
* The Bonded tokens;
* APRs and unbonding time;
* Add/Remove Liquidity to the Pool.

On the **Swap Page** you can swap your token. The process is simple: just enter the amount you want to exchange and click on Swap.

![](https://lh3.googleusercontent.com/xWyPTdDE0Dm0zHylt_aeYIbef86cyBOhBneKczjPSVJMzDDW-qFDZvN6cFf7q2FOCuYHBR_w46Z5Y1qXUb98uNxEAarhNxoyHtwsdAsHDicW0eqX21YDoWCZq0GV4qhpXr7TPh7c)

To **provide Liquidity** on the Pool click on *Add/Remove Liquidity*

![](https://lh3.googleusercontent.com/4OHFuj8mHfZgoVOpMB1XT-qhQWa4zMInfbeIIgETEyji7cX_domczW9Lm5pD-PoJuxGpsl9gg068VGGoCm_TieWJC7Bf66nYB-UiOYbzX35cpAyAR9ZubzseGtacbObGS0VUd49a)

Select the amount of tokens you want to Provide to the Pool. Remember to match the entire amount of the liquidity you want to add.

![](https://lh4.googleusercontent.com/MAlBNSqsmonLwRnEU5q5cvDSEmU45EU17yUaQ2FpoGwRj3PYrixe5sC7oZJNMRb5Gu5MMBqoUxz-80CPd5Xs7lvgA3o7WWoSB7rFc7rwNlGqtizJXUP6PUZzeV-NrUkRtornHHtw)

Now click on **Add Liquidity** and confirm the transaction on Keplr. To start **Earning Liquidity**, now you have to Bond your LP tokens. On the voice “Available LP Tokens” now you can view the amount of tokens that you’ve decided to Add in the Pool

\
Click **on Start Earning**

![](https://lh4.googleusercontent.com/dfoJH_suvon0kj0n8FHV58kqYCD0AM-BbC4m2ci2kwGxmUS6vkhyRzxZ4jYCFOj_RTLcdvQWJsJ5uuuGm36BWja-vh6dpZp9uGeS7pedb7zNL6OBkc5F2ITxiJeIFkgKREmq7ynI)

Choose now the Unbonding Period. The more you keep the LP tokens in the pool, the higher the APRs will be.

Click on “**Max**” to Bond all your LP tokens and then Bond Tokens

![](https://lh4.googleusercontent.com/hju0g9AFtWrhFn_XjKURacYCk7ry0Qv0d3XdE9mIwXwhrKL9ROW_pPFLADg8FYBdNmnxclFdq93MWNXbXfyx3McFOj7JjadoNnc8puW6kJVcd6i2AoXp9h13ViMI3sSrAztyck0Z)

You have correctly bonded your Assets and you are earning daily rewards. To view the amount of the Liquidity you have provided in the Pool, click on the Pool and consult the index “*My Liquidity”*

![](https://lh3.googleusercontent.com/jjQIercQ4N_Y-CdZjZLVgo2qLH3HNw4qoKmQ5pXc11lq7S3JmDmoy9V1irI21nEv1io1D9UO4mr6wWqqQKFPvAVmCAif4ESzANWsoKUcwbvRqlmFrtfpBLyzXdxO4e16ZgOMvUvU)


# How to Add $BTSG Liquidity to Osmosis Pools

This is a quick guide for adding $BTSG liquidity to Osmosis Pools.

**1.** Go to [**https://osmosis.zone**](https://osmosis.zone)

![](/files/9bE3WeBtKYH9a4E7HZdA)

**2.** Click on "*Connect Wallet*" to connect your Keplr wallet to Osmosis.&#x20;

![](/files/bbY84zjmCGX2DQBxFnuG)

**3.** Enter your Keplr password and click to "*Unlock*"

![](/files/XflkEWpBkDWyowt5KLRt)

**4.** Click on "*Assets*" in the left navigation menu and find $BTSG on the list.  Now click on "*Deposit*" to transfer your $BTSG from your BitSong Wallet to **Osmosis**.

![](/files/a5mNtGHOuAdbqRyZ0kww)

**5.** Select the amount of $BTSG you want to deposit on **Osmosis** and click to "*Approve*" the transaction from **Keplr**. Now you can see your $BTSG balance on the "*Assets*" page.&#x20;

![](/files/ejpdbmuUOWVsjyP6x5ms)

**6.** Now it's time to select the pool to which you want to add liquidity. You can find **three** different BTSG pools: Pool #**574** $ATOM/$BTSG - Pool #**573** $BTSG/$OSMO and Pool #**592** $UST/$BTSG.&#x20;

**In this guide, we will add liquidity to Pool #573 $BTSG/$OSMO but the principles are the same for all Osmosis BTSG pools.**&#x20;

![](/files/TjZ8XcaOqL3bg41cnyzn)

**7.**  Click on "*Add / Remove Liquidity"*

![](/files/Aw0sWP4GqxL9dEO5xarP)

**8.** Now you have to pair the amount of tokens you want to add. In this case, we have chosen to add $OSMO and $BTSG. Choose the amount and "*Approve*" from Keplr.&#x20;

Now you have added liquidity to the pool!&#x20;

![](/files/P3Uqp7BmNc6gbB7gTnUq)

**9.**  If you want to bond your Liquidity Provider tokens (LP tokens) to earn rewards, click the *"Start Earning"* butto&#x6E;*.*

![](/files/dgbnlJIZSm4dW4RmWZ5X)

**10.** Choose the Unbonding period, click on "*Max"* to bond all of your LP tokens, and then click *"Bond."* You'll be prompted to confirm the transaction on Keplr.&#x20;

![](/files/ssCvmRme80hhD9vIkB3m)

That's it! You're now earning rewards for bonding your LP tokens.&#x20;


# How to Report a Bug on Sinfonia

1 - Go to <https://github.com/bitsongofficial/sinfonia-ui/tree/main/.github>

![](/files/ChnOXohKRtjHBuHIrMq6)

2 - Click on **CONTRIBUTING.md** to be sure you match the requirements to Report a Bug.&#x20;

![](/files/zlKL4oeZpdCRbT4Fmy8u)

3 - Go back to <https://github.com/bitsongofficial/sinfonia-ui/tree/main/.github> and click on **ISSUE TEMPLATE**.

![](/files/Q0PcyncuYwbtfJ01t46v)

4 - Click on **BUG-COMPETITION-REPORT** to have a preview of the template you will to Report a Bug.

![](/files/mKOvDwjoL8Yew9YAXbP9)

5 - Now you can Report a Bug, click on **Issue.**  Before proceeding, make sure the Bug has not already been reported.

![](/files/SUhka3ZzAFB6hfDJJBmJ)

6 - Click on **New Issue.**

![](/files/KU9pdyxMC4ksdWh7uNs6)

7 - Click on **Get Started.**

![](/files/EohNhjGx4fQddJmE8AjX)

8 - Fill the Template and click at end end of the Page **Submit new issue.**&#x20;

![](/files/gb4UXAq7PdQDVmdJATjS)

You have correctly Report a Bug. Thank your for you support! A team member will contact you.


# Nodes


# Sentry Nodes via Akash

host public or private sentry nodes on hardware resources rented via Akash


# Fantokens




---

[Next Page](/llms-full.txt/1)

