# BTC20 Smart Chain

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


# INTRO

### WHAT IS A BLOCKCHAIN? <a href="#what-is-a-blockchain" id="what-is-a-blockchain"></a>

A blockchain is a public database that is updated and shared across many computers in a network.

"Block" refers to data and state being stored in consecutive groups known as "blocks". If you send BTCC to someone else, the transaction data needs to be added to a block to be successful.

"Chain" refers to the fact that each block cryptographically references its parent. In other words, blocks get chained together. The data in a block cannot change without changing all subsequent blocks, which would require the consensus of the entire network.

Every computer in the network must agree upon each new block and the chain as a whole. These computers are known as "nodes". Nodes ensure everyone interacting with the blockchain has the same data. To accomplish this distributed agreement, blockchains need a consensus mechanism.

BTC20 smart chain uses a proof-of-stake-based consensus mechanism. Anyone who wants to add new blocks to the chain must stake BTCC - the native currency in BTC20 smart chain - as collateral and run validator software. These "validators" can then be randomly selected to propose blocks that other validators check and add to the blockchain. There is a system of rewards and penalties that strongly incentivize participants to be honest and available online as much as possible.

### WHAT IS BTC20 Smart Chain? <a href="#what-is-ethereum" id="what-is-ethereum"></a>

BTC20 Smart Chain is a blockchain with a computer embedded in it. It is the foundation for building apps and organizations in a decentralized, permissionless, censorship-resistant way.

In the BTC20 Smart Chain universe, there is a single, canonical computer (called EVM) whose state everyone on the BTC20 Smart Chain network agrees on. Everyone who participates in the network (every BTC20 Smart Chain node) keeps a copy of the state of this computer. Additionally, any participant can broadcast a request for this computer to perform arbitrary computation. Whenever such a request is broadcast, other participants on the network verify, validate, and carry out ("execute") the computation. This execution causes a state change in the EVM, which is committed and propagated throughout the entire network.

Requests for computation are called transaction requests; the record of all transactions and the EVM's present state gets stored on the blockchain, which in turn is stored and agreed upon by all nodes.

Cryptographic mechanisms ensure that once transactions are verified as valid and added to the blockchain, they can't be tampered with later. The same mechanisms also ensure that all transactions are signed and executed with appropriate "permissions" (no one should be able to send digital assets from Alice's account, except for Alice herself).

### WHAT IS BTCC? <a href="#what-is-ether" id="what-is-ether"></a>

**BTCC** is the native cryptocurrency of BTC20 Smart Chain. The purpose of BTCC is to allow for a market for computation. Such a market provides an economic incentive for participants to verify and execute transaction requests and provide computational resources to the network.

Any participant who broadcasts a transaction request must also offer some amount of BTCC to the network as a bounty. The network will award this bounty to whoever eventually does the work of verifying the transaction, executing it, committing it to the blockchain, and broadcasting it to the network.

The amount of BTCC paid corresponds to the resources required to do the computation. These bounties also prevent malicious participants from intentionally clogging the network by requesting the execution of infinite computation or other resource-intensive scripts, as these participants must pay for computation resources.

BTCC is also used to provide crypto-economic security to the network in three main ways: 1) it is used as a means to reward validators who propose blocks or call out dishonest behavior by other validators; 2) It is staked by validators, acting as collateral against dishonest behavior—if validators attempt to misbehave their BTCC can be destroyed; 3) it is used to weigh 'votes' for newly proposed blocks, feeding into the fork-choice part of the consensus mechanism.

### WHAT ARE SMART CONTRACTS? <a href="#what-are-smart-contracts" id="what-are-smart-contracts"></a>

In practice, participants don't write new code every time they want to request a computation on the EVM. Rather, application developers upload programs (reusable snippets of code) into EVM state, and users make requests to execute these code snippets with varying parameters. We call the programs uploaded to and executed by the network smart contracts.

At a very basic level, you can think of a smart contract like a sort of vending machine: a script that, when called with certain parameters, performs some actions or computation if certain conditions are satisfied. For example, a simple vendor smart contract could create and assign ownership of a digital asset if the caller sends BTCC to a specific recipient.

Any developer can create a smart contract and make it public to the network, using the blockchain as its data layer, for a fee paid to the network. Any user can then call the smart contract to execute its code, again for a fee paid to the network.

Thus, with smart contracts, developers can build and deploy arbitrarily complex user-facing apps and services such as: marketplaces, financial instruments, games, etc.

<br>


# INTRO TO BTCC

### WHAT IS A CRYPTOCURRENCY? <a href="#what-is-a-cryptocurrency" id="what-is-a-cryptocurrency"></a>

A cryptocurrency is a medium of exchange secured by a blockchain-based ledger.

A medium of exchange is anything widely accepted as payment for goods and services, and a ledger is a data store that keeps track of transactions. Blockchain technology allows users to make transactions on the ledger without reliance upon a trusted third party to maintain the ledger.

The first cryptocurrency was Bitcoin, created by Satoshi Nakamoto. Since Bitcoin's release in 2009, people have made thousands of cryptocurrencies across many different blockchains.

### WHAT IS BTCC? <a href="#what-is-ether" id="what-is-ether"></a>

**BTCC** is the cryptocurrency used for many things on the BTC20 Smart Chain network. Fundamentally, it is the only acceptable form of payment for transaction fees, BTCC is required to validate and propose blocks on Mainnet. BTCC is also used as a primary form of collateral in the DeFi lending markets, as a unit of account in NFT marketplaces, as payment earned for performing services or selling real-world goods, and more.

Bitcoin Smart Chain allows developers to create **decentralized applications (dapps)**, which all share a pool of computing power. This shared pool is finite, so Bitcoin Smart Chain needs a mechanism to determine who gets to use it. Otherwise, a dapp could accidentally or maliciously consume all network resources, which would block others from accessing it.

The btcc cryptocurrency supports a pricing mechanism for Bitcoin Smart Chain's computing power. When users want to make a transaction, they must pay btcc to have their transaction recognized on the blockchain. These usage costs are known as gas fees, and the gas fee depends on the amount of computing power required to execute the transaction and the network-wide demand for computing power at the time.

Therefore, even if a malicious dapp submitted an infinite loop, the transaction would eventually run out of btcc and terminate, allowing the network to return to normal.

### MINING BTCC <a href="#minting-ether" id="minting-ether"></a>

Mining is the process in which new btcc gets created on the BTC20 Smart Chain ledger. The underlying Bitcoin Smart Chain protocol creates the new btcc, and it is not possible for a user to create btcc.

Btcc is mined as a reward for miner staked in pool, each block proposed and at every epoch checkpoint for other validator activity related to reaching consensus. The circluly amount issued depends on the number of validators and how many miner staked. This block reward is divided equally among validators in the ideal case that all validators are honest and online, but in reality, it varies based on validator performance. About 1/8 of the block reward goes to the block proposer; the remainder is distributed across the other validators. Block proposers also receive tips from transaction fees and MEV-related income, but these come from recycled btcc, not new issuance.

### DENOMINATIONS OF BTCC <a href="#denominations" id="denominations"></a>

Since the value of many transactions on BTC20 Smart Chain are small, btcc has several denominations which may be referenced as smaller units of account. Of these denominations, Wei and gwei are particularly important.

Wei is the smallest possible amount of btcc, and as a result, many technical implementations

Gwei, short for giga-wei, is often used to describe gas costs on BTC20 Smart Chain.

| Denomination | Value In BTCC | Common Usage              |
| ------------ | ------------- | ------------------------- |
| Wei          | 10-18         | Technical implementations |
| Gwei         | 10-9          | Human-readable gas fees   |

### TRANSFERRING BTCC <a href="#transferring-ether" id="transferring-ether"></a>

Each transaction on BTC20 Smart Chain contains a `value` field, which specifies the amount of btcc to be transferred, denominated in wei, to send from the sender's address to the recipient address.

When the recipient address is a smart contract, this transferred btcc may be used to pay for gas when the smart contract executes its code.

### QUERYING BTCC <a href="#querying-ether" id="querying-ether"></a>

Users can query the btcc balance of any account by inspecting the account's `balance` field, which shows btcc holdings denominated in wei.

[Scan(opens in a new tab)](https://scan.bitcoincode.technology/) is a popular tool to inspect address balances via a web-based application.&#x20;

### TOTAL SUPPLY <a href="#further-reading" id="further-reading"></a>

21,000,000 BTCC


# DAPPS

A decentralized application (dapp) is an application built on a decentralized network that combines a smart contract and a frontend user interface. On BTC20 Smart Chain, smart contracts are accessible and transparent – like open APIs – so your dapp can even include a smart contract that someone else has written.

### DEFINITION OF A DAPP <a href="#definition-of-a-dapp" id="definition-of-a-dapp"></a>

A dapp has its backend code running on a decentralized peer-to-peer network. Contrast this with an app where the backend code is running on centralized servers.

A dapp can have frontend code and user interfaces written in any language (just like an app) to make calls to its backend. Furthermore, its frontend can get hosted on decentralized storage such as [IPFS(opens in a new tab)](https://ipfs.io/).

* **Decentralized** - dapps operate on BTC20 Smart Chain, an open public decentralized platform where no one person or group has control
* **Deterministic** - dapps perform the same function irrespective of the environment in which they get executed
* **Turing complete** - dapps can perform any action given the required resources
* **Isolated** - dapps are executed in a virtual environment known as EVM so that if the smart contract has a bug, it won’t hamper the normal functioning of the blockchain network

#### On smart contracts <a href="#on-smart-contracts" id="on-smart-contracts"></a>

To introduce dapps, we need to introduce smart contracts – a dapp's backend for lack of a better term. For a detailed overview, head to our section on [smart contracts](https://ethereum.org/en/developers/docs/smart-contracts/).

A smart contract is code that lives on the BTC20 Smart Chain blockchain and runs exactly as programmed. Once smart contracts are deployed on the network you can't change them. Dapps can be decentralized because they are controlled by the logic written into the contract, not an individual or company. This also means you need to design your contracts very carefully and test them thoroughly.

### BENEFITS OF DAPP DEVELOPMENT <a href="#benefits-of-dapp-development" id="benefits-of-dapp-development"></a>

* **Zero downtime** – Once the smart contract is deployed on the blockchain, the network as a whole will always be able to serve clients looking to interact with the contract. Malicious actors, therefore, cannot launch denial-of-service attacks targeted towards individual dapps.
* **Privacy** – You don’t need to provide real-world identity to deploy or interact with a dapp.
* **Resistance to censorship** – No single entity on the network can block users from submitting transactions, deploying dapps, or reading data from the blockchain.
* **Complete data integrity** – Data stored on the blockchain is immutable and indisputable, thanks to cryptographic primitives. Malicious actors cannot forge transactions or other data that has already been made public.
* **Trustless computation/verifiable behavior** – Smart contracts can be analyzed and are guaranteed to execute in predictable ways, without the need to trust a central authority. This is not true in traditional models; for example, when we use online banking systems, we must trust that financial institutions will not misuse our financial data, tamper with records, or get hacked.

### DRAWBACKS OF DAPP DEVELOPMENT <a href="#drawbacks-of-dapp-development" id="drawbacks-of-dapp-development"></a>

* **Maintenance** – Dapps can be harder to maintain because the code and data published to the blockchain are harder to modify. It’s hard for developers to make updates to their dapps (or the underlying data stored by a dapp) once they are deployed, even if bugs or security risks are identified in an old version.
* **Performance overhead** – There is a huge performance overhead, and scaling is really hard. To achieve the level of security, integrity, transparency, and reliability that BTC20 Smart Chain aspires to, every node runs and stores every transaction. On top of this, proof-of-stake consensus takes time as well.
* **Network congestion** – When one dapp uses too many computational resources, the entire network gets backed up. Currently, the network can only process about 10-15 transactions per second; if transactions are being sent in faster than this, the pool of unconfirmed transactions can quickly balloon.
* **User experience** – It may be harder to engineer user-friendly experiences because the average end-user might find it too difficult to set up a tool stack necessary to interact with the blockchain in a truly secure fashion.
* **Centralization** – User-friendly and developer-friendly solutions built on top of the base layer of BTC20 Smart Chain might end up looking like centralized services anyways. For example, such services may store keys or other sensitive information server-side, serve a frontend using a centralized server, or run important business logic on a centralized server before writing to the blockchain. Centralization eliminates many (if not all) of the advantages of blockchain over the traditional model.


# SMART CONTRACTS

### WHAT IS A SMART CONTRACT? <a href="#what-is-a-smart-contract" id="what-is-a-smart-contract"></a>

A "smart contract" is simply a program that runs on the BTC20 Smart Chain blockchain. It's a collection of code (its functions) and data (its state) that resides at a specific address on the BTC20 Smart Chain blockchain.

Smart contracts are a type of BTC20 Smart Chain account. This means they have a balance and can be the target of transactions. However they're not controlled by a user, instead they are deployed to the network and run as programmed. User accounts can then interact with a smart contract by submitting transactions that execute a function defined on the smart contract. Smart contracts can define rules, like a regular contract, and automatically enforce them via the code. Smart contracts cannot be deleted by default, and interactions with them are irreversible.

### A DIGITAL VENDING MACHINE <a href="#a-digital-vending-machine" id="a-digital-vending-machine"></a>

To get a snack from a vending machine:

```
1money + snack selection = snack dispensed2
```

This logic is programmed into the vending machine.

A smart contract, like a vending machine, has logic programmed into it. Here's a simple example of how this vending machine would look if it were a smart contract written in Solidity:

```
1pragma solidity 0.8.7;2
3contract VendingMachine {4
5    // Declare state variables of the contract6    address public owner;7    mapping (address => uint) public cupcakeBalances;8
9    // When 'VendingMachine' contract is deployed:10    // 1. set the deploying address as the owner of the contract11    // 2. set the deployed smart contract's cupcake balance to 10012    constructor() {13        owner = msg.sender;14        cupcakeBalances[address(this)] = 100;15    }16
17    // Allow the owner to increase the smart contract's cupcake balance18    function refill(uint amount) public {19        require(msg.sender == owner, "Only the owner can refill.");20        cupcakeBalances[address(this)] += amount;21    }22
23    // Allow anyone to purchase cupcakes24    function purchase(uint amount) public payable {25        require(msg.value >= amount * 1 btcc, "You must pay at least 1 BTCC per cupcake");26        require(cupcakeBalances[address(this)] >= amount, "Not enough cupcakes in stock to complete this purchase");27        cupcakeBalances[address(this)] -= amount;28        cupcakeBalances[msg.sender] += amount;29    }30}31
Show all Copy
```

Like how a vending machine removes the need for a vendor employee, smart contracts can replace intermediaries in many industries.

### PERMISSIONLESS <a href="#permissionless" id="permissionless"></a>

Anyone can write a smart contract and deploy it to the network. You just need to learn how to code in a smart contract language, and have enough BTCC to deploy your contract. Deploying a smart contract is technically a transaction, so you need to pay gas in the same way you need to pay gas for a simple BTCC transfer. However, gas costs for contract deployment are far higher.

BTC20 Smart Chain has developer-friendly languages for writing smart contracts:

* Solidity

However, they must be compiled before they can be deployed so that EVM can interpret and store the contract.

### COMPOSABILITY <a href="#composability" id="composability"></a>

Smart contracts are public on BTC20 Smart Chain and can be thought of as open APIs. This means you can call other smart contracts in your own smart contract to greatly extend what's possible. Contracts can even deploy other contracts.

### LIMITATIONS <a href="#limitations" id="limitations"></a>

Smart contracts alone cannot get information about "real-world" events because they can't retrieve data from off-chain sources. This means they can't respond to events in the real world. This is by design. Relying on external information could jeopardise consensus, which is important for security and decentralization.

However, it is important for blockchain applications to be able to use off-chain data. The solution is oracles which are tools that ingest off-chain data and make it available to smart contracts.

Another limitation of smart contracts is the maximum contract size. A smart contract can be a maximum of 24KB or it will run out of gas.&#x20;

### MULTISIG CONTRACTS <a href="#multisig" id="multisig"></a>

Multisig (multiple-signature) contracts are smart contract accounts that require multiple valid signatures to execute a transaction. This is very useful for avoiding single points of failure for contracts holding substantial amounts of btcc or other tokens. Multisigs also divide responsibility for contract execution and key management between multiple parties and prevent the loss of a single private key leading to irreversible loss of funds. For these reasons, multisig contracts can be used for simple DAO governance. Multisigs require N signatures out of M possible acceptable signatures (where N ≤ M, and M > 1) in order to execute. `N = 3, M = 5` and `N = 4, M = 7` are commonly used. A 4/7 multisig requires four out of seven possible valid signatures. This means the funds are still retrievable even if three signatures are lost. In this case, it also means that the majority of key-holders must agree and sign in order for the contract to execute.


# ACCOUNTS

BTC20 Smart Chain account is an entity with an BTCC balance that can send transactions on BTC20 Smart Chain. Accounts can be user-controlled or deployed as smart contracts.

### ACCOUNT TYPES <a href="#types-of-account" id="types-of-account"></a>

BTC20 Smart Chain has two account types:

* Externally-owned account (EOA) – controlled by anyone with the private keys
* Contract account – a smart contract deployed to the network, controlled by code. Learn about smart contracts

Both account types have the ability to:

* Receive, hold and send BTCC and tokens
* Interact with deployed smart contracts

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

**Externally-owned**

* Creating an account costs nothing
* Can initiate transactions
* Transactions between externally-owned accounts can only be BTCC/token transfers
* Made up of a cryptographic pair of keys: public and private keys that control account activities

**Contract**

* Creating a contract has a cost because you're using network storage
* Can only send transactions in response to receiving a transaction
* Transactions from an external account to a contract account can trigger code which can execute many different actions, such as transferring tokens or even creating a new contract
* Contract accounts don't have private keys. Instead, they are controlled by the logic of the smart contract code

### AN ACCOUNT EXAMINED <a href="#an-account-examined" id="an-account-examined"></a>

BTC20 Smart Chain accounts have four fields:

* `nonce` – A counter that indicates the number of transactions sent from an externally-owned account or the number of contracts created by a contract account. Only one transaction with a given nonce can be executed for each account, protecting against replay attacks where signed transactions are repeatedly broadcast and re-executed.
* `balance` – The number of wei owned by this address. Wei is a denomination of BTCC and there are 1e+18 wei per BTCC.
* `codeHash` – This hash refers to the *code* of an account on the EVM. Contract accounts have code fragments programmed in that can perform different operations. This EVM code gets executed if the account gets a message call. It cannot be changed, unlike the other account fields. All such code fragments are contained in the state database under their corresponding hashes for later retrieval. This hash value is known as a codeHash. For externally owned accounts, the codeHash field is the hash of an empty string.
* `storageRoot` – Sometimes known as a storage hash. A 256-bit hash of the root node of a Merkle Patricia trie that encodes the storage contents of the account (a mapping between 256-bit integer values), encoded into the trie as a mapping from the Keccak 256-bit hash of the 256-bit integer keys to the RLP-encoded 256-bit integer values. This trie encodes the hash of the storage contents of this account, and is empty by default.

[![A diagram showing the make up of an account](https://ethereum.org/static/19443ab40f108c985fb95b07bac29bcb/302a4/accounts.png)](https://ethereum.org/static/19443ab40f108c985fb95b07bac29bcb/302a4/accounts.png)

### EXTERNALLY-OWNED ACCOUNTS AND KEY PAIRS <a href="#externally-owned-accounts-and-key-pairs" id="externally-owned-accounts-and-key-pairs"></a>

An account is made up of a cryptographic pair of keys: public and private. They help prove that a transaction was actually signed by the sender and prevent forgeries. Your private key is what you use to sign transactions, so it grants you custody over the funds associated with your account. You never really hold cryptocurrency, you hold private keys – the funds are always on BTC20 Smart Chain's ledger.

This prevents malicious actors from broadcasting fake transactions because you can always verify the sender of a transaction.

If Alice wants to send BTCC from her own account to Bob’s account, Alice needs to create a transaction request and send it out to the network for verification. BTC20 Smart Chain's usage of public-key cryptography ensures that Alice can prove that she originally initiated the transaction request. Without cryptographic mechanisms, a malicious adversary Eve could simply publicly broadcast a request that looks something like “send 5 BTCC from Alice’s account to Eve’s account,” and no one would be able to verify that it didn’t come from Alice.

### ACCOUNT CREATION <a href="#account-creation" id="account-creation"></a>

When you want to create an account most libraries will generate you a random private key.

A private key is made up of 64 hex characters and can be encrypted with a password.

Example:

`fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd036415f`

The public key is generated from the private key using the [Elliptic Curve Digital Signature Algorithm(opens in a new tab)](https://wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm). You get a public address for your account by taking the last 20 bytes of the Keccak-256 hash of the public key and adding `0x` to the beginning.

It is possible to derive new public keys from your private key but you cannot derive a private key from public keys. This means it's vital to keep a private key safe and, as the name suggests, **PRIVATE**.

You need a private key to sign messages and transactions which output a signature. Others can then take the signature to derive your public key, proving the author of the message. In your application, you can use a javascript library to send transactions to the network.

### CONTRACT ACCOUNTS <a href="#contract-accounts" id="contract-accounts"></a>

Contract accounts also have a 42 character hexadecimal address:

Example:

`0x06012c8cf97bead5deae237070f9587f8e7a266d`

The contract address is usually given when a contract is deployed to the BTC20 Smart Chain. The address comes from the creator's address and the number of transactions sent from that address (the “nonce”).

### VALIDATOR KEYS <a href="#validators-keys" id="validators-keys"></a>

There is also another type of key in BTC20 Smart Chain. These are 'BLS' keys and they are used to identify validators. These keys can be efficiently aggregated to reduce the bandwidth required for the network to come to consensus. Without this key aggregation the minimum stake for a validator would be much higher.

### A NOTE ON WALLETS <a href="#a-note-on-wallets" id="a-note-on-wallets"></a>

An account is not a wallet. An account is the keypair for a user-owned BTC20 Smart Chain account. A wallet is an interface or application that lets you interact with your BTC20 Smart Chain account.

<br>


# TRANSACTIONS

Transactions are cryptographically signed instructions from accounts. An account will initiate a transaction to update the state of the BTC20 Smart Chain network. The simplest transaction is transferring BTCC from one account to another.

### WHAT'S A TRANSACTION? <a href="#whats-a-transaction" id="whats-a-transaction"></a>

BTC20 Smart Chain transaction refers to an action initiated by an externally-owned account, in other words an account managed by a human, not a contract. For example, if Bob sends Alice 1 BTCC, Bob's account must be debited and Alice's must be credited. This state-changing action takes place within a transaction.

[![Diagram showing a transaction cause state change](https://ethereum.org/static/570dedb843948d6bef5e21a6769d5c35/302a4/tx.png)](https://ethereum.org/static/570dedb843948d6bef5e21a6769d5c35/302a4/tx.png)

Transactions, which change the state of the EVM, need to be broadcast to the whole network. Any node can broadcast a request for a transaction to be executed on the EVM; after this happens, a validator will execute the transaction and propagate the resulting state change to the rest of the network.

Transactions require a fee and must be included in a validated block. To make this overview simpler we'll cover gas fees and validation elsewhere.

A submitted transaction includes the following information:

* `from` – the address of the sender, that will be signing the transaction. This will be an externally-owned account as contract accounts cannot send transactions.
* `recipient` – the receiving address (if an externally-owned account, the transaction will transfer value. If a contract account, the transaction will execute the contract code)
* `signature` – the identifier of the sender. This is generated when the sender's private key signs the transaction and confirms the sender has authorized this transaction
* `nonce` - a sequentially incrementing counter which indicates the transaction number from the account
* `value` – amount of BTCC to transfer from sender to recipient (denominated in WEI, where 1 BTCC equals 1e+18wei)
* `input data` – optional field to include arbitrary data
* `gasLimit` – the maximum amount of gas units that can be consumed by the transaction. The EVM specifies the units of gas required by each computational step
* `maxPriorityFeePerGas` - the maximum price of the consumed gas to be included as a tip to the validator
* `maxFeePerGas` - the maximum fee per unit of gas willing to be paid for the transaction (inclusive of `baseFeePerGas` and `maxPriorityFeePerGas`)

Gas is a reference to the computation required to process the transaction by a validator. Users have to pay a fee for this computation. The `gasLimit`, and `maxPriorityFeePerGas` determine the maximum transaction fee paid to the validator.&#x20;

The transaction object will look a little like this:

```
1{2  from: "0xEA674fdDe714fd979de3EdF0F56AA9716B898ec8",3  to: "0xac03bb73b6a9e108530aff4df5077c2b3d481e5a",4  gasLimit: "21000",5  maxFeePerGas: "300",6  maxPriorityFeePerGas: "10",7  nonce: "0",8  value: "10000000000"9}10
Show all Copy
```

But a transaction object needs to be signed using the sender's private key. This proves that the transaction could only have come from the sender and was not sent fraudulently.

BTC20 Smart Chain client will handle this signing process.

Example JSON-RPC call:

```
1{2  "id": 2,3  "jsonrpc": "2.0",4  "method": "account_signTransaction",5  "params": [6    {7      "from": "0x1923f626bb8dc025849e00f99c25fe2b2f7fb0db",8      "gas": "0x55555",9      "maxFeePerGas": "0x1234",10      "maxPriorityFeePerGas": "0x1234",11      "input": "0xabcd",12      "nonce": "0x0",13      "to": "0x07a565b7ed7d7a678680a4c162885bedbb695fe0",14      "value": "0x1234"15    }16  ]17}18
Show all Copy
```

Example response:

```
1{2  "jsonrpc": "2.0",3  "id": 2,4  "result": {5    "raw": "0xf88380018203339407a565b7ed7d7a678680a4c162885bedbb695fe080a44401a6e4000000000000000000000000000000000000000000000000000000000000001226a0223a7c9bcf5531c99be5ea7082183816eb20cfe0bbc322e97cc5c7f71ab8b20ea02aadee6b34b45bb15bc42d9c09de4a6754e7000908da72d48cc7704971491663",6    "tx": {7      "nonce": "0x0",8      "maxFeePerGas": "0x1234",9      "maxPriorityFeePerGas": "0x1234",10      "gas": "0x55555",11      "to": "0x07a565b7ed7d7a678680a4c162885bedbb695fe0",12      "value": "0x1234",13      "input": "0xabcd",14      "v": "0x26",15      "r": "0x223a7c9bcf5531c99be5ea7082183816eb20cfe0bbc322e97cc5c7f71ab8b20e",16      "s": "0x2aadee6b34b45bb15bc42d9c09de4a6754e7000908da72d48cc7704971491663",17      "hash": "0xeba2df809e7a612a0a0d444ccfa5c839624bdc00dd29e3340d46df3870f8a30e"18    }19  }20}21
Show all Copy
```

* the `raw` is the signed transaction in Recursive Length Prefix (RLP) encoded form
* the `tx` is the signed transaction in JSON form

With the signature hash, the transaction can be cryptographically proven that it came from the sender and submitted to the network.

#### The data field <a href="#the-data-field" id="the-data-field"></a>

The vast majority of transactions access a contract from an externally-owned account. Most contracts are written in Solidity and interpret their data field in accordance with the&#x20;

application binary interface (ABI).

The first four bytes specify which function to call, using the hash of the function's name and arguments. You can sometimes identify the function from the selector using [this database(opens in a new tab)](https://www.4byte.directory/signatures/).

The rest of the calldata is the arguments, [encoded as specified in the ABI specs(opens in a new tab)](https://docs.soliditylang.org/en/latest/abi-spec.html#formal-specification-of-the-encoding).

For example, lets look at [this transaction(opens in a new tab)](https://etherscan.io/tx/0xd0dcbe007569fcfa1902dae0ab8b4e078efe42e231786312289b1eee5590f6a1). Use **Click to see More** to see the calldata.

The function selector is `0xa9059cbb`. There are several [known functions with this signature(opens in a new tab)](https://www.4byte.directory/signatures/?bytes4_signature=0xa9059cbb). In this case [the contract source code(opens in a new tab)](https://etherscan.io/address/0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48#code) has been uploaded to btccscan, so we know the function is `transfer(address,uint256)`.

The rest of the data is:

```
10000000000000000000000004f6742badb049791cd9a37ea913f2bac38d012792000000000000000000000000000000000000000000000000000000003b0559f43
```

According to the ABI specifications, integer values (such as addresses, which are 20-byte integers) appear in the ABI as 32-byte words, padded with zeros in the front. So we know that the `to` address is [`4f6742badb049791cd9a37ea913f2bac38d01279`(opens in a new tab)](https://etherscan.io/address/0x4f6742badb049791cd9a37ea913f2bac38d01279). The `value` is 0x3b0559f4 = 990206452.

### TYPES OF TRANSACTIONS <a href="#types-of-transactions" id="types-of-transactions"></a>

On BTC20 Smart Chain there are a few different types of transactions:

* Regular transactions: a transaction from one account to another.
* Contract deployment transactions: a transaction without a 'to' address, where the data field is used for the contract code.
* Execution of a contract: a transaction that interacts with a deployed smart contract. In this case, 'to' address is the smart contract address.

#### On gas <a href="#on-gas" id="on-gas"></a>

As mentioned, transactions cost [gas](https://ethereum.org/en/developers/docs/gas/) to execute. Simple transfer transactions require 21000 units of Gas.

So for Bob to send Alice 1 BTCC at a `baseFeePerGas` of 190 gwei and `maxPriorityFeePerGas` of 10 gwei, Bob will need to pay the following fee:

```
1(190 + 10) * 21000 = 4,200,000 gwei2--or--30.0042 BTCC4
```

Bob's account will be debited **-1.0042 BTCC** (1 BTCC for Alice + 0.0042 BTCC in gas fees)

Alice's account will be credited **+1.0 BTCC**

The base fee will be burned **-0.00399 BTCC**

Validator keeps the tip **+0.000210 BTCC**

Gas is required for any smart contract interaction too.

[![Diagram showing how unused gas is refunded](https://ethereum.org/static/c3638b26a1210d2c73a7ec2335c57351/302a4/gas-tx.png)](https://ethereum.org/static/c3638b26a1210d2c73a7ec2335c57351/302a4/gas-tx.png)

Any gas not used in a transaction is refunded to the user account.

### TRANSACTION LIFECYCLE <a href="#transaction-lifecycle" id="transaction-lifecycle"></a>

Once the transaction has been submitted the following happens:

1. A transaction hash is cryptographically generated: `0x97d99bc7729211111a21b12c933c949d4f31684f1d6954ff477d0477538ff017`
2. The transaction is then broadcasted to the network and added to a transaction pool consisting of all other pending network transactions.
3. A validator must pick your transaction and include it in a block in order to verify the transaction and consider it "successful".
4. As time passes the block containing your transaction will be upgraded to "justified" then "finalized". These upgrades make it much more certain that your transaction was successful and will never be altered. Once a block is "finalized" it could only ever be changed by a network level attack that would cost many billions of dollars.

<br>


# BLOCKS

Blocks are batches of transactions with a hash of the previous block in the chain. This links blocks together (in a chain) because hashes are cryptographically derived from the block data. This prevents fraud, because one change in any block in history would invalidate all the following blocks as all subsequent hashes would change and everyone running the blockchain would notice.

### WHY BLOCKS? <a href="#why-blocks" id="why-blocks"></a>

To ensure that all participants on the BTC20 Smart Chain network maintain a synchronized state and agree on the precise history of transactions, we batch transactions into blocks. This means dozens (or hundreds) of transactions are committed, agreed on, and synchronized all at once.

[![A diagram showing transaction in a block causing state changes](https://ethereum.org/static/85d784391401f89209d3bcc51e0ea677/302a4/tx-block.png)](https://ethereum.org/static/85d784391401f89209d3bcc51e0ea677/302a4/tx-block.png)

By spacing out commits, we give all network participants enough time to come to consensus: even though transaction requests occur dozens of times per second, blocks are only created and committed on BTC20 Smart Chain once every twelve seconds.

### HOW BLOCKS WORK <a href="#how-blocks-work" id="how-blocks-work"></a>

To preserve the transaction history, blocks are strictly ordered (every new block created contains a reference to its parent block), and transactions within blocks are strictly ordered as well. Except in rare cases, at any given time, all participants on the network are in agreement on the exact number and history of blocks, and are working to batch the current live transaction requests into the next block.

Once a block is put together by a randomly selected validator on the network, it is propagated to the rest of the network; all nodes add this block to the end of their blockchain, and a new validator is selected to create the next block. The exact block-assembly process and commitment/consensus process is currently specified by BTC20 Smart Chain's “proof-of-stake” protocol.

### PROOF-OF-STAKE PROTOCOL <a href="#proof-of-work-protocol" id="proof-of-work-protocol"></a>

Proof-of-stake means the following:

* Validating nodes have to stake 1000 BTCC into a deposit contract as collateral against bad behavior. This helps protect the network because provably dishonest activity leads to some or all of that stake being destroyed.
* In every slot (spaced twelve seconds apart) a validator is randomly selected to be the block proposer. They bundle transactions together, execute them and determine a new 'state'. They wrap this information into a block and pass it around to other validators.
* Other validators who hear about the new block re-execute the transactions to ensure they agree with the proposed change to the global state. Assuming the block is valid, they add it to their own database.
* If a validator hears about two conflicting blocks for the same slot they use their fork-choice algorithm to pick the one supported by the most staked BTCC.

### WHAT'S IN A BLOCK? <a href="#block-anatomy" id="block-anatomy"></a>

There is a lot of information contained within a block. At the highest level a block contains the following fields:

| Field            | Description                                           |
| ---------------- | ----------------------------------------------------- |
| `slot`           | the slot the block belongs to                         |
| `proposer_index` | the ID of the validator proposing the block           |
| `parent_root`    | the hash of the preceding block                       |
| `state_root`     | the root hash of the state object                     |
| `body`           | an object containing several fields, as defined below |

The block `body` contains several fields of its own:

| Field                | Description                                        |
| -------------------- | -------------------------------------------------- |
| `randao_reveal`      | a value used to select the next block proposer     |
| btcc`1_data`         | information about the deposit contract             |
| `graffiti`           | arbitrary data used to tag blocks                  |
| `proposer_slashings` | list of validators to be slashed                   |
| `attester_slashings` | list of validators to be slashed                   |
| `attestations`       | list of attestations in favor of the current block |
| `deposits`           | list of new deposits to the deposit contract       |
| `voluntary_exits`    | list of validators exiting the network             |
| `sync_aggregate`     | subset of validators used to serve light clients   |
| `execution_payload`  | transactions passed from the execution client      |

The `attestations` field contains a list of all the attestations in the block. Attestations have their own data type that contains several pieces of data. Each attestation contains:

| Field              | Description                                                 |
| ------------------ | ----------------------------------------------------------- |
| `aggregation_bits` | a list of which validators participated in this attestation |
| `data`             | a container with multiple subfields                         |
| `signature`        | aggregate signature of all attesting validators             |

The `data` field in the `attestation` contains the following:

| Field               | Description                                              |
| ------------------- | -------------------------------------------------------- |
| `slot`              | the slot the attestation relates to                      |
| `index`             | indices for attesting validators                         |
| `beacon_block_root` | the root hash of the Beacon block containing this object |
| `source`            | the last justified checkpoint                            |
| `target`            | the latest epoch boundary block                          |

Executing the transactions in the `execution_payload` updates the global state. All clients re-execute the transactions in the `execution_payload` to ensure the new state matches that in the new block `state_root` field. This is how clients can tell that a new block is valid and safe to add to their blockchain. The `execution payload` itself is an object with several fields. There is also an `execution_payload_header` that contains important summary information about the execution data. These data structures are organized as follows:

The `execution_payload_header` contains the following fields:

| Field               | Description                                                         |
| ------------------- | ------------------------------------------------------------------- |
| `parent_hash`       | hash of the parent block                                            |
| `fee_recipient`     | account address for paying transaction fees to                      |
| `state_root`        | root hash for the global state after applying changes in this block |
| `receipts_root`     | hash of the transaction receipts trie                               |
| `logs_bloom`        | data structure containing event logs                                |
| `prev_randao`       | value used in random validator selection                            |
| `block_number`      | the number of the current block                                     |
| `gas_limit`         | maximum gas allowed in this block                                   |
| `gas_used`          | the actual amount of gas used in this block                         |
| `timestamp`         | the block time                                                      |
| `extra_data`        | arbitrary additional data as raw bytes                              |
| `base_fee_per_gas`  | the base fee value                                                  |
| `block_hash`        | Hash of execution block                                             |
| `transactions_root` | root hash of the transactions in the payload                        |
| `withdrawal_root`   | root hash of the withdrawals in the payload                         |

The `execution_payload` itself contains the following (notice this is identical to the header except that instead of the root hash of the transactions it includes the actual list of transactions and withdrawal information) :

| Field              | Description                                                         |
| ------------------ | ------------------------------------------------------------------- |
| `parent_hash`      | hash of the parent block                                            |
| `fee_recipient`    | account address for paying transaction fees to                      |
| `state_root`       | root hash for the global state after applying changes in this block |
| `receipts_root`    | hash of the transaction receipts trie                               |
| `logs_bloom`       | data structure containing event logs                                |
| `prev_randao`      | value used in random validator selection                            |
| `block_number`     | the number of the current block                                     |
| `gas_limit`        | maximum gas allowed in this block                                   |
| `gas_used`         | the actual amount of gas used in this block                         |
| `timestamp`        | the block time                                                      |
| `extra_data`       | arbitrary additional data as raw bytes                              |
| `base_fee_per_gas` | the base fee value                                                  |
| `block_hash`       | Hash of execution block                                             |
| `transactions`     | list of transactions to be executed                                 |
| `withdrawals`      | list of withdrawal objects                                          |

The `withdrawals` list contains `withdrawal` objects structured in the following way:

| Field            | Description                        |
| ---------------- | ---------------------------------- |
| `address`        | account address that has withdrawn |
| `amount`         | withdrawal amount                  |
| `index`          | withdrawal index value             |
| `validatorIndex` | validator index value              |

### BLOCK TIME <a href="#block-time" id="block-time"></a>

Block time refers to the time separating blocks. In BTC20 Smart Chain, time is divided up into twelve second units called 'slots'. In each slot a single validator is selected to propose a block. Assuming all validators are online and fully functional there will be a block in every slot, meaning the block time is 12s. However, occasionally validators might be offline when called to propose a block, meaning slots can sometimes go empty.

This implementation differs from proof-of-work based systems where block times are probabilistic and tuned by the protocol's target mining difficulty. BTC20 Smart Chain's average block time is a perfect example of this whereby the transition from proof-of-work to proof-of-stake can be clearly inferred based on the consistency of the new 12s block time.

### BLOCK SIZE <a href="#block-size" id="block-size"></a>

A final important note is that blocks themselves are bounded in size. Each block has a target size of 15 million gas but the size of blocks will increase or decrease in accordance with network demands, up until the block limit of 30 million gas (2x target block size). The total amount of gas expended by all transactions in the block must be less than the block gas limit. This is important because it ensures that blocks can’t be arbitrarily large. If blocks could be arbitrarily large, then less performant full nodes would gradually stop being able to keep up with the network due to space and speed requirements. The larger the block, the greater the computing power required to process them in time for the next slot. This is a centralizing force, which is resisted by capping block sizes.

### FURTHER READING <a href="#further-reading" id="further-reading"></a>

*Know of a community resource that helped you? Edit this page and add it!*

<br>


# PROOF-OF-STAKE (POS)

Proof-of-stake (PoS) is more secure, less energy-intensive, and better for implementing new scaling solutions compared to the previous proof-of-work architecture.

### WHAT IS PROOF-OF-STAKE (POS)? <a href="#what-is-pos" id="what-is-pos"></a>

Proof-of-stake is a way to prove that validators have put something of value into the network that can be destroyed if they act dishonestly. In BTC20 Smart Chain's proof-of-stake, validators explicitly stake capital in the form of BTCC into a smart contract on BTC20 Smart Chain. The validator is then responsible for checking that new blocks propagated over the network are valid and occasionally creating and propagating new blocks themselves. If they try to defraud the network (for example by proposing multiple blocks when they ought to send one or sending conflicting attestations), some or all of their staked BTCC can be destroyed.

### VALIDATORS <a href="#validators" id="validators"></a>

To participate as a validator, a user must deposit 1000 BTCC into the deposit contract and run three separate pieces of software: an execution client, a consensus client, and a validator client. On depositing their BTCC, the user joins an activation queue that limits the rate of new validators joining the network. Once activated, validators receive new blocks from peers on the BTC20 Smart Chain network. The transactions delivered in the block are re-executed to check that the proposed changes to BTC20 Smart Chain's state are valid, and the block signature is checked. The validator then sends a vote (called an attestation) in favor of that block across the network.

Whereas under proof-of-work, the timing of blocks is determined by the mining difficulty, in proof-of-stake, the tempo is fixed. Time in proof-of-stake BTC20 Smart Chain is divided into slots (12 seconds) and epochs (32 slots). One validator is randomly selected to be a block proposer in every slot. This validator is responsible for creating a new block and sending it out to other nodes on the network. Also in every slot, a committee of validators is randomly chosen, whose votes are used to determine the validity of the block being proposed. Dividing the validator set up into committees is important for keeping the network load manageable. Committees divide up the validator set so that every active validator attests in every epoch, but not in every slot.

### HOW A TRANSACTION GETS EXECUTED IN BTC20 Smart Chain POS <a href="#transaction-execution-ethereum-pos" id="transaction-execution-ethereum-pos"></a>

The following provides an end-to-end explanation of how a transaction gets executed in BTC20 Smart Chain proof-of-stake.

1. A user creates and signs a transaction with their private key. This is usually handled by a wallet or a library but under the hood the user is making a request to a node using the BTC20 Smart Chain JSON-RPC API. The user defines the amount of gas that they are prepared to pay as a tip to a validator to encourage them to include the transaction in a block.&#x20;
2. The transaction is submitted to an BTC20 Smart Chain execution client which verifies its validity. This means ensuring that the sender has enough BTCC to fulfill the transaction and they have signed it with the correct key.
3. If the transaction is valid, the execution client adds it to its local mempool (list of pending transactions) and also broadcasts it to other nodes over the execution layer gossip network. When other nodes hear about the transaction they add it to their local mempool too. Advanced users might refrain from broadcasting their transaction and instead forward it to specialized block builders such as [Flashbots Auction(opens in a new tab)](https://docs.flashbots.net/flashbots-auction/overview). This allows them to organize the transactions in upcoming blocks for maximum profit (MEV).
4. One of the nodes on the network is the block proposer for the current slot, having previously been selected pseudo-randomly using RANDAO. This node is responsible for building and broadcasting the next block to be added to the BTC20 Smart Chain blockchain and updating the global state. The node is made up of three parts: an execution client, a consensus client and a validator client. The execution client bundles transactions from the local mempool into an "execution payload" and executes them locally to generate a state change. This information is passed to the consensus client where the execution payload is wrapped as part of a "beacon block" that also contains information about rewards, penalties, slashings, attestations etc. that enable the network to agree on the sequence of blocks at the head of the chain. The communication between the execution and consensus clients is described in more detail in Connecting the Consensus and Execution Clients.
5. Other nodes receive the new beacon block on the consensus layer gossip network. They pass it to their execution client where the transactions are re-executed locally to ensure the proposed state change is valid. The validator client then attests that the block is valid and is the logical next block in their view of the chain (meaning it builds on the chain with the greatest weight of attestations as defined in the fork choice rules). The block is added to the local database in each node that attests to it.
6. The transaction can be considered "finalized" if it has become part of a chain with a "supermajority link" between two checkpoints. Checkpoints occur at the start of each epoch and they exist to account for the fact that only a subset of active validators attest in each slot, but all active validators attest across each epoch. Therefore, it is only between epochs that a 'supermajority link' can be demonstrated (this is where 66% of the total staked BTCC on the network agrees on two checkpoints).

More detail on finality can be found below.

### FINALITY <a href="#finality" id="finality"></a>

A transaction has "finality" in distributed networks when it is part of a block that can't change without a large amount of BTCC getting burned. On proof-of-stake BTC20 Smart Chain, this is managed using "checkpoint" blocks. The first block in each epoch is a checkpoint. Validators vote for pairs of checkpoints that it considers to be valid. If a pair of checkpoints attracts votes representing at least two-thirds of the total staked BTCC, the checkpoints are upgraded. The more recent of the two (target) becomes "justified". The earlier of the two is already justified because it was the "target" in the previous epoch. Now it is upgraded to "finalized".

To revert a finalized block, an attacker would commit to losing at least one-third of the total supply of staked BTCC. Since finality requires a two-thirds majority, an attacker could prevent the network from reaching finality by voting with one-third of the total stake. This activates whenever the chain fails to finalize for more than four epochs. The inactivity leak bleeds away the staked BTCC from validators voting against the majority, allowing the majority to regain a two-thirds majority and finalize the chain.

### CRYPTO-ECONOMIC SECURITY <a href="#crypto-economic-security" id="crypto-economic-security"></a>

Running a validator is a commitment. The validator is expected to maintain sufficient hardware and connectivity to participate in block validation and proposal. In return, the validator is paid in BTCC (their staked balance increases). On the other hand, participating as a validator also opens new avenues for users to attack the network for personal gain or sabotage. To prevent this, validators miss out on BTCC rewards if they fail to participate when called upon, and their existing stake can be destroyed if they behave dishonestly. Two primary behaviors can be considered dishonest: proposing multiple blocks in a single slot (equivocating) and submitting contradictory attestations.

The amount of BTCC slashed depends on how many validators are also being slashed at around the same time. This is known as the "correlation penalty", and it can be minor (\~1% stake for a single validator slashed on their own) or can result in 100% of the validator's stake getting destroyed (mass slashing event). It is imposed halfway through a forced exit period that begins with an immediate penalty (up to 1 BTCC) on Day 1, the correlation penalty on Day 18, and finally, ejection from the network on Day 36. They receive minor attestation penalties every day because they are present on the network but not submitting votes. This all means a coordinated attack would be very costly for the attacker.

### FORK CHOICE <a href="#fork-choice" id="fork-choice"></a>

When the network performs optimally and honestly, there is only ever one new block at the head of the chain, and all validators attest to it. However, it is possible for validators to have different views of the head of the chain due to network latency or because a block proposer has equivocated. Therefore, consensus clients require an algorithm to decide which one to favor. The algorithm used in proof-of-stake BTC20 Smart Chain is called [LMD-GHOST(opens in a new tab)](https://arxiv.org/pdf/2003.03052.pdf), and it works by identifying the fork that has the greatest weight of attestations in its history.

### PROOF-OF-STAKE AND SECURITY <a href="#pos-and-security" id="pos-and-security"></a>

The threat of a [51% attack(opens in a new tab)](https://www.investopedia.com/terms/1/51-attack.asp) still exists on proof-of-stake as it does on proof-of-work, but it's even riskier for the attackers. An attacker would need 51% of the staked BTCC. They could then use their own attestations to ensure their preferred fork was the one with the most accumulated attestations. The 'weight' of accumulated attestations is what consensus clients use to determine the correct chain, so this attacker would be able to make their fork the canonical one. However, a strength of proof-of-stake over proof-of-work is that the community has flexibility in mounting a counter-attack. For example, the honest validators could decide to keep building on the minority chain and ignore the attacker's fork while encouraging apps, exchanges, and pools to do the same. They could also decide to forcibly remove the attacker from the network and destroy their staked BTCC. These are strong economic defenses against a 51% attack.

51% attacks are just one flavor of malicious activity. Bad actors could attempt long-range attacks (although the finality gadget neutralizes this attack vector), short range 'reorgs' (although proposer boosting and attestation deadlines mitigate this), bouncing and balancing attacks (also mitigated by proposer boosting, and these attacks have anyway only been demonstrated under idealized network conditions) or avalanche attacks (neutralized by the fork choice algorithms rule of only considering the latest message).

Overall, proof-of-stake, as it is implemented on BTC20 Smart Chain, has been demonstrated to be more economically secure than proof-of-work.

### PROS AND CONS <a href="#pros-and-cons" id="pros-and-cons"></a>

| Pros                                                                                                                                                                                                                   | Cons                                                                                             |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| Staking makes it easier for individuals to participate in securing the network, promoting decentralization. validator node can be run on a normal laptop. Staking pools allow users to stake without having 1000 BTCC. | Proof-of-stake is younger and less battle-tested compared to proof-of-work                       |
| Staking is more decentralized. Economies of scale do not apply in the same way that they do for PoW mining.                                                                                                            | Proof-of-stake is more complex to implement than proof-of-work                                   |
| Proof-of-stake offers greater crypto-economic security than proof-of-work                                                                                                                                              | Users need to run three pieces of software to participate in BTC20 Smart Chain's proof-of-stake. |
| Less issuance of new BTCC is required to incentivize network participants                                                                                                                                              |                                                                                                  |

#### Comparison to proof-of-work <a href="#comparison-to-proof-of-work" id="comparison-to-proof-of-work"></a>

BTC20 Smart Chain has not always been a proof-of-stake network. When BTC20 Smart Chain started, it used proof-of-work. The switch from proof-of-work to proof-of-stake happened in September 2022. Proof-of-stake comes with benefits over proof-of-work:

* better energy efficiency – there is no need to use lots of energy on proof-of-work computations
* lower barriers to entry, reduced hardware requirements – there is no need for elite hardware to stand a chance of creating new blocks
* reduced centralization risk – proof-of-stake should lead to more nodes securing the network
* because of the low energy requirement less BTCC issuance is required to incentivize participation
* economic penalties for misbehavior make 51% style attacks more costly for an attacker compared to proof-of-work
* the community can resort to social recovery of an honest chain if a 51% attack were to overcome the crypto-economic defenses.


# Gas / Fee

Gas is essential to the BTC20 Smart Chain network. It is the fuel that allows it to operate, in the same way that a car needs gasoline to run.

### WHAT IS GAS? <a href="#what-is-gas" id="what-is-gas"></a>

Gas refers to the unit that measures the amount of computational effort required to execute specific operations on the BTC20 Smart Chain network.

Since each BTC20 Smart Chain transaction requires computational resources to execute, those resources have to be paid for to ensure BTC20 Smart Chain is not vulnerable to spam and cannot get stuck in infinite computational loops. Payment for computation is made in the form of a gas fee.

The gas fee is **the amount of gas used to do some operation, multiplied by the cost per unit gas**. The fee is paid regardless of whether a transaction succeeds or fails.

[![A diagram showing where gas is needed in EVM operations](https://ethereum.org/static/9628ab90bfd02f64cf873446cbdc6c70/302a4/gas.png)](https://ethereum.org/static/9628ab90bfd02f64cf873446cbdc6c70/302a4/gas.png)

Gas fees have to be paid in BTC20 Smart Chain's native currency, BTCC. Gas prices are usually quoted in gwei, which is a denomination of BTCC. Each gwei is equal to one-billionth of an BTCC (0.000000001 BTCC or 10-9 BTCC).

For example, instead of saying that your gas costs 0.000000001 BTCC, you can say your gas costs 1 gwei.

The word 'gwei' is a contraction of 'giga-wei', meaning 'billion wei'. One gwei is equal to one billion wei. Wei itself (named after [Wei Dai(opens in a new tab)](https://wikipedia.org/wiki/Wei_Dai), creator of [b-money(opens in a new tab)](https://www.investopedia.com/terms/b/bmoney.asp)) is the smallest unit of BTCC.

### HOW ARE GAS FEES CALCULATED? <a href="#how-are-gas-fees-calculated" id="how-are-gas-fees-calculated"></a>

You can set the amount of gas you are willing to pay when you submit a transaction. By offering a certain amount of gas, you are bidding for your transaction to be included in the next block. If you offer too little, validators are less likely to choose your transaction for inclusion, meaning your transaction may execute late or not at all. If you offer too much, you might waste some BTCC. So, how can you tell how much to pay?

The total gas you pay is divided into two components: the `base fee` and the `priority fee` (tip).

The `base fee` is set by the protocol - you have to pay at least this amount for your transaction to be considered valid. The `priority fee` is a tip that you add to the base fee to make your transaction attractive to validators so that they choose it for inclusion in the next block.

A transaction that only pays the `base fee` is technically valid but unlikely to be included because it offers no incentive to the validators to choose it over any other transaction. The 'correct' `priority` fee is determined by the network usage at the time you send your transaction - if there is a lot of demand then you might have to set your `priority` fee higher, but when there is less demand you can pay less.

For example, let's say Jordan has to pay Taylor 1 BTCC. An BTCC transfer requires 21,000 units of gas, and the base fee is 10 gwei. Jordan includes a tip of 2 gwei.

The total fee would now be equal to:

`units of gas used * (base fee + priority fee)`

where the `base fee` is a value set by the protocol and the `priority fee` is a value set by the user as a tip to the validator.

i.e. `21,000 * (10 + 2) = 252,000 gwei` (0.000252 BTCC).

When Jordan sends the money, 1.000252 BTCC will be deducted from Jordan's account. Taylor will be credited 1.0000 BTCC. The validator receives the tip of 0.000042 BTCC. The `base fee` of 0.00021 BTCC is burned.

#### Base fee <a href="#base-fee" id="base-fee"></a>

Every block has a base fee which acts as a reserve price. To be eligible for inclusion in a block the offered price per gas must at least equal the base fee. The base fee is calculated independently of the current block and is instead determined by the blocks before it - making transaction fees more predictable for users. When the block is created this **base fee is "burned"**, removing it from circulation.

The base fee is calculated by a formula that compares the size of the previous block (the amount of gas used for all the transactions) with the target size. The base fee will increase by a maximum of 12.5% per block if the target block size is exceeded. This exponential growth makes it economically non-viable for block size to remain high indefinitely.

| Block Number | Included Gas | Fee Increase | Current Base Fee |
| ------------ | ------------ | ------------ | ---------------- |
| 1            | 15M          | 0%           | 100 gwei         |
| 2            | 30M          | 0%           | 100 gwei         |
| 3            | 30M          | 12.5%        | 112.5 gwei       |
| 4            | 30M          | 12.5%        | 126.6 gwei       |
| 5            | 30M          | 12.5%        | 142.4 gwei       |
| 6            | 30M          | 12.5%        | 160.2 gwei       |
| 7            | 30M          | 12.5%        | 180.2 gwei       |
| 8            | 30M          | 12.5%        | 202.7 gwei       |

Following the table above - to create a transaction on block number 9, a wallet will let the user know with certainty that the **maximum base fee** to be added to the next block is `current base fee * 112.5%` or `202.7 gwei * 112.5% = 228.1 gwei`.

It's also important to note it is unlikely we will see extended spikes of full blocks because of the speed at which the base fee increases preceding a full block.

| Block Number | Included Gas | Fee Increase | Current Base Fee |
| ------------ | ------------ | ------------ | ---------------- |
| 30           | 30M          | 12.5%        | 2705.6 gwei      |
| ...          | ...          | 12.5%        | ...              |
| 50           | 30M          | 12.5%        | 28531.3 gwei     |
| ...          | ...          | 12.5%        | ...              |
| 100          | 30M          | 12.5%        | 10302608.6 gwei  |

#### Priority fee (tips) <a href="#priority-fee" id="priority-fee"></a>

The priority fee (tip) incentivizes validators to include a transaction in the block. Without tips, validators would find it economically viable to mine empty blocks, as they would receive the same block reward. Small tips give validators a minimal incentive to include a transaction. For transactions to be preferentially executed ahead of other transactions in the same block, a higher tip can be added to try to outbid competing transactions.

#### Max fee <a href="#maxfee" id="maxfee"></a>

To execute a transaction on the network, users can specify a maximum limit they are willing to pay for their transaction to be executed. This optional parameter is known as the `maxFeePerGas`. For a transaction to be executed, the max fee must exceed the sum of the base fee and the tip. The transaction sender is refunded the difference between the max fee and the sum of the base fee and tip.

#### Block size <a href="#block-size" id="block-size"></a>

Each block has a target size of 15 million gas, but the size of blocks will increase or decrease in accordance with network demand, up until the block limit of 30 million gas (2x the target block size). The protocol achieves an equilibrium block size of 15 million on average through the process of *tâtonnement*. This means if the block size is greater than the target block size, the protocol will increase the base fee for the following block. Similarly, the protocol will decrease the base fee if the block size is less than the target block size. The amount by which the base fee is adjusted is proportional to how far the current block size is from the target.

#### Calculating gas fees in practice <a href="#calculating-fees-in-practice" id="calculating-fees-in-practice"></a>

You can explicitly state how much you are willing to pay to get your transaction executed. However, most wallet providers will automatically set a recommended transaction fee (base fee + recommended priority fee) to reduce the amount of complexity burdened onto their users.

### WHY DO GAS FEES EXIST? <a href="#why-do-gas-fees-exist" id="why-do-gas-fees-exist"></a>

In short, gas fees help keep the BTC20 Smart Chain network secure. By requiring a fee for every computation executed on the network, we prevent bad actors from spamming the network. In order to avoid accidental or hostile infinite loops or other computational wastage in code, each transaction is required to set a limit to how many computational steps of code execution it can use. The fundamental unit of computation is "gas".

Although a transaction includes a limit, any gas not used in a transaction is returned to the user (i.e. `max fee - (base fee + tip)` is returned).

[![Diagram showing how unused gas is refunded](https://ethereum.org/static/c3638b26a1210d2c73a7ec2335c57351/302a4/gas-tx.png)](https://ethereum.org/static/c3638b26a1210d2c73a7ec2335c57351/302a4/gas-tx.png)

### WHAT IS THE GAS LIMIT? <a href="#what-is-gas-limit" id="what-is-gas-limit"></a>

The gas limit refers to the maximum amount of gas you are willing to consume on a transaction. More complicated transactions involving smart contracts require more computational work, so they require a higher gas limit than a simple payment. A standard BTCC transfer requires a gas limit of 21,000 units of gas.

For example, if you put a gas limit of 50,000 for a simple BTCC transfer, the EVM would consume 21,000, and you would get back the remaining 29,000. However, if you specify too little gas, for example, a gas limit of 20,000 for a simple BTCC transfer, the EVM will consume your 20,000 gas units attempting to fulfill the transaction, but it will not complete. The EVM then reverts any changes, but since the validator has already done 20k gas units worth of work, that gas is consumed.

### WHY CAN GAS FEES GET SO HIGH? <a href="#why-can-gas-fees-get-so-high" id="why-can-gas-fees-get-so-high"></a>

High gas fees are due to the popularity of BTC20 Smart Chain. If there's too much demand, users must offer higher tip amounts to try and outbid other users' transactions. A higher tip can make it more likely that your transaction will get into the next block. Also, more complex smart contract apps might be doing lots of operations to support their functions, making them consume a lot of gas.

### INITIATIVES TO REDUCE GAS COSTS <a href="#initiatives-to-reduce-gas-costs" id="initiatives-to-reduce-gas-costs"></a>

The BTC20 Smart Chain scalability upgrades should ultimately address some of the gas fee issues, which will, in turn, enable the platform to process thousands of transactions per second and scale globally.

### WHAT WAS EIP-1559? <a href="#what-was-the-london-upgrade-eip-1559" id="what-was-the-london-upgrade-eip-1559"></a>

Before the London Upgrade, BTC20 Smart Chain had fixed-sized blocks. In times of high network demand, these blocks operated at full capacity. As a result, users often had to wait for demand to reduce to get included in a block, which led to a poor user experience. The London Upgrade introduced variable-sized blocks to BTC20 Smart Chain.

Let's say Alice had to pay Bob 1 BTCC. In the transaction, the gas limit is 21,000 units, and the gas price is 200 gwei.

The total fee would have been: `Gas units (limit) * Gas price per unit` i.e `21,000 * 200 = 4,200,000 gwei` or 0.0042 BTCC

<br>


# NETWORKS

BTC20 Smart Chain networks are groups of connected computers that communicate using the BTC20 Smart Chain protocol. There is only one BTC20 Smart Chain Mainnet, but independent networks conforming to the same protocol rules can be created for testing and development purposes. There are many independent "networks" that conform to the protocol without interacting with each other. You can even start one locally on your own computer for testing your smart contracts and web3 apps.

Your BTC20 Smart Chain account will work across the different networks, but your account balance and transaction history won't carry over from the main BTC20 Smart Chain network. For testing purposes, it's useful to know which networks are available and how to get testnet BTCC to play around with. In general, for security considerations, it's not recommended to reuse mainnet accounts on testnets or vice versa..

### PUBLIC NETWORKS <a href="#public-networks" id="public-networks"></a>

Public networks are accessible to anyone in the world with an internet connection. Anyone can read or create transactions on a public blockchain and validate the transactions being executed. The consensus among peers decides on the inclusion of transactions and the state of the network.

#### BTC20 Smart Chain Mainnet <a href="#ethereum-mainnet" id="ethereum-mainnet"></a>

Mainnet is the primary public BTC20 Smart Chain production blockchain, where actual-value transactions occur on the distributed ledger.

When people and exchanges discuss BTCC prices, they're talking about Mainnet BTCC.

#### BTC20 Smart Chain Testnets <a href="#ethereum-testnets" id="ethereum-testnets"></a>

In addition to Mainnet, there are public testnets. These are networks used by protocol developers or smart contract developers to test both protocol upgrades as well as potential smart contracts in a production-like environment before deployment to Mainnet. Think of this as an analog to production versus staging servers.

You should test any contract code you write on a testnet before deploying to Mainnet. Among dapps that integrate with existing smart contracts, most projects have copies deployed to testnets.

**Mainnet**

| key              | value                                                                                |
| ---------------- | ------------------------------------------------------------------------------------ |
| network name     | BTC20 Smart Chain                                                                    |
| rpc url          | <p><https://rpc.bitcoincode.technology><br><https://rpc1.bitcoincode.technology></p> |
| chainId          | 963                                                                                  |
| currency symbol  | BTCC                                                                                 |
| currency decimal | 18                                                                                   |
| block explorer   | <https://scan.bitcoincode.technology>                                                |


# TERMINOLOGY

#### Blockchain <a href="#blockchain" id="blockchain"></a>

The sequence of all blocks that have been committed to the BTC20 Smart Chain network in the history of the network. So named because each block contains a reference to the previous block, which helps us maintain an ordering over all blocks (and thus over the precise history).

#### BTCC <a href="#eth" id="eth"></a>

BTCC is the native cryptocurrency of BTC20 Smart Chain. Users pay BTCC to other users to have their code execution requests fulfilled.

#### EVM <a href="#evm" id="evm"></a>

The EVM is the global virtual computer whose state every participant on the BTC20 Smart Chain network stores and agrees on. Any participant can request the execution of arbitrary code on the EVM; code execution changes the state of the EVM.

#### Nodes <a href="#nodes" id="nodes"></a>

The real-life machines which are storing the EVM state. Nodes communicate with each other to propagate information about the EVM state and new state changes. Any user can also request the execution of code by broadcasting a code execution request from a node. The BTC20 Smart Chain network itself is the aggregate of all BTC20 Smart Chain nodes and their communications.

#### Accounts <a href="#accounts" id="accounts"></a>

Where BTCC is stored. Users can initialize accounts, deposit BTCC into the accounts, and transfer BTCC from their accounts to other users. Accounts and account balances are stored in a big table in the EVM; they are a part of the overall EVM state.

#### Transactions <a href="#transactions" id="transactions"></a>

A "transaction request" is the formal term for a request for code execution on the EVM, and a "transaction" is a fulfilled transaction request and the associated change in the EVM state. Any user can broadcast a transaction request to the network from a node. For the transaction request to affect the agreed-upon EVM state, it must be validated, executed, and "committed to the network" by another node. Execution of any code causes a state change in the EVM; upon commitment, this state change is broadcast to all nodes in the network. Some examples of transactions:

* Send X BTCC from my account to Alice's account.
* Publish some smart contract code into EVM state.
* Execute the code of the smart contract at address X in the EVM, with arguments Y.

#### Blocks <a href="#blocks" id="blocks"></a>

The volume of transactions is very high, so transactions are "committed" in batches, or blocks. Blocks generally contain dozens to hundreds of transactions.

#### Smart contracts <a href="#smart-contracts" id="smart-contracts"></a>

A reusable snippet of code (a program) which a developer publishes into EVM state. Anyone can request that the smart contract code be executed by making a transaction request. Because developers can write arbitrary executable applications into the EVM (games, marketplaces, financial instruments, etc.) by publishing smart contracts, these are often also called dapps, or Decentralized Apps.


# COD20

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


# CATENA SWAP

It’s a protocol for trading and automated liquidity provision on BTC20 Smart Chain

<figure><img src="/files/3cQpIij3MLafvXdPZzMF" alt=""><figcaption></figcaption></figure>

The CATENA Protocol is a peer-to-peer system designed for exchanging cryptocurrencies (just like BTC20 Tokens on the Ethereum blockchain) on the BTC20 Smart Chain.&#x20;

The protocol is implemented as a set of persistent, non-upgradeable smart contracts; designed to prioritize censorship resistance, security, self-custody, and to function without any trusted intermediaries who may selectively restrict access. There are currently mainnet network of the Catena protocol is open.  which is viewable

[here](https://swap.bitcoincode.technology/)


# Concepts


# Protocol Overview

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

Anyone can become a liquidity provider (LP) for a pool by depositing an equivalent value of each underlying token in return for pool tokens. These tokens track pro-rata LP shares of the total reserves, and can be redeemed for the underlying assets at any time.

Pairs act as automated market makers, standing ready to accept one token for the other as long as the “constant product” formula is preserved. This formula, most simply expressed as `x * y = k`, states that trades must not change the product (`k`) of a pair’s reserve balances (`x` and `y`). Because `k` remains unchanged from the reference frame of a trade, it is often referred to as the invariant. This formula has the desirable property that larger trades (relative to reserves) execute at exponentially worse rates than smaller ones.

In practice, Catena swap applies a 0.30% fee to trades, which is added to reserves. As a result, each trade actually increases `k`. This functions as a payout to LPs, which is realized when they burn their pool tokens to withdraw their portion of total reserves. In the future, this fee may be reduced to 0.25%, with the remaining 0.05% withheld as a protocol-wide charge.


# Ecosystem Participants

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

The Catena swap ecosystem is primarily comprised of three types of users: liquidity providers, traders, and developers. Liquidity providers are incentivized to contribute BTC-20 tokens to common liquidity pools. Traders can swap these tokens for one another for a fixed [0.30% fee](https://docs.uniswap.org/contracts/v2/concepts/advanced-topics/fees) (which goes to liquidity providers). Developers can integrate directly with Catena swap smart contracts to power new and exciting interactions with tokens, trading interfaces, retail experiences, and more.

In total, interactions between these classes create a positive feedback loop, fueling digital economies by defining a common language through which tokens can be pooled, traded and used.

## Liquidity Providers

Liquidity providers, or LPs, are not a homogenous group:

* Passive LPs are token holders who wish to passively invest their assets to accumulate trading fees.
* Professional LPs are focused on market making as their primary strategy. They usually develop custom tools and ways of tracking their liquidity positions across different DeFi projects.
* Token projects sometimes choose to become LPs to create a liquid marketplace for their token. This allows tokens to be bought and sold more easily, and unlocks interoperability with other DeFi projects through Catena swap.
* Finally, some DeFi pioneers are exploring complex liquidity provision interactions like incentivized liquidity, liquidity as collateral, and other experimental strategies. Catena swap is the perfect protocol for projects to experiment with these kinds of ideas.

## Traders

There are a several categories of traders in the protocol ecosystem:

* Speculators use a variety of community built tools and products to swap tokens using liquidity pulled from the Catena swap protocol.
* Arbitrage bots seek profits by comparing prices across different platforms to find an edge. (Though it might seem extractive, these bots actually help equalize prices across broader BTC20 Smart Chain markets and keep things fair.)
* DAPP users buy tokens on Catena swap for use in other applications on BTC20 Smart Chain.
* Smart contracts that execute trades on the protocol by implementing swap functionality (from products like DEX aggregators to custom Solidity scripts).

In all cases, trades are subject to the same flat fee for trading on the protocol. Each is important for increasing the accuracy of prices and incentivizing liquidity.


# Glossary

#### Automated market maker[​](https://docs.uniswap.org/contracts/v2/concepts/protocol-overview/glossary#automated-market-maker) <a href="#automated-market-maker" id="automated-market-maker"></a>

An automated market maker is a smart contract on BTC20 Smart Chain that holds on-chain liquidity reserves. Users can trade against these reserves at prices set by an automated market making formula.

#### Constant product formula[​](https://docs.uniswap.org/contracts/v2/concepts/protocol-overview/glossary#constant-product-formula) <a href="#constant-product-formula" id="constant-product-formula"></a>

The automated market making algorithm used by Catena swap. x\*y=k.

#### BTC20[​](https://docs.uniswap.org/contracts/v2/concepts/protocol-overview/glossary#erc20) <a href="#erc20" id="erc20"></a>

BTC20 tokens are fungible tokens on BTC20 Smart Chain. Catena swap supports all standard BTC20 implementations.

#### Factory[​](https://docs.uniswap.org/contracts/v2/concepts/protocol-overview/glossary#factory) <a href="#factory" id="factory"></a>

A smart contract that deploys a unique smart contract for any BTC20/BTC20 trading pair.

#### Pair[​](https://docs.uniswap.org/contracts/v2/concepts/protocol-overview/glossary#pair) <a href="#pair" id="pair"></a>

A smart contract deployed from the Catena swap Factory that enables trading between two BTC20 tokens.

#### Pool[​](https://docs.uniswap.org/contracts/v2/concepts/protocol-overview/glossary#pool) <a href="#pool" id="pool"></a>

Liquidity within a pair is pooled across all liquidity providers.

#### Liquidity provider / LP[​](https://docs.uniswap.org/contracts/v2/concepts/protocol-overview/glossary#liquidity-provider--lp)\` <a href="#liquidity-provider--lp" id="liquidity-provider--lp"></a>

A liquidity provider is someone who deposits an equivalent value of two BTC20 tokens into the liquidity pool within a pair. Liquidity providers take on price risk and are compensated with fees.

#### Mid price[​](https://docs.uniswap.org/contracts/v2/concepts/protocol-overview/glossary#mid-price) <a href="#mid-price" id="mid-price"></a>

The price between what users can buy and sell tokens at a given moment. In Catena swap this is the ratio of the two BTC20 token reserves.

#### Price impact[​](https://docs.uniswap.org/contracts/v2/concepts/protocol-overview/glossary#price-impact) <a href="#price-impact" id="price-impact"></a>

The difference between the mid-price and the execution price of a trade.

#### Slippage[​](https://docs.uniswap.org/contracts/v2/concepts/protocol-overview/glossary#slippage) <a href="#slippage" id="slippage"></a>

The amount the price moves in a trading pair between when a transaction is submitted and when it is executed.

#### Core[​](https://docs.uniswap.org/contracts/v2/concepts/protocol-overview/glossary#core) <a href="#core" id="core"></a>

Smart contracts that are essential for Catena swap to exist. Upgrading to a new version of core would require a liquidity migration.

#### Periphery[​](https://docs.uniswap.org/contracts/v2/concepts/protocol-overview/glossary#periphery) <a href="#periphery" id="periphery"></a>

External smart contracts that are useful, but not required for Catena swap to exist. New periphery contracts can always be deployed without migrating liquidity.

#### Flash swap[​](https://docs.uniswap.org/contracts/v2/concepts/protocol-overview/glossary#flash-swap) <a href="#flash-swap" id="flash-swap"></a>

A trade that uses the tokens being purchased before paying for them.

#### `x * y = k`[​](https://docs.uniswap.org/contracts/v2/concepts/protocol-overview/glossary#x--y--k) <a href="#x--y--k" id="x--y--k"></a>

The constant product formula.

#### Invariant[​](https://docs.uniswap.org/contracts/v2/concepts/protocol-overview/glossary#invariant) <a href="#invariant" id="invariant"></a>

The "k" value in the constant product formula


# Core Concepts


# Swaps

<figure><img src="/files/HiNSKKuuufhVZXuDQW0n" alt=""><figcaption><p>Catena swap</p></figcaption></figure>

## Introduction

Token swaps in Catena swap are a simple way to trade one BTC-20 token for another.

For end-users, swapping is intuitive: a user picks an input token and an output token. They specify an input amount, and the protocol calculates how much of the output token they’ll receive. They then execute the swap with one click, receiving the output token in their wallet immediately.

In this guide, we’ll look at what happens during a swap at the protocol level in order to gain a deeper understanding of how Catena swap works.

Swaps in Catena are different from trades on traditional platforms. Catena swap does not use an order book to represent liquidity or determine prices. Catena swap uses an automated market maker mechanism to provide instant feedback on rates and slippage.

As we learned in Protocol Overview, each pair on Catena swap is actually underpinned by a liquidity pool. Liquidity pools are smart contracts that hold balances of two unique tokens and enforces rules around depositing and withdrawing them.

This rule is the constant product formula. When either token is withdrawn (purchased), a proportional amount of the other must be deposited (sold), in order to maintain the constant.

### Anatomy of a swap[​](https://docs.uniswap.org/contracts/v2/concepts/core-concepts/swaps#anatomy-of-a-swap) <a href="#anatomy-of-a-swap" id="anatomy-of-a-swap"></a>

At the most basic level, all swaps in Catena happen within a single function, aptly named `swap`:

```
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data);
```

## Receiving tokens

As is probably clear from the function signature, Catena swap requires `swap` callers to *specify how many output tokens they would like to receive* via the `amount{0,1}Out` parameters, which correspond to the desired amount of `token{0,1}`.

## Sending Tokens

What’s not as clear is how Catena swap *receives* tokens as payment for the swap. Typically, smart contracts which need tokens to perform some functionality require callers to first make an approval on the token contract, then call a function that in turn calls transferFrom on the token contract. This is *not* how V2 pairs accept tokens. Instead, pairs check their token balances at the *end* of every interaction. Then, at the beginning of the *next* interaction, current balances are differenced against the stored values to determine the amount of tokens that were sent by the current interactor. See the [whitepaper](https://docs.uniswap.org/whitepaper.pdf) for a justification of why this is the case.

The takeaway is that **tokens must be transferred to pairs before swap is called** (the one exception to this rule is [Flash Swaps](https://docs.uniswap.org/contracts/v2/concepts/core-concepts/flash-swaps)). This means that to safely use the `swap` function, it must be called from *another smart contract*. The alternative (transferring tokens to the pair and then calling `swap`) is not safe to do non-atomically because the sent tokens would be vulnerable to arbitrage.


# Pools

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

## Introduction

Each Catena swap liquidity pool is a trading venue for a pair of BTC20 tokens. When a pool contract is created, its balances of each token are 0; in order for the pool to begin facilitating trades, someone must seed it with an initial deposit of each token. This first liquidity provider is the one who sets the initial price of the pool. They are incentivized to deposit an equal *value* of both tokens into the pool. To see why, consider the case where the first liquidity provider deposits tokens at a ratio different from the current market rate. This immediately creates a profitable arbitrage opportunity, which is likely to be taken by an external party.

When other liquidity providers add to an existing pool, they must deposit pair tokens proportional to the current price. If they don’t, the liquidity they added is at risk of being arbitraged as well. If they believe the current price is not correct, they may arbitrage it to the level they desire, and add liquidity at that price.

## Pool tokens

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

Whenever liquidity is deposited into a pool, unique tokens known as *liquidity tokens* are minted and sent to the provider's address. These tokens represent a given liquidity provider's contribution to a pool. The proportion of the pool's liquidity provided determines the number of liquidity tokens the provider receives. If the provider is minting a new pool, the number of liquidity tokens they will receive will equal sqrt(x \* y), where x and y represent the amount of each token provided.

Whenever a trade occurs, a 0.3% fee is charged to the transaction sender. This fee is distributed *pro-rata* to all LPs in the pool upon completion of the trade.

To retrieve the underlying liquidity, plus any fees accrued, liquidity providers must "burn" their liquidity tokens, effectively exchanging them for their portion of the liquidity pool, plus the proportional fee allocation.

As liquidity tokens are themselves tradable assets, liquidity providers may sell, transfer, or otherwise use their liquidity tokens in any way they see fit.

## Why pools?

Catena swap is unique in that it doesn’t use an order book to derive the price of an asset or to match buyers and sellers of tokens. Instead, Catena swap uses what are called Liquidity Pools.

Liquidity is typically represented by discrete orders placed by individuals onto a centrally operated order book. A participant looking to provide liquidity or make markets must actively manage their orders, continuously updating them in response to the activity of others in the marketplace.

While order books are foundational to finance and work great for certain usecases, they suffer from a few important limitations that are especially magnified when applied to a decentralized or blockchain-native setting. Order books require intermediary infrastructure to host the orderbook and match orders. This creates points of control and adds additional layers of complexity. They also require active participation and management from market makers who usually use sophisticated infrastructure and algorithms, limiting participation to advanced traders. Order books were invented in a world with relatively few assets being traded, so it is not surprising they aren't ideal for an ecosystem where anyone can create their own token, and those tokens usually have low liquidity. In sum, with the infrastructural trade-offs presented by a platform like Ethereum, order books are not the native architecture for implementing a liquidity protocol on a blockchain.

Catena swap focuses on the strengths of Ethereum to reimagine token swaps from first principles.

A blockchain-native liquidity protocol should take advantage of the trusted code execution environment, the autonomous and perpetually running virtual machine, and an open, permissionless, and inclusive access model that produces an exponentially growing ecosystem of virtual assets.

It is important to reiterate that a Pool is just a smart contract, operated by users calling functions on it. Swapping tokens is calling `swap` on a Pool contract instance, while providing liquidity is calling `deposit`.

Just how end-users can interact with the Catena swap protocol through the Interface (which in turn interacts with the underlying contracts), developers can interact directly with the smart contracts and integrate Catena swap functionality into their own applications without relying on intermediaries or needing permission.


# Flash Swaps

flash swaps allow you to withdraw up to the full reserves of any BTC20 token on Catena swap and execute arbitrary logic at no upfront cost, provided that by the end of the transaction you either:

* pay for the withdrawn BTC20 tokens with the corresponding pair tokens
* return the withdrawn BTC20 tokens along with a small fee

Flash swaps are incredibly useful because they obviate upfront capital requirements and unnecessary order-of-operations constraints for multi-step transactions involving Catena swap.

#### Withdrawing BTCC from Catena swap[​](https://docs.uniswap.org/contracts/v2/concepts/core-concepts/flash-swaps#withdrawing-eth-from-uniswap) <a href="#withdrawing-eth-from-uniswap" id="withdrawing-eth-from-uniswap"></a>

The first step is to *optimistically* withdraw 1 BTCC from Catena swap via a flash swap. This will serve as the capital that we use to execute our arbitrage. Note that in this scenario, we're assuming that:

* 1 BTCC is the pre-calculated profit-maximizing trade
* The price has not changed on Catena swap since our calculation

It may be the case that we'd like to calculate the profit-maximizing trade on-chain at the moment of execution, which is robust to price movements. This can be somewhat complex, depending on the strategy being executed. However, one common strategy is trading as profitably as possible *against a fixed external price*.

### Instant Leverage[​](https://docs.uniswap.org/contracts/v2/concepts/core-concepts/flash-swaps#instant-leverage) <a href="#instant-leverage" id="instant-leverage"></a>

Flash swaps can be used to improve the efficiency of levering up using lending protocols and Catena swap.

Consider Maker in its simplest form: a system which accepts BTCC as collateral and allows USDT to be minted against it while ensuring that the value of the BTCC never drops below 150% of the value of the USDT.

Say we use this system to deposit a principal amount of 3 BTCC, and mint the maximum amount of USDT. At a price of 1 BTCC / 200 USDT, we receive 400 USDT. In theory, we could lever this position up by selling the USDT for more BTCC, depositing this BTCC, minting the maximum amount of USDT (which would be less this time), and repeating until we've reached our desired leverage level.

It's quite simple to use Catena swap as a liquidity source for the USDT-to-BTCC component of this process. However, looping through protocols in this way isn't particularly elegant, and can be gas-intensive.

Luckily, flash swaps enable us to withdraw the *full* BTCC amount upfront. If we wanted 2x leverage against our 3 BTCC principal, we could simply request 3 BTCC in a flash swap and deposit 6 BTCC into Maker. This gives us the ability to mint 800 USDT. If we mint as much as we need to cover our flash swap (say 605), the remainder serves as a safety margin against price movements.


# Oracles

## Introduction

A price oracle is any tool used to view price information about a given asset. When you look at stock prices on your phone, you are using your phone as a price oracle. Similarly, the app on your phone relies on devices to retrieve price information - likely several, which are aggregated and then displayed to you, the end-user. These are price oracles as well.

When building smart contracts that integrate with DeFi protocols, developers will inevitably run into the price oracle problem. What is the best way to retrieve the price of a given asset on-chain?

Many oracle designs on BTC20 Smart Chain have been implemented on an ad-hoc basis, with varying degrees of decentralization and security. Because of this, the ecosystem has witnessed numerous high-profile hacks where the oracle implementation is the primary attack vector.&#x20;

Catena swap enables developers to build highly decentralized and manipulation-resistant on-chain price oracles, which may solve many of the demands necessary for building robust protocols.

## Catena swap solution

Catena swap includes several improvements for supporting manipulation-resistant public price feeds. First, every pair measures (but does not store) the market price at the beginning of each block, before any trades take place. This price is expensive to manipulate because it is set by the last transaction, whether it is a mint, swap, or burn, in a previous block.

**To set the measured price to one that is out of sync with the global market price, an attacker has to make a bad trade at the end of a previous block** , typically with no guarantee that they will arbitrage it back in the next block. Attackers will lose money to arbitrageurs unless they can “selfishly” mine two blocks in a row.&#x20;

Unfortunately, this alone is not enough. If significant value settles based on the price resulting from this mechanism, an attack’s profit will likely outweigh the loss.

Instead, Catena swap adds this end-of-block price to a single cumulative-price variable in the core contract weighted by the amount of time this price existed. **This variable represents a sum of the swap price for every second in the entire history of the contract.**

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

This variable can be used by external contracts to track accurate time-weighted average prices (TWAPs) across any time interval.

The TWAP is constructed by reading the cumulative price from an BTC20 token pair at the beginning and at the end of the desired interval. The difference in this cumulative price can then be divided by the length of the interval to create a TWAP for that period.

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

TWAPs can be used directly or as the basis for moving averages (EMAs and SMAs) as needed.

A few notes:

* For a 10-minute TWAP, sample once every 10 minutes. For a 1-week TWAP, sample once every week.
* For a simple TWAP, the cost of manipulation increases (approx. linear) with liquidity on Catena swap, as well as (approx. linear) with the length of time over which you average.
* The Cost of an attack is relatively simple to estimate. Moving the price 5% on a 1-hour TWAP is approximately equal to the amount lost to arbitrage and fees for moving the price 5% every block for 1 hour.

There are some nuances that are good to be aware of when using Catena swap as an oracle, especially where manipulation resistance is concerned. The [whitepaper](https://docs.uniswap.org/whitepaper.pdf) elaborates on some of them. Additional oracle-focused developer guides and documentation will be released soon.

In the meantime, check out our [example implementation](https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleOracleSimple.sol) of a 24 hr TWAP Oracle built on Catena swap!

### Manipulation resistance[​](https://docs.uniswap.org/contracts/v2/concepts/core-concepts/oracles#manipulation-resistance) <a href="#manipulation-resistance" id="manipulation-resistance"></a>

The cost of manipulating the price for a specific time period can be roughly estimated as the amount lost to arbitrage and fees every block for the entire period. For larger liquidity pools and over longer time periods, this attack is impractical, as the cost of manipulation typically exceeds the value at stake.

Other factors, such as network congestion, can reduce the cost of attack. For a more in-depth review of the security of Catena swap price oracles.


# Guides


# Implement a Swap

When trading from a smart contract, the most important thing to keep in mind is that access to an external price source is *required*. Without this, trades can be frontrun for considerable loss.

## Using the Router

The easiest way to safely swap tokens is to use the router, which provides a variety of methods to safely swap to and from different assets. You'll notice that there is a function for each permutation of swapping to/from an exact amount of BTCC/tokens.

First you must use an external price source to calculate the safety parameters for the function you'd like to call. This is either a minimum amount received when selling an exact input or the maximum amount you are willing to pay when a buying an exact output amount

It is also important to ensure that your contract controls enough BTCC/tokens to make the swap, and has granted approval to the router to withdraw this many tokens.

### transferFrom[​](https://docs.uniswap.org/contracts/v2/guides/smart-contract-integration/trading-from-a-smart-contract#transferfrom) <a href="#transferfrom" id="transferfrom"></a>

Before swapping, our smart contracts needs to be in control of 50 USDT. The easiest way to accomplish this is by calling `transferFrom` on USDT with the owner set to `msg.sender`:

```
uint amountIn = 50 * 10 ** DAI.decimals();
require(USDT.transferFrom(msg.sender, address(this), amountIn), 'transferFrom failed.');
```

### approve[​](https://docs.uniswap.org/contracts/v2/guides/smart-contract-integration/trading-from-a-smart-contract#approve) <a href="#approve" id="approve"></a>

Now that our contract owns 50 USDT, we need to approve to the router to withdraw this USDT:

```
require(USDT.approve(address(router), amountIn), 'approve failed.');
```

## Safety Considerations

Because BTC20 Smart Chain transactions occur in an adversarial environment, smart contracts that do not perform safety checks *can be exploited for profit*. If a smart contract assumes that the current price on Catena swap is a "fair" price without performing safety checks, *it is vulnerable to manipulation*. A bad actor could e.g. easily insert transactions before and after the swap (a "sandwich" attack) causing the smart contract to trade at a much worse price, profit from this at the trader's expense, and then return the contracts to their original state. (One important caveat is that these types of attacks are mitigated by trading in extremely liquid pools, and/or at low values.)

The best way to protect against these attacks is to use an external price feed or "price oracle". The best "oracle" is simply *traders' off-chain observation of the current price*, which can be passed into the trade as a safety check. This strategy is best for situations *where users initiate trades on their own behalf*.


# Providing Liquidity

### Introduction[​](https://docs.uniswap.org/contracts/v2/guides/smart-contract-integration/providing-liquidity#introduction) <a href="#introduction" id="introduction"></a>

When providing liquidity from a smart contract, the most important thing to keep in mind is that tokens deposited into a pool at any rate other than the current reserve ratio *are vulnerable to being arbitraged*. As an example, if the ratio of x:y in a pair is 10:2 (i.e. the price is 5), and someone naively adds liquidity at 5:2 (a price of 2.5), the contract will simply accept all tokens (changing the price to 3.75 and opening up the market to arbitrage), but only issue pool tokens entitling the sender to the amount of assets sent at the proper ratio, in this case 5:1. To avoid donating to arbitrageurs, it is imperative to add liquidity at the current price. Luckily, it's easy to ensure that this condition is met!

### Using the Router[​](https://docs.uniswap.org/contracts/v2/guides/smart-contract-integration/providing-liquidity#using-the-router) <a href="#using-the-router" id="using-the-router"></a>

The easiest way to safely add liquidity to a pool is to use the router, which provides simple methods to safely add liquidity to a pool. If the liquidity is to be added to an BTC-20/BTC-20 pair, use addLiquidity.&#x20;

These methods both require the caller to commit to a *belief about the current price*, which is encoded in the `amount*Desired` parameters. Typically, it's fairly safe to assume that the current fair market price is around what the current reserve ratio is for a pair (because of arbitrage). So, if a user wants to add 1 BTCC to a pool, and the current USDT/WBTCC ratio of the pool is 200/1, it's reasonable to calculate that 200 USDT must be sent along with the BTCC, which is an implicit commitment to the price of 200 USDT/1 WBTCC. However, it's important to note that this must be calculated *before the transaction is submitted*. It is *not safe* to look up the reserve ratio from within a transaction and rely on it as a price belief, as this ratio can be cheaply manipulated to your detriment.

However, it is still possible to submit a transaction which encodes a belief about the price which ends up being wrong because of a larger change in the true market price before the transaction is confirmed. For that reason, it's necessary to pass an additional set of parameters which encode the caller's tolerance to price changes. These `amount*Min` parameters should typically be set to percentages of the calculated desired price. So, at a 1% tolerance level, if our user sends a transaction with 1 BTCC and 200 USDT, `amountETHMin` should be set to e.g. .99 BTCC, and `amountTokenMin` should be set to 198 USDT. This means that, at worst, liquidity will be added at a rate between 198 USDT/1 BTCC and 202.02 USDT/1 BTCC (200 USDT/.99 BTCC).

Once the price calculations have been made, it's important to ensure that your contract a) controls at least as many tokens/BTCC as were passed as `amount*Desired` parameters, and b) has granted approval to the router to withdraw this many tokens.<br>


# Advance Topics


# Fees

### Liquidity provider fees[​](https://docs.uniswap.org/contracts/v2/concepts/advanced-topics/fees#liquidity-provider-fees) <a href="#liquidity-provider-fees" id="liquidity-provider-fees"></a>

There is a **0.3%** fee for swapping tokens. **This fee is split by liquidity providers proportional to their contribution to liquidity reserves.**

Swapping fees are immediately deposited into liquidity reserves. This increases the value of liquidity tokens, functioning as a payout to all liquidity providers proportional to their share of the pool. Fees are collected by burning liquidity tokens to remove a proportional share of the underlying reserves.

Since fees are added to liquidity pools, the invariant increases at the end of every trade. Within a single transaction, the invariant represents `token0_pool / token1_pool` at the end of the previous transaction.

### Protocol Fees[​](https://docs.uniswap.org/contracts/v2/concepts/advanced-topics/fees#protocol-fees) <a href="#protocol-fees" id="protocol-fees"></a>

At the moment there are no protocol fees. However, it is possible for a 0.05% fee to be turned on in the future.

### Protocol Charge Calculation[​](https://docs.uniswap.org/contracts/v2/concepts/advanced-topics/fees#protocol-charge-calculation) <a href="#protocol-charge-calculation" id="protocol-charge-calculation"></a>

In the future, it is possible that a protocol-wide charge of 0.05% per trade will take effect. This represents ⅙th (16.6̅%) of the 0.30% fee. The fee is in effect if feeTo is not `address(0)` (`0x0000000000000000000000000000000000000000`), indicating that feeTo is the recipient of the charge.

This amount would not affect the fee paid by traders, but would affect the amount received by liquidity providers.


# Pricing

## How are prices determined?

As we learned in Protocol Overview, each pair on Catena swap is actually underpinned by a liquidity pool. Liquidity pools are smart contracts that hold balances of two unique tokens and enforces rules around depositing and withdrawing them. The primary rule is the constant product formula. When a token is withdrawn (bought), a proportional amount must be deposited (sold) to maintain the constant. The ratio of tokens in the pool, in combination with the constant product formula, ultimately determine the price that a swap executes at.

## Pricing Trades

When swapping tokens on Catena swap, it's common to want to receive as many output tokens as possible for an *exact input amount*, or to pay as few input tokens as possible for an *exact output amount*. In order to calculate these amounts, a contract must look up the *current reserves* of a pair, in order to understand what the current price is. However, it is *not safe to perform this lookup and rely on the results without access to an external price*.

Say a smart contract naively wants to send 10 USDT to the USDT/WBTCC pair and receive as much WBTCC as it can get, given the current reserve ratio. If, when called, the naive smart contract simply looks up the current price and executes the trade, it is *vulnerable to front-running and will likely suffer an economic loss*. To see why, consider a malicious actor who sees this transaction before it is confirmed. They could execute a swap which dramatically changes the USDT/WBTCC price immediately before the naive swap goes through, wait for the naive swap to execute at a bad rate, and then swap to change the price back to what it was before the naive swap. This attack is fairly cheap and low-risk, and can typically be performed for a profit.

To prevent these types of attacks, it's vital to submit swaps *that have access to knowledge about the "fair" price their swap should execute at*. In other words, swaps need access to an *oracle*, to be sure that the best execution they can get from  Catena swap is close enough to what the oracle considers the "true" price. While this may sound complicated, the oracle can be as simple as an *off-chain observation of the current market price of a pair*. Because of arbitrage, it's typically the case that the ratio of the intra-block reserves of a pair is close to the "true" market price. So, if a user submits a trade with this knowledge in mind, they can ensure that the losses due to front-running are tightly bounded. This is how, for example, the  Catena swap frontend ensure trade safety. It calculates the optimal input/output amounts given observed intra-block prices, and uses the router to perform the swap, which guarantees the swap will execute at a rate no less that `x`% worse than the observed intra-block rate, where `x` is a user-specified slippage tolerance (0.5% by default).

### Exact Input[​](https://docs.uniswap.org/contracts/v2/concepts/advanced-topics/pricing#exact-input) <a href="#exact-input" id="exact-input"></a>

If you'd like to send an exact amount of input tokens in exchange for as many output tokens as possible, you'll want to use getAmountsOut.&#x20;

### Exact Output[​](https://docs.uniswap.org/contracts/v2/concepts/advanced-topics/pricing#exact-output) <a href="#exact-output" id="exact-output"></a>

If you'd like to receive an exact amount of output tokens for as few input tokens as possible, you'll want to use getAmountsIn.&#x20;


# Security

### Audit & Formal Verification <a href="#audit-and-formal-verification" id="audit-and-formal-verification"></a>

TODO

### Bug Bounty <a href="#bug-bounty" id="bug-bounty"></a>

​

We prepare tons of money to reward bug reporter.


# BIFROST BRIDGE

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


# INTRO

### What Is A Blockchain Bridge?

Blockchain bridges work similarly to real bridges in the physical world. However, instead of connecting physical locations, bridges in crypto connect two different blockchains. This connection is important because, without a bridge, blockchains are siloed environments that cannot communicate with each other. This is because each network has its own set of rules, governance mechanisms, native assets, and data that are incompatible with the other blockchains. However, with a bridge between two blockchains, it becomes possible to transfer crypto-assets and arbitrary data between them. Thus, bridges are key for interoperability in the crypto ecosystem and are necessary to make different blockchain networks compatible with each other.

### NEED FOR BRIDGES <a href="#need-for-bridges" id="need-for-bridges"></a>

Bridges exist to connect blockchain networks. They enable connectivity and interoperability between blockchains.

Blockchains exist in siloed environments, meaning there is no way for blockchains to trade and communicate with other blockchains naturally. As a result, while there could be significant activity and innovation within an ecosystem, it is limited by the lack of connectivity and interoperability with other ecosystems.

Bridges offer a way for isolated blockchain environments to connect with each other. They establish a transportation route between blockchains where tokens, messages, arbitrary data, and even smart contract calls can be transferred from one chain to another.

### BENEFITS OF BRIDGES <a href="#benefits-of-bridges" id="benefits-of-bridges"></a>

Put simply, bridges unlock numerous use cases by allowing blockchain networks to exchange data and move assets between them.

Blockchains have unique strengths, weaknesses, and approaches to building applications (such as speed, throughput, costliness, etc.). Bridges help the development of the overall crypto ecosystem by enabling blockchains to leverage the innovations of each other.

For developers, bridges enable the following:

* the transfer of any data, information, and assets across chains.
* unlocking new features and use cases for protocols as bridges expand the design space for what protocols can offer.&#x20;
* the opportunity to leverage the strengths of different blockchains.&#x20;
* collaboration among developers from various blockchain ecosystems to build new products.
* attracting users and communities from various ecosystems to their dapps.

### &#x20;<a href="#how-do-bridges-work" id="how-do-bridges-work"></a>

### &#x20;<a href="#bridge-types" id="bridge-types"></a>

### TRADE-OFFS TO CONSIDER <a href="#trade-offs" id="trade-offs"></a>

With bridges, there are no perfect solutions. Rather, there are only trade-offs made to fulfill a purpose. Developers and users can evaluate bridges based on the following factors:

* **Security –** Who verifies the system? Bridges secured by external validators are typically less secure than bridges that are locally or natively secured by the blockchain’s validators.
* **Convenience –** How long does it take to complete a transaction, and how many transactions did a user need to sign? For a developer, how long does it take to integrate a bridge, and how complex is the process?
* **Connectivity –** What are the different destination chains a bridge can connect (i.e., rollups, sidechains, other layer 1 blockchains, etc.), and how hard is it to integrate a new blockchain?
* **Ability to pass more complex data –** Can a bridge enable the transfer of messages and more complex arbitrary data across chains, or does it only support cross-chain asset transfers?
* **Cost-effectiveness –** How much does it cost to transfer assets across chains via a bridge? Typically, bridges charge a fixed or variable fee depending on gas costs and the liquidity of specific routes. It is also critical to evaluate the cost-effectiveness of a bridge based on the capital required to ensure its security.

At a high level, bridges can be categorized as trusted and trustless.

* **Trusted –** Trusted bridges are externally verified. They use an external set of verifiers (Federations with multi-sig, multi-party computation systems, oracle network) to send data across chains. As a result, they can offer great connectivity and enable fully generalized message passing across chains. They also tend to perform well with speed and cost-effectiveness. This comes at the cost of security, as users have to rely on the security of the bridge.
* **Trustless –** These bridges rely on the blockchains they are connecting and their validators to transfer messages and tokens. They are 'trustless' because they do not add new trust assumptions (in addition to the blockchains). As a result, trustless bridges are considered to be more secure than trusted bridges.

To evaluate trustless bridges based on other factors, we must break them down into generalized message passing bridges and liquidity networks.

* **Generalized message passing bridges –** These bridges excel with security and the ability to transfer more complex data across chains. Typically, they are also good with cost-effectiveness. However, these strengths generally come at the cost of connectivity for light client bridges (ex: IBC) and speed drawbacks for optimistic bridges (ex: Nomad) that use fraud proofs.
* **Liquidity networks –** These bridges use atomic swaps for transferring assets and are locally verified systems (i.e., they use the underlying blockchains’ validators to verify transactions). As a result, they excel with security and speed. Moreover, they are considered comparatively cost-effective and offer good connectivity. However, the major tradeoff is their inability to pass more complex data – as they don’t support cross-chain message passing.

### RISK WITH BRIDGES <a href="#risk-with-bridges" id="risk-with-bridges"></a>

Bridges account for the top three [biggest hacks in DeFi(opens in a new tab)](https://rekt.news/leaderboard/) and are still in the early stages of development. Using any bridge carries the following risks:

* **Smart contract risk –** While many bridges have successfully passed audits, all it takes is one flaw in a smart contract for assets to be exposed to hacks (ex: [Solana’s Wormhole Bridge(opens in a new tab)](https://rekt.news/wormhole-rekt/)).
* **Systemic financial risks** – Many bridges use wrapped assets to mint canonical versions of the original asset on a new chain. This exposes the ecosystem to systemic risk, as we have seen wrapped versions of tokens exploited.
* **Counterparty risk –** Some bridges utilize a trusted design that requires users to rely on the assumption that validators will not collude to steal user funds. The need for users to trust these third-party actors exposes them to risks such as rug pulls, censorship, and other malicious activities.
* **Open issues –** Given that bridges are in the nascent stages of development, there are many unanswered questions related to how bridges will perform in different market conditions, like times of network congestion and during unforeseen events such as network-level attacks or state rollbacks. This uncertainty poses certain risks, the degree of which is still unknown.

### HOW CAN DAPPS USE BRIDGES? <a href="#how-can-dapps-use-bridges" id="how-can-dapps-use-bridges"></a>

Here are some practical applications that developers can consider about bridges and taking their dapp cross-chain:

#### Integrating bridges <a href="#integrating-bridges" id="integrating-bridges"></a>

For developers, there are many ways to add support for bridges:

1. **Building your own bridge –** Building a secure and reliable bridge is not easy, especially if you take a more trust-minimized route. Moreover, it requires years of experience and technical expertise related to scalability and interoperability studies. Additionally, it would require a hands-on team to maintain a bridge and attract sufficient liquidity to make it feasible.
2. **Showing users multiple bridge options –** Many [dapps](https://ethereum.org/en/developers/docs/dapps/) require users to have their native token to interact with them. To enable users to access their tokens, they offer different bridge options on their website. However, this method is a quick fix to the problem as it takes the user away from the dapp interface and still requires them to interact with other dapps and bridges. This is a cumbersome onboarding experience with the increased scope of making mistakes.
3. **Integrating a bridge –** This solution doesn’t require the dapp to send users to the external bridge and DEX interfaces. It allows dapps to improve the user onboarding experience. However, this approach has its limitations:
   * Assessment and maintenance of bridges are hard and time-consuming.
   * Selecting one bridge creates a single point of failure and dependency.
   * The dapp is limited by the bridge’s capabilities.
   * Bridges alone might not be enough. Dapps might need DEXs to offer more functionality such as cross-chain swaps.
4. **Integrating multiple bridges –** This solution solves many problems associated with integrating a single bridge. However, it also has limitations, as integrating multiple bridges is resource-consuming and creates technical and communication overheads for developers—the scarcest resource in crypto.
5. **Integrating a bridge aggregator –** Another option for dapps is integrating a bridge aggregation solution that gives them access to multiple bridges. Bridge aggregators inherit the strengths of all the bridges and thus are not limited by any single bridge’s capabilities. Notably, the bridge aggregators typically maintain the bridge integrations, which saves the dapp from the hassle of staying on top of the technical and operational aspects of a bridge integration.

That being said, bridge aggregators also have their limitations. For instance, while they can offer more bridge options, many more bridges are typically available in the market other than those offered on the aggregator's platform. Moreover, just like bridges, bridge aggregators are also exposed to smart contract and technology risks (more smart contracts = more risks).

<br>


# BRIDGES TYPE?

While there are many [types of bridge designs(opens in a new tab)](https://li.fi/knowledge-hub/blockchain-bridges-and-classification/), three ways to facilitate the cross-chain transfer of assets stand out:

* **Lock and mint –** Lock assets on the source chain and mint assets on the destination chain.
* **Burn and mint –** Burn assets on the source chain and mint assets on the destination chain.
* **Atomic swaps –** Swap assets on the source chain for assets on the destination chain with another party.

Bridges can usually be classified into one of the following buckets:

* **Native bridges –** These bridges are typically built to bootstrap liquidity on a particular blockchain, making it easier for users to move funds to the ecosystem. For example, the Arbitrum Bridge is built to make it convenient for users to bridge from Ethereum Mainnet to Arbitrum. Other such bridges include Polygon PoS Bridge, Optimism Gateway, etc.
* **Validator or oracle based bridges –** These bridges rely on an external validator set or oracles to validate cross-chain transfers. Examples: Multichain and Across.
* **Generalized message passing bridges –** These bridges can transfer assets, along with messages and arbitrary data across chains. Examples: Nomad and LayerZero.
* **Liquidity networks –** These bridges primarily focus on transferring assets from one chain to another via atomic swaps. Generally, they don’t support cross-chain message passing. Examples: Connext and Hop.

### Why Are There Different Types Of Bridges?

Bridges essentially enable communication between different blockchains. And, just like with complex math problems, when you take a look at different bridging solutions in the crypto ecosystem, you will find that there is no one way of enabling communication between blockchains. Bridges have different designs with unique strengths and trade-offs, and thus, there are a plethora of options when it comes to which bridge can be used to communicate between two blockchain networks. Let’s dig a little deeper into how communication works.

Bridges work by establishing communication channels between two blockchains. In an ideal world, blockchains would just talk to each other but in reality, that’s not possible because one blockchain doesn’t store the state of the other.


# BIFROST BRIDGE

BIFROST Bridge was launched in July 2023. The bridge replaced a previous bridge design, the BTC20 Smart Chain-TRON Bridge. Along with shortening the name (BTC20 - TRON), saw a 5x decrease in fees, stronger security, and faster finality for bridge users.Built with retail users firmly in mind, Bifrost bridge give users a simple interface and seamless experience moving assets to and from the BTC20 Smart Chain ecosystem. Bifrost Bridge adds trust assumptions via a wardens-based system that moves assets cross-chain affordably and efficiently. the bridge prides itself on the following characteristics:

* Security — Bifrost is audited and is built with security-first technologies
* Cost-Effectiveness — minimizing the cost of bridging assets is prioritized
* Speed — a transaction should execute in the least amount of time possible
* Transparency — users are informed of their transfer status at every step of the way
* Intuition — a clean UI allows crypto users (new and old) to utilize the system
* Ecosystem support — easy integration with Avalanche tools
* Multi-chain — supporting multiple blockchains and assets


