# Introduction

CityCoins are cryptocurrencies that allow you to support your favorite cities while earning Stacks and Bitcoin.

Welcome, we're glad you found us! CityCoins are powered by [Stacks](https://stacks.co), a blockchain that enables smart contracts on the Bitcoin network.

CityCoins have four main features: **Activation**, **Mining**, **Stacking,** and **Programming.**

* [**Activation:**](/core-protocol/registration-and-activation) CityCoins only exist through mining, which does not begin until 20 independent wallets signal activation after the contract is deployed. No ICO, no pre-sale, no pre-mine.
* [**Mining:**](/core-protocol/mining-citycoins) Anyone can mine CityCoins by submitting STX into a CityCoins smart contract on the Stacks blockchain. 30% of the STX that miners forward is sent directly to a reserved wallet for the city.
* [**Stacking:**](/core-protocol/stacking-citycoins) Anyone can Stack CityCoins by locking them in a CityCoins smart contract for selected reward cycles, and receive a portion of the remaining 70% of the STX sent by miners.
* [**Programming:**](/developer-resources/general) using [Clarity](https://clarity-lang.org), the language that powers smart contracts on Stacks, CityCoins open up endless possibilities for utility, including new opportunities for developers, entrepreneurs, residents, and more.

Please use the navigation on the left to learn more!


# What are CityCoins?

A quick intro to the CityCoins protocol.

CityCoins give communities the power to improve their cities, while providing crypto rewards to individual contributors and city governments alike. Each city has their own coin, starting with the launch of MiamiCoin (MIA) in August of 2021.

A CityCoin provides an ongoing crypto revenue stream for a city, and can be mined or bought by individuals who want to support the city and benefit from the protocol. There is no pre-mine, pre-sale, or ICO, and new CityCoins are only mined into existence.

A city can elect to use its growing crypto treasury to benefit the city and its constituents — think new public spaces, improvements to infrastructure, hosting city events, recruiting startups, and more.

## What can I do with CityCoins?

With any CityCoin, you can mine it, hold it, stack it to earn STX, borrow it, lend it, and program it. Built on open source software, CityCoins are a new way for developers to create applications and experiment with innovative use cases.

## **Why are CityCoins built on Stacks?**

[Stacks](https://www.stacks.co/) enables smart contracts and apps on Bitcoin. It enables a function called “[Stacking](https://stacks.org/stacking)“, which earns BTC when you lock STX in the protocol. CityCoins leverage a similar Stacking function to enable CityCoin holders to Stack their CityCoins to earn STX, which can be further Stacked to earn BTC.


# How do I get started?

How to get started with Stacks and CityCoins.

## Stacks **Wallets**

CityCoins follow the [SIP-010 fungible token standard](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md) on the Stacks blockchain, which is a fancy way of saying you'll need a Stacks wallet to interact with them.

The currently supported wallets for CityCoins are listed below.

|                                                       |                                                       |                                             |
| ----------------------------------------------------- | :---------------------------------------------------: | :-----------------------------------------: |
| **Features**                                          | [**Hiro Wallet**](https://hiro.so/wallet/install-web) | [**Xverse Wallet**](https://www.xverse.app) |
| <p>Desktop Support</p><p><em>(Win/Mac/Linux)</em></p> |                           ⚠                           |                                             |
| <p>Web Support</p><p><em>(Chrome/Firefox)</em></p>    |                           ✅                           |                      ✅                      |
| <p>Mobile Support</p><p><em>(Android/iPhone)</em></p> |                                                       |                      ✅                      |
| <p>Hardware Support<br>(Ledger only)</p>              |                           ✅                           |                                             |
| Activation                                            |                           ✅                           |                      ✅                      |
| Mining                                                |                           ✅                           |                      ✅                      |
| Stacking                                              |                           ✅                           |                      ✅                      |
| Send                                                  |                           ✅                           |                      ✅                      |
| Receive                                               |                           ✅                           |                      ✅                      |

{% hint style="warning" %}
The desktop version of the Hiro Wallet does not support displaying, sending, or receiving CityCoins at this time.
{% endhint %}

## **How to Acquire Stacks (STX)**

All transactions on the Stacks blockchain require Stacks (STX) as fuel.\
\
To acquire Stacks, please see the [market list on CoinMarketCap](https://coinmarketcap.com/currencies/stacks/markets/) for supported exchanges.

## **How to HODL CityCoins**

All CityCoins are fungible tokens on Stacks, meaning they are stored as part of your Stacks account and viewable in the [Stacks Explorer](https://explorer.stacks.co) by searching for your Stacks address.

{% hint style="info" %}
When sending or receiving CityCoins, use the Stacks address of the sender and recipient. A memo is generally only required when transferring to an exchange.
{% endhint %}


# General

General resources centered around the CityCoins ecosystem.

## Community Connections

CityCoins are ultimately powered by the community around them. Connect with fellow CityCoiners!

[Blog](https://citycoins.co/blog) | [Discord](https://chat.citycoins.co) | [FAQ](https://www.citycoins.co/citycoins-faq) | [Twitter](https://twitter.com/minecitycoins) | [Website](https://citycoins.co)

## Community Tools

{% hint style="info" %}
See something missing or incorrect? Come [join the Discord](https://chat.citycoins.co) and let us know in the #docs channel!
{% endhint %}

<table><thead><tr><th>Link</th><th width="172.33333333333331">Creator</th><th>Description</th></tr></thead><tbody><tr><td><a href="https://www.catamaranswaps.org/">Catamaran Swaps</a></td><td><a href="https://friedger.de/">Friedger</a></td><td>Trustless swaps between Bitcoin, Stacks, and SIP-010 tokens (<a href="https://thetutorials.notion.site/thetutorials/How-to-use-Catamaranswaps-c9c0b864bdfc4f01b656be468b15d526">tutorial here</a>)</td></tr><tr><td><a href="https://cryptoacptd.com/">cryptoacptd</a></td><td><a href="https://twitter.com/cryptoacptd">cryptoacptd.btc</a></td><td>Directory of businesses in Miami that accept crypto, including MIA</td></tr><tr><td><a href="https://fatstx.github.io/">FATSTX</a></td><td><a href="https://twitter.com/EPARROT">eparrot</a> &#x26; <a href="https://twitter.com/FoRaGeRr">foragerr</a></td><td>Analyze wallet transactions, stacking data, and see estimated dates for important CItyCoins milestones</td></tr><tr><td><a href="https://gitlab.com/riot.ai/clarity-pool-tools/-/blob/master/tool-scripts/analysis-citycoins.ts">MiamiCoin Analysis Script</a></td><td><a href="https://friedger.de/">Friedger</a></td><td>A tool to download all transactions for the MiamiCoin core and token contracts</td></tr><tr><td><a href="https://miamining.com">MiamiCoin Block Explorer</a></td><td><a href="https://mobile.twitter.com/jamilbtc">jamil.btc</a></td><td>Block explorer and statistics for MiamiCoin</td></tr><tr><td><a href="https://docs.google.com/spreadsheets/d/1pR9q6MAFrPjXoDNjQFMOZW6MQE1piTsXausYQyABWqk/edit#gid=0">Mining Calculator</a></td><td><a href="https://twitter.com/benoror">benoror.btc</a></td><td>Google spreadsheet with probability calculations based on block commits</td></tr><tr><td><a href="https://mining.nyc">NewYorkCityCoin Block Explorer</a></td><td><a href="https://mobile.twitter.com/jamilbtc">jamil.btc</a></td><td>Block explorer and statistics for NewYorkCityCoin</td></tr><tr><td><a href="https://thetutorials.notion.site/How-to-mine-NYC-727a74c8d8964d1aa7d110ff19929272">NewYorkCityCoin Mining Tutorial</a></td><td><code>@pneppl</code></td><td>A mining tutorial hosted as a Notion site</td></tr><tr><td><a href="https://stacksonchain.com/dashboards/MiamiCoin-($MIA)/10">StacksOnChain: MIA Dashboard</a></td><td><a href="https://twitter.com/anononchain">stacksonchain.btc</a></td><td>Several statistics and charts created for MiamiCoin</td></tr><tr><td><a href="https://stacksonchain.com/dashboards/NYC-Summary/31">StacksOnChain: NYC Dashboard</a></td><td><a href="https://twitter.com/anononchain">stacksonchain.btc</a></td><td>Several statistics and charts created for NewYorkCityCoin</td></tr><tr><td><a href="https://stacksonchain.com/tokenwhales">StacksOnChain: Whales</a></td><td><a href="https://twitter.com/anononchain">stacksonchain.btc</a></td><td>Dashboard showing the top ten largest wallet balances by Stacks address for the selected token</td></tr></tbody></table>

## Brand Resources

CityCoins brand assets are available on the CDN hosted through CloudFlare Pages.

Anything found in [this GitHub repo](https://github.com/citycoins/cdn) can also be found at <https://cdn.citycoins.co>.

{% hint style="info" %}
For example, the main CityCoins brand guide located at the link below:

<https://github.com/citycoins/cdn/blob/main/cdn/brand/CityCoins_BrandGuidelines.pdf>

Is also available at:

<https://cdn.citycoins.co/brand/CityCoins_BrandGuidelines.pdf>
{% endhint %}

The available resources include branding guidelines and assets, hosted logos, and token metadata for each CityCoin.


# Registration and Activation

An overview of the registration and activation component of the CityCoins protocol.

{% hint style="info" %}
CityCoins require the [Stacks Web Wallet](https://hiro.so/wallet/install-web) to interact with the smart contracts on the [Stacks blockchain](https://stacks.co). (see [How do I get started?](/about-citycoins/how-do-i-get-started))
{% endhint %}

CityCoins only exist through mining, which does not begin until 20 independent wallets signal activation after the contract is deployed.

There is no ICO, no pre-sale, and no pre-mine, and there are no CityCoins issued or distributed prior to the start of mining.

Once 20 users register to activate the contract, a 150 block (\~24hr) countdown begins, after which anyone is eligible to try and mine the CityCoins within a given Stacks block.

{% hint style="info" %}
Registration **is not required** once the contract is activated. After this process is complete, anyone who completes a mining or stacking transaction will automatically be registered as a user.
{% endhint %}

A nominal transaction fee is required in order to send this transaction, paid in STX, and you can optionally include a memo of up to 50 characters that will be recorded on-chain.

For a more technical explanation, please see the [contract functions for activation](/contract-functions/activation#overview).


# Mining CityCoins

An overview of the mining component of the CityCoins protocol.

{% hint style="info" %}
CityCoins require the [Stacks Web Wallet](https://hiro.so/wallet/install-web) to interact with the smart contracts on the [Stacks blockchain](https://stacks.co). (see [How do I get started?](/about-citycoins/how-do-i-get-started))
{% endhint %}

## Overview

Anyone can mine CityCoins by submitting a transaction to a CityCoins smart contract on the Stacks blockchain.

There are no hardware requirements and the protocol is open source, so anyone can build a website that interacts with it. The main website for mining/stacking CityCoins is [minecitycoins.com](https://minecitycoins.com), and others are listed under the CityCoins Resources category on the left menu.

{% hint style="warning" %}
Miners can only participate once per block. **Once STX are sent for mining a CityCoin they are not returned,** they are distributed to the city's wallet and CityCoin Stackers.
{% endhint %}

There are also [code examples](/developer-resources/code-examples/mining), [Node.js scripts](https://github.com/citycoins/scripts), and [community resources](/citycoins-resources/general#community-tools) built around mining.

For a more technical explanation, please see the contract functions for [mining](/contract-functions/mining) and [mining claims](/contract-functions/mining-claims).

## How it Works

CityCoin miners spend STX while competing to earn the CityCoin block reward, which is defined by the [token emissions schedule](/core-protocol/token-configuration#emissions-schedule) and begins at 250,000 CityCoins per block.

* 30% of the STX that miners spend is sent directly to a reserved wallet for the city
* 70% of the STX that miners spend are distributed to people who stack their CityCoins (Stackers)

{% hint style="info" %}
There is only one winning miner per block that can claim the CityCoin reward.
{% endhint %}

![How it Works](/files/WZC9FGJEV1w3Vupmn84h)

The city can claim this reserved wallet and convert their STX to USD whenever they want. They can also Stack the STX to earn BTC.

## How to Mine

The main website for mining/stacking CityCoins is [minecitycoins.com](https://minecitycoins.com), and others are listed under the CityCoins Resources category on the left menu.

The general flow for mining on any CityCoins website will be:

1. Log in with your Stacks Wallet
2. Select the number of blocks to mine for (1-200)
3. Select the amount of STX to commit per block
4. Submit the transaction
5. Verify the transaction with the Stacks Wallet

{% hint style="danger" %}
**Remember:** nobody will ask you for your secret key and you should never enter it into a website.
{% endhint %}

## **Mining Strategy**

You can only submit a mining bid once per block. Once that transaction confirms then the bid is locked in. If you submit a mining transaction in a block where you are already mining, it will fail.

You can also mine for multiple blocks in one transaction by selecting the amount to spend per block and submitting the total bid up front. Once that transaction confirms then the bid is locked in for the following blocks.

{% hint style="info" %}
You can mine for up to 200 blocks based on the function in the contract, however due to transaction costs, mining over 100 blocks may require a higher fee for the transaction to be processed.
{% endhint %}

The probability to win at least one block in a sequence of blocks with a fixed commit of `C` STX and a total of other miners `T` STX is the following:

```
P(win at least 1 block in N blocks) = 1 - (T / (T + C)) ^ N
```

An example with real numbers: the table below assumes the total committed by miners in a block is 500 STX, and as a miner you have 200 STX to spend.

|           |                      |                 |
| --------- | -------------------- | --------------- |
| **Spend** | **Number of Blocks** | **Probability** |
| 1 STX     | 200                  | 32.9%           |
| 10 STX    | 20                   | 32.7%           |
| 12.5 STX  | 16                   | 32.6%           |
| 100 STX   | 2                    | 30.5%           |
| 200 STX   | 1                    | 28.5%           |

## **Mining Pools**

Individual miners can pool their funds together and mine CityCoins as a team.&#x20;

There are two main options for mining pools:

* **custodial:** an administrator for the pool will manage funds, make contract calls, and make payouts to pool members
* **non-custodial:** powered by smart contracts, miners can participate simply by sending a transaction and the funds, mining, and payouts are managed by the contract

{% hint style="warning" %}
Always *do your own research* (DYOR) before participating in a pool by joining the community, evaluating the code, and fully understanding the process.
{% endhint %}

## **Claiming Rewards**

A winner cannot be verified until 100 Stacks blocks pass from the block mined (\~16 hours).

Mining claims are based on the block height of the transaction, which can be seen by searching for your address in the [Stacks Explorer](https://explorer.stacks.co) and viewing previous mining transactions.

![Mining Transaction in Explorer](/files/BHdEdrRWh4OrH7xxGw8Y)

If mining for a single block, then the block height of the transaction is the one to check.

If mining for multiple blocks, then the block height of the transaction is the first block to check, followed by the number of blocks selected.

{% hint style="info" %}
For example, if mining for 100 blocks and the transaction confirms at block #45,600, then blocks #45,600 to #45,699 should be checked for rewards.
{% endhint %}

There are [community tools](/citycoins-resources/general#community-tools) to help see the mining history including won and/or unclaimed blocks, two examples are below for MIA/NYC where `ADDRESS` is your Stacks address.

* `https://miamining.com/history/ADDRESS`
* `https://mining.nyc/history/ADDRESS`

![Mining History Example](/files/7AykJPjdaMOsJPoLOtjQ)

The general flow for claiming a mining reward on any CityCoins website will be:

1. Log in with your Stacks Wallet
2. Enter the block height to claim the reward
3. Submit the transaction
4. Verify the transaction with the Stacks Wallet

{% hint style="danger" %}
**Remember:** nobody will ask you for your secret key and you should never enter it into a website.
{% endhint %}


# Stacking CityCoins

An overview of the stacking component of the CityCoins protocol.

{% hint style="info" %}
CityCoins require the [Stacks Web Wallet](https://hiro.so/wallet/install-web) to interact with the smart contracts on the [Stacks blockchain](https://stacks.co). (see [How do I get started?](/about-citycoins/how-do-i-get-started))
{% endhint %}

## Overview

Anyone can Stack CityCoins by locking them in a CityCoins smart contract for selected reward cycles and receive a portion of the remaining 70% of the STX sent by CityCoins miners.

Reward cycles are 2,100 Stacks blocks in length (\~ 2 weeks), similar to Stacking STX.

**When Stacking, you must select:**

* the amount of CityCoins you want to Stack, which will be transferred to the smart contract
* the number of reward cycles you want to participate in, maximum 32 (\~16 months)

{% hint style="warning" %}
You cannot Stack in the currently active reward cycle, only for the next reward cycle.

*e.g. if you select to Stack in a block height in reward cycle 1 then Stacking will begin in reward cycle 2.*
{% endhint %}

There are also [code examples](/developer-resources/code-examples/stacking), [Node.js scripts](https://github.com/citycoins/scripts), and [community resources](/citycoins-resources/general#community-tools) built around Stacking.

For a more technical explanation, please see the contract functions for [Stacking](/contract-functions/stacking) and [Stacking claims](/contract-functions/stacking-claims).

## **Stacking Claims**

While Stacking CityCoins is similar to Stacking STX, there are a few key differences.

Instead of rewards being delivered automatically during the cycle, Stackers must wait for the **reward cycles to pass** before claiming their Stacking rewards, which consist of:

* the Stacks (STX) sent by miners
* the amount of CityCoins they Stacked, if unlocked

For example, if you Stacked CityCoins for three cycles starting in Cycle 1, then you would be able to claim:

* your portion of the 70% Stacks (STX) sent by miners for Cycle 1, after Cycle 1 ends
* your portion of the 70% Stacks (STX) sent by miners for Cycle 2, after Cycle 2 ends
* your portion of the 70% Stacks (STX) sent by miners for Cycle 3, in addition to the Stacked CityCoins, after Cycle 3 ends

Each Stacker receives rewards proportionate to what they stacked against the total amount of Stacked CityCoins for the given reward cycle.

## **Common Questions**

### **Do the Stacked CityCoins stay in my wallet?**

No, they are transferred to the contract and can be reclaimed once the selected cycles are complete. Some examples are below.

* if you Stack 50,000 CityCoins for 1 cycle, then after the cycle ends you can claim the STX rewards for that cycle in addition to the 50,000 CityCoins
* if you Stack 50,000 CityCoins for 3 cycles, then after cycle 1 and 2 you can claim the STX rewards for each, and after cycle 3 you can claim the STX rewards in addition to the 50,000 CityCoins

See the table under [Can I stack additional tokens for a cycle?](#can-i-stack-additional-tokens-for-a-cycle) for another example.

### **Is there a minimum amount for Stacking?**

No, however the STX rewards for a given cycle are proportionate to the amount you Stack versus the total Stacked in that cycle.

If the amount you Stack in CityCoins entitles you to less than 1 uSTX (0.000001 STX) then no reward will be received.

### **Can I change the duration of CityCoins I've already Stacked?**

No, once `stack-tokens` is called the CityCoins are transferred to the smart contract and the values are set. There is no way to update it.

### **Is there a cooldown between cycles?**

Yes, when you are finished Stacking and reclaim your CityCoins, you can then stack for the *next cycle*. An example with MiamiCoin (MIA):

* A user submits a Stacking transaction at block height #26386 for one cycle
* Since block #26386 is part of Cycle 0, the MIA are Stacked for Cycle 1
* After Cycle 1 finishes at #28696, the user can reclaim their STX rewards and their Stacked MIA
* The user submits a Stacking transaction at block height #28697 for one cycle
* Since block #28697 is part of Cycle 2, the MIA are Stacked for Cycle 3
* After Cycle 3 finishes at #32896, the user can reclaim their STX rewards and their Stacked MIA

### **Can I Stack additional tokens for a cycle?**

A: Yes, if you call the `stack-tokens` function before the next cycle starts, you can add to the amount Stacked as well as choose different amounts for a different number of cycles.

In a more complex example:

* the user has 1,000,000 CityCoins to Stack
* the user calls `stack-tokens` during cycle 3 with 250,000 for 1 cycle
* the user calls `stack-tokens` during cycle 3 with 250,000 for 2 cycles
* the user calls `stack-tokens` during cycle 3 with 500,000 for 3 cycles

The payouts would then be based on the amount Stacked by the user `R`, the total STX reward that cycle `S`, and the total of all Stackers `T`using the formula: `STX Rewards = (R * S) / T`

<table data-header-hidden><thead><tr><th>Reward Cycle</th><th width="200">Amount Stacked</th><th>Claimable Amount</th><th>STX Rewards</th></tr></thead><tbody><tr><td>Reward Cycle</td><td>Amount Stacked</td><td>Claimable Amount</td><td>STX Rewards</td></tr><tr><td>3</td><td>none</td><td>none</td><td>none</td></tr><tr><td>4</td><td>1,000,000 CityCoins</td><td>none</td><td><code>(R * 1,000,000) / T</code></td></tr><tr><td>5</td><td>750,000 CityCoins</td><td>250,000 CityCoins</td><td><code>(R * 500,000) / T</code></td></tr><tr><td>6</td><td>500,000 CityCoins</td><td>250,000 CityCoins</td><td><code>(R * 500,000) / T</code></td></tr><tr><td>7</td><td>none</td><td>500,000 CityCoins</td><td>none</td></tr></tbody></table>


# Token Configuration

An overview of the token component of the CityCoins protocol.

{% hint style="info" %}
CityCoins require the [Stacks Web Wallet](https://hiro.so/wallet/install-web) to interact with the smart contracts on the [Stacks blockchain](https://stacks.co). (see [How do I get started?](/about-citycoins/how-do-i-get-started))
{% endhint %}

## Overview

CityCoins are fungible tokens on the Stacks blockchain with no ICO, no pre-sale, and no pre-mine.

Once a CityCoin is deployed and [activated](/core-protocol/registration-and-activation), the emission schedule begins and winning miners mint the CityCoin into existence.

CityCoins can be sent and received using a STX address, used for payment in smart contracts, and more.

For a more technical explanation, please see the contract functions for [CityCoins tokens](/contract-functions/token).

## Emissions Schedule

Miners receive coinbase rewards for mining CityCoins outlined in the table on this page **per block**.

The emission schedule does not begin until [mining is activated](/core-protocol/registration-and-activation#overview), and once it begins, the current block height of the Stacks blockchain is recorded in the smart contract.

From there, the amount of CityCoins rewarded through mining follow a [doubling epoch halving schedule](https://github.com/citycoins/governance/blob/main/ccips/ccip-008/ccip-008-citycoins-sip-010-token-v2.md#emissions-schedule), where the mining rewards are cut in half in intervals over the next 20 years.

{% hint style="info" %}
There is a bonus block reward for early miners who participate in the first 10,000 blocks.
{% endhint %}

<table data-header-hidden><thead><tr><th width="150">Time Period</th><th width="150">Rewards</th><th width="163">Notes</th><th width="150"></th></tr></thead><tbody><tr><td>Epoch</td><td>Epoch Length</td><td>Epoch End Block</td><td>Block Reward</td></tr><tr><td>0</td><td>10,000</td><td>10,000</td><td>250,000</td></tr><tr><td>1</td><td>25,000</td><td>35,000</td><td>100,000</td></tr><tr><td>2</td><td>50,000</td><td>85,000</td><td>50,000</td></tr><tr><td>3</td><td>100,000</td><td>185,000</td><td>25,000</td></tr><tr><td>4</td><td>200,000</td><td>385,000</td><td>12,500</td></tr><tr><td>5</td><td>400,000</td><td>785,000</td><td>6,250</td></tr><tr><td>6</td><td>n/a</td><td>n/a</td><td>3,125</td></tr></tbody></table>

After the final halving the total supply is estimated to be 17,500,000,000 CityCoins and will increase indefinitely by an estimated 164,062,500 CityCoins per year.

{% hint style="info" %}
The values above are denoted in CityCoins, and the values in the contract and APIs the value will represent the reward/supply above multiplied by `1,000,000` to account for the 6 decimal places as micro-CityCoins.
{% endhint %}

### Decimals

CityCoins have 6 decimals, denoted with `u` for `micro-`.

<table><thead><tr><th width="189">Currency</th><th>Unit</th></tr></thead><tbody><tr><td>Bitcoin</td><td>1 BTC = 100,000,000 Satoshis</td></tr><tr><td>Stacks</td><td>1 STX = 1,000,000 micro-STX (uSTX)</td></tr><tr><td>CityCoins</td><td>1 CityCoin = 1,000,000 micro-CityCoin</td></tr><tr><td>MiamiCoin</td><td>1 MIA = 1,000,000 uMIA</td></tr><tr><td>NewYorkCityCoin</td><td>1 NYC = 1,000,000 NYC</td></tr></tbody></table>

Since CityCoins have 6 decimals, there will be places that may show the balance of `CityCoins * 1,000,000`. **This is not a bug.**

What's showing is the "raw" value on-chain, which represents micro-CityCoins. Consider a `50,000 MIA` block reward - claiming from the contract will mint `50,000,000,000 uMIA` which is then displayed correctly in wallets based on the number of decimals.

You can also see this in V1 to V2 conversion transactions, where for example, `50 MIA (V1)` is burned and `50,000,000 uMIA (V2)` minted, and both are equivalent in value because V2 MIA has 6 decimal places.


# General

General developer resources for building with Stacks and CityCoins.

## Stacks

|                                                                         |                                                                                                                                                                                                                                                                     |
| ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Stacks Cookbook](https://docs.stacks.co/docs/cookbook/)                | Authenticate users, sign transactions and store data with the Stacks blockchain                                                                                                                                                                                     |
| [micro-stacks](https://micro-stacks.dev/)                               | The primary package modern Typescript (+javascript) projects use to build apps in the Stacks ecosystem                                                                                                                                                              |
| [Stacks.js](https://github.com/hirosystems/stacks.js)                   | The Stacks.js libraries which provide everything you need to work with the [Stacks blockchain](https://www.stacks.co/what-is-stacks)                                                                                                                                |
| [Stacks.js Docs](https://stacks.js.org/)                                | In-depth library reference for Stacks.js                                                                                                                                                                                                                            |
| [Stacks API Docs](https://hirosystems.github.io/stacks-blockchain-api/) | The OpenAPI specification for the Stacks 2.0 blockchain API. ([more info](/developer-resources/integrations/supporting-citycoins))                                                                                                                                  |
| [Stacks Connect](https://github.com/hirosystems/connect)                | A JavaScript library for interacting with the Hiro Web Wallet.                                                                                                                                                                                                      |
| [Stacks Explorer](https://explorer.stacks.co)                           | Block explorer for the Stacks blockchain                                                                                                                                                                                                                            |
| [Stacks Node API](https://github.com/hirosystems/stacks-blockchain-api) | A full Stacks node and API implementation available via [Docker ](https://github.com/hirosystems/stacks-blockchain-api/blob/master/running_an_api.md)or [from source](https://github.com/hirosystems/stacks-blockchain-api/blob/master/running_api_from_source.md). |

For wallets that support Stacks, see the [how do I get started](/about-citycoins/how-do-i-get-started#stacks-wallets) page.

## Clarity

|                                                                             |                                                                                                                                             |
| --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| [Language Overview](https://docs.stacks.co/docs/clarity/)                   | Overview of the Clarity language constructs                                                                                                 |
| [Clarity Functions](https://docs.stacks.co/docs/clarity/language-functions) | A detailed list of all functions for the Clarity language                                                                                   |
| [Clarity Keywords](https://docs.stacks.co/docs/clarity/language-keywords)   | A detailed list of all keywords for the Clarity language                                                                                    |
| [Clarity Types](https://docs.stacks.co/docs/clarity/language-types)         | A detailed list of all types for the Clarity language                                                                                       |
| [Clarigen](https://github.com/mechanismHQ/clarigen)                         | A developer tool that automatically generates TypeScript-friendly clients that can interact with Clarity smart contracts.                   |
| [Clarinet](https://github.com/hirosystems/clarinet)                         | A Clarity runtime packaged as a command line tool, designed to facilitate smart contract understanding, development, testing and deployment |
| [Clarity of Mind](https://book.clarity-lang.org/title-page.html)            | *Clarity of Mind* is both an introductory as well as a reference book for the Clarity smart contract language                               |
| [Clarity Tools](https://clarity.tools/)                                     | An interactive, browser-based Clarity IDE for experimentation                                                                               |
| [Clarity Universe](https://stacks.org/clarity-universe)                     | A portal that brings together everything a developer, project, or company needs to be successful with the Clarity smart contract language   |
| [VSCode Extension](https://github.com/hirosystems/clarity-lsp)              | Provides language features for Clarity like auto complete, go to definition, find all references, etc                                       |

## CityCoins

|                                                                                             |                                                                                                                                               |
| ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| [CityCoins Brand Resources](/citycoins-resources/general#brand-resources)                   | Logos, illustrations, and style guides for each city.                                                                                         |
| [CityCoins Github Org](https://github.com/citycoins)                                        | The GitHub organization that contains the contracts, user interface, and other resources related to the CityCoins protocol                    |
| [CityCoins API](https://api.citycoins.co/docs) ([github](https://github.com/citycoins/api)) | A simple API to interact with Stacks and CityCoins data without dependencies.                                                                 |
| [CityCoins Contracts](https://github.com/citycoins/citycoin)                                | The main contract repository including a test suite using Clarinet.                                                                           |
| [CityCoins Governance](https://github.com/citycoins/governance)                             | Community-submitted CityCoins Improvement Proposals (CCIPs)                                                                                   |
| [CityCoins Scripts](https://github.com/citycoins/scripts)                                   | Node.js scripts that interact with the protocol via a prompt-driven console interface ([documentation](https://citycoins.github.io/scripts)). |
| [CityCoins UI Template](https://github.com/citycoins/citycoin-ui)                           | The main UI template used to create [minecitycoins.com](https://minecitycoins.com) and interact with the CityCoins protocol                   |


# API

A simple API to interact with Stacks and CityCoins data.

The [CityCoins API](https://api.citycoins.co) is a quick and easy way to interact with both Stacks and CityCoins data.

It is built with Cloudflare Workers and micro-stacks, and the [code is open source](https://github.com/citycoins/api).

### Things to Note

* uses simple typed responses and provides detailed error messages
* all CityCoin contract routes start with `:version` and `:cityname`
  * e.g. `/v1/mia/mining/get-mining-stats-at-block/57934`
* `:version` accepts the major CityCoins contract version, e.g. v1, v2
* `:cityname` routes accept three letter city names, e.g. mia, nyc
* all additional parameters follow the order of operations below
  * `:blockheight > :cycleid > :userid > :address`
* routes are structured the same as the contract functions and documentation

### Endpoint Examples

A full list of routes and responses can be found in the [OpenAPI documentation](https://api.citycoins.co/docs).

Some quick examples:

* [Get the current Stacks block height](https://api.citycoins.co/stacks/get-block-height)
* [Get the activation block height for MIA](https://api.citycoins.co/activation/get-activation-block/mia)
* [Get the mining stats at block 49000 for MIA](https://api.citycoins.co/mining/get-mining-stats-at-block/mia/49000)
* [Get the total supply for MIA](https://api.citycoins.co/token/get-total-supply/mia)

### Implementation

If you want to use this for your project, build a copy for yourself, or have any questions, [file a GitHub Issue](https://github.com/citycoins/api/issues/new) and reach out!


# Code Examples

Examples of various interactions with the Stacks blockchain and CityCoins protocol.

In this section are several code examples outlining some common functions around interacting with Stacks and CityCoins.

Also be sure to look at the [CityCoins Scripts](https://github.com/citycoins/scripts) as part of the [General resources page](/developer-resources/general#citycoins), which include some Node.js prompt-driven console app examples.

{% hint style="info" %}
Have something you'd like to add? Feedback for what's here? [Open an issue!](https://github.com/citycoins/docs/issues/new)
{% endhint %}


# Get Account Transactions

Getting and manipulating transactions from the Stacks blockchain.

## Getting Account Transactions

The Stacks API [provides an endpoint](https://hirosystems.github.io/stacks-blockchain-api/#operation/get_account_transactions) for getting all transactions related to a principal, which can be a Stacks address or a contract identifier.

{% hint style="info" %}
Contract identifiers are formatted *deployer\_address.contract-name*

*e.g.* SP2H8PY27SEZ03MWRKS5XABZYQN17ETGQS3527SA5.newyorkcitycoin-core-v1
{% endhint %}

The `limit` parameter can fetch a maximum of 50 transactions at a time, and the `offset` parameter allows you to set the index for the first transaction to fetch.

Using the `total` value from the initial result, a simple `do...while` loop can help iterate over and collect all transactions for an address.

### Node.js

{% hint style="info" %}
Requires [`node-fetch`](https://www.npmjs.com/package/node-fetch)`in package.json`
{% endhint %}

```
import fetch from "node-fetch";

// returns a Promise that resolves after 'ms' milliseconds
const timer = (ms) => new Promise((res) => setTimeout(res, ms));

// fetches all account transactions for a given address or contract identifier
async function getAccountTxs(address) {
  let counter = 0;
  let total = 0;
  let limit = 50;
  let url = "";
  let txResults = [];

  // bonus points if you use your own node!
  let stxApi = "https://stacks-node-api.mainnet.stacks.co";

  console.log(`checking address: ${address}`);

  // obtain all account transactions 50 at a time
  do {
    url = `${stxApi}/extended/v1/address/${address}/transactions?limit=${limit}&offset=${counter}`;
    const response = await fetch(url);
    if (response.status === 200) {
      // success
      const responseJson = await response.json();
      // get total number of tx
      if (total === 0) {
        total = responseJson.total;
        console.log(`Total Txs: ${total}`);
      }
      // add all transactions to main array
      responseJson.results.map((tx) => {
        txResults.push(tx);
        counter++;
      });
      // output counter
      console.log(`Processed ${counter} of ${total}`);
    } else {
      // error
      throw new Error(
        `getAccountTxs response err: ${response.status} ${response.statusText}`
      );
    }
    // pause for 1sec, avoid rate limiting
    await timer(1000);
  } while (counter < total);

  // view the output
  //console.log(JSON.stringify(txResults));
  
  return txResults;
}

getAccountTxs("SP3CK642B6119EVC6CT550PW5EZZ1AJW661ZMQTYD");

```

## Filtering Transactions

With the full set of transactions for an address, the results can then easily be filtered into a new array with useful data.

### MIA Mining

Filters for all MIA mining transactions for the specified address.

```
// get all MIA mining tx for address
let address = 'SP3CK642B6119EVC6CT550PW5EZZ1AJW661ZMQTYD';
let miningTxs = [];
let txs = getAccountTxs(address);
txs.map(tx => {
  if (tx.tx_type === 'contract_call') {
    if (tx.contract_call.contract_id === `SP466FNC0P7JWTNM2R9T199QRZN1MYEDTAR0KP27.miamicoin-core-v1` && tx.tx_status === 'success') {
      if (tx.contract_call.function_name === 'mine-tokens' || tx.contract_call.function_name === 'mine-many') {
        miningTxs.push(tx);
      }
    }
  }
});

console.log(`total MIA mining txs: ${miningTxs.length}`);
```

### NYC Mining Claims

Filters for all NYC mining claim transactions for the specified address.

```
// get all NYC mining claim tx for address
let miningClaimTxs = [];
let address = 'SP3CK642B6119EVC6CT550PW5EZZ1AJW661ZMQTYD';
let txs = getAccountTxs(address);
txs.map(tx => {
  if (tx.tx_type === 'contract_call') {
    if (tx.contract_call.contract_id === `SP2H8PY27SEZ03MWRKS5XABZYQN17ETGQS3527SA5.newyorkcitycoin-core-v1` && tx.tx_status === 'success') {
      if (tx.contract_call.function_name === 'claim-mining-reward') {
        miningClaimTxs.push(tx);
      }
    }
  }
});
console.log(`total NYC mining claim txs: ${miningClaimTxs.length}`);
```

### MIA Stacking

```
// get all MIA stacking tx for address
let stackingTxs = [];
let address = 'SP3CK642B6119EVC6CT550PW5EZZ1AJW661ZMQTYD';
let txs = getAccountTxs(address);
txs.map(tx => {
  if (tx.tx_type === 'contract_call') {
    if (tx.contract_call.contract_id === `SP466FNC0P7JWTNM2R9T199QRZN1MYEDTAR0KP27.miamicoin-core-v1` && tx.tx_status === 'success') {
      if (tx.contract_call.function_name === 'stack-tokens') {
        stackingTxs.push(tx);
      }
    }
  }
});
console.log(`total MIA stacking txs: ${stackingTxs.length}`);
```

### NYC Stacking Claims

```
// get all NYC stacking claim tx for address
let stackingClaimTxs = [];
let address = 'SP3CK642B6119EVC6CT550PW5EZZ1AJW661ZMQTYD';
let txs = getAccountTxs(address);
txs.map(tx => {
  if (tx.tx_type === 'contract_call') {
    if (tx.contract_call.contract_id === `SP2H8PY27SEZ03MWRKS5XABZYQN17ETGQS3527SA5.newyorkcitycoin-core-v1` && tx.tx_status === 'success') {
      if (tx.contract_call.function_name === 'claim-stacking-reward') {
        stackingClaimTxs.push(tx);
      }
    }
  }
});
console.log(`total NYC stacking claim txs: ${stackingClaimTxs.length}`);
```


# Activation

Examples of CityCoin contract functions related to activation and registration.

## Get Activation Block

Get the block height the contract activates at.

{% hint style="info" %}
Requires `@stacks/network` and `@stacks/transactions`
{% endhint %}

```
// returns the activation block height

const NETWORK = new StacksMainnet(); // set network from @stacks/network

export async function getActivationBlock() {
  const resultCv = await callReadOnlyFunction({
    contractAddress: 'SP466FNC0P7JWTNM2R9T199QRZN1MYEDTAR0KP27',
    contractName: 'miamicoin-core-v1',
    functionName: 'get-activation-block',
    functionArgs: [],
    network: NETWORK, 
    senderAddress: contractAddress, // can be any valid STX address
  });
  const result = cvToJSON(resultCv);
  return result.value.value; // activation block height
}
```

## Get Registered Users

Get the total number of registered users that have sent one of the following:

* register user tx (`register-user`)
* mining tx (`mine-tokens` or `mine-many`)
* stacking tx (`stack-tokens`)

{% hint style="info" %}
Requires `@stacks/network` and `@stacks/transactions`
{% endhint %}

```
// returns the current number of registered users

const NETWORK = new StacksMainnet(); // set network from @stacks/network

export async function getRegisteredUsersNonce() {
  const resultCv = await callReadOnlyFunction({
    contractAddress: 'SP466FNC0P7JWTNM2R9T199QRZN1MYEDTAR0KP27',
    contractName: 'miamicoin-core-v1',
    functionName: 'get-registered-users-nonce',
    functionArgs: [],
    network: NETWORK,
    senderAddress: contractAddress, // can be any valid STX address
  });
  const result = cvToJSON(resultCv);
  return result.value; // total registered users
}
```


# Mining

Examples of CityCoin contract functions related to mining.

## Mining a Single Block

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

* `@stacks/network`
* `@stacks/transactions`
* `@stacks/connect-react`
  {% endhint %}

```
// example: mining a single block with 10 STX

const NETWORK = new StacksMainnet(); // set network from @stacks/network
const { doContractCall } = useConnect(); // hook for Stacks Connect

let totalUstx = 10000000; // amount of uSTX to spend in block
let totalUstxCV = uintCV(totalUstx);

let memoCV = someCV(bufferCVFromString('an optional memo'));
// alternate if no memo:
// let memoCV = noneCV();

try {
  await doContractCall({
    contractAddress: 'SP466FNC0P7JWTNM2R9T199QRZN1MYEDTAR0KP27',
    contractName: 'miamicoin-core-v1',
    functionName: 'mine-tokens',
    functionArgs: [totalUstxCV, memoCV],
    postConditionMode: PostConditionMode.Deny,
    postConditions: [
      makeStandardSTXPostCondition(
        ownerStxAddress,
        FungibleConditionCode.Equal,
        totalUstxCV.value
      ),
    ],
    network: NETWORK,
    onCancel: () => {
      // what to do if tx is canceled / window is closed
      console.log('Transaction canceled, please try again');
    },
    onFinish: result => {
      // what to if tx is successfully broadcasted
      console.log(`Transaction successfully broadcasted:\n${result.txId}`);
    },
  });
} catch (err) {
  console.log(`Error: ${err.message}`);
}
```

## Mining for Multiple Blocks

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

* `@stacks/network`
* `@stacks/transactions`
* `@stacks/connect-react`
  {% endhint %}

```
// example: mining 10 blocks with 5, 10, and 15 STX per block

const NETWORK = new StacksMainnet(); // set network from @stacks/network
const { doContractCall } = useConnect(); // hook for Stacks Connect

// initialize variables
let commitsUstx = [5000000, 10000000, 15000000, 5000000, 10000000, 15000000, 5000000, 10000000, 15000000, 5000000];
let totalUstx = 0;
let totalUstxCV = uintCV(0);
let mineManyArray = [];
let mineManyArrayCV = listCV([]);

// set up contract submission data
for (let i = 0; i < commits.length; i++) {
  mineManyArray.push(uintCV(amount));
  totalUstx += amount;
}
totalUstxCV = uintCV(totalUstx);
mineManyArrayCV = listCV(mineManyArray);

try {
  await doContractCall({
    contractAddress: 'SP466FNC0P7JWTNM2R9T199QRZN1MYEDTAR0KP27',
    contractName: 'miamicoin-core-v1',
    functionName: 'mine-many',
    functionArgs: [mineManyArrayCV],
    postConditionMode: PostConditionMode.Deny,
    postConditions: [
      makeStandardSTXPostCondition(
        ownerStxAddress,
        FungibleConditionCode.Equal,
        totalUstxCV.value
      ),
    ],
    network: NETWORK,
    onCancel: () => {
      // what to do if tx is canceled / window is closed
      console.log('Transaction canceled, please try again');
    },
    onFinish: result => {
      // what to if tx is successfully broadcasted
      console.log(`Transaction successfully broadcasted:\n${result.txId}`);
    },
  });
} catch (err) {
  console.log(`Error: ${err.message}`);
}
```


# Mining Claims

Examples of CityCoin contract functions related to mining claims.

## Claim Mining Rewards

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

* `@stacks/network`
* `@stacks/transactions`
* `@stacks/connect-react`
  {% endhint %}

```
// example: claim mining rewards at a given block height

const NETWORK = new StacksMainnet(); // set network from @stacks/network
const { doContractCall } = useConnect(); // hook for Stacks Connect

const targetBlock = 24498; // block height to claim
const targetBlockCV = uintCV(targetBlock);

try {
  await doContractCall({
    contractAddress: 'SP466FNC0P7JWTNM2R9T199QRZN1MYEDTAR0KP27',
    contractName: 'miamicoin-core-v1',
    functionName: 'claim-mining-reward',
    functionArgs: [targetBlockCV],
    postConditionMode: PostConditionMode.Deny,
    postConditions: [],
    network: NETWORK,
    onCancel: () => {
      // what to do if tx is canceled / window is closed
      console.log('Transaction canceled, please try again');
    },
    onFinish: result => {
      // what to if tx is successfully broadcasted
      console.log(`Transaction successfully broadcasted:\n${result.txId}`);
    },
  });
} catch (err) {
  console.log(`Error: ${err.message}`);
}
```


# Stacking

Examples of CityCoin contract functions related to stacking.

## Stack CityCoins

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

* `@stacks/network`
* `@stacks/transactions`
* `@stacks/connect-react`
  {% endhint %}

```
// example: stack CityCoins for the next active cycle

const NETWORK = new StacksMainnet(); // set network from @stacks/network
const { doContractCall } = useConnect(); // hook for Stacks Connect

const amount = 250000; // amount of CityCoins
const cycles = 5; // cycles to lock for
const amountCV = uintCV(amount);
const cyclesCV = uintCV(cycles);

try {
  await doContractCall({
    contractAddress: 'SP466FNC0P7JWTNM2R9T199QRZN1MYEDTAR0KP27',
    contractName: 'miamicoin-core-v1',
    functionName: 'stack-tokens',
    functionArgs: [amountCV, cyclesCV],
    postConditionMode: PostConditionMode.Deny,
    postConditions: [
      makeStandardFungiblePostCondition(
        ownerStxAddress,
        FungibleConditionCode.Equal,
        amountCV.value,
        createAssetInfo('SP466FNC0P7JWTNM2R9T199QRZN1MYEDTAR0KP27', 'miamicoin-token', 'miamicoin')
      ),
    ],
    network: NETWORK,
    onCancel: () => {
      // what to do if tx is canceled / window is closed
      console.log('Transaction canceled, please try again');
    },
    onFinish: result => {
      // what to if tx is successfully broadcasted
      console.log(`Transaction successfully broadcasted:\n${result.txId}`);
    },
  });
} catch (err) {
  console.log(`Error: ${err.message}`);
}
```


# Contracts

Links and information about deployed CityCoin contracts.

## CityCoins Protocol

More content will be added here following the mainnet deployments of the protocol outlined in [CCIP-013](https://github.com/citycoins/governance/blob/main/ccips/ccip-013/ccip-013-stabilize-protocol-and-simplify-contracts.md).

### DAO Structure

The CityCoins DAO implementation is based on the [Executor DAO](https://github.com/MarvinJanssen/executor-dao), [Ecosystem DAO](https://stx.eco/), and other similar implementations on the Stacks blockchain.

The core concepts that make this possible are:

* proposals are smart contracts that execute the described changes
* the core (base-dao) executes proposals, the extensions define additional actions
* ownership control happens via sending context

### DAO Extensions

In order to achieve the structure and goals laid out by CCIP-013, the following DAO extensions provide functionality for each part of the CityCoins protocol.

| Name                   | Summary                                                                                                              | Description                                                                                                                                                                                                                                                                                                                                                                                                   |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| base-dao               | An ExecutorDAO implementation for CityCoins inspired by the one DAO to rule them all.                                |                                                                                                                                                                                                                                                                                                                                                                                                               |
| ccd001-direct-execute  | Allows a small number of very trusted principals to immediately execute a proposal once a super majority is reached. | An extension meant for the bootstrapping period of a DAO. It temporarily gives trusted principals the ability to perform a "direct execution"; meaning, they can immediately execute a proposal with the required signals. The Direct Execute extension is set with a sunset period of \~6 months from deployment. Approvers, the parameters, and sunset period may be changed by means of a future proposal. |
| ccd002-treasury        | A treasury contract that can manage STX, SIP-009 NFTs, and SIP-010 FTs.                                              | An extension contract that holds assets on behalf of the DAO. SIP-009 and SIP-010 assets must be allowed before they are supported. Deposits can be made by anyone either by transferring to the contract or using a deposit function below. Withdrawals are restricted to the DAO through either extensions or proposals.                                                                                    |
| ccd003-user-registry   | A central user registry for the CityCoins protocol.                                                                  | An extension contract that associates an address (principal) with an ID (uint) for use in other CityCoins extensions.                                                                                                                                                                                                                                                                                         |
| ccd004-city-registry   | A central city registry for the CityCoins protocol.                                                                  | An extension contract that associates a city name (string-ascii 10) with an ID (uint) for use in other CityCoins extensions.                                                                                                                                                                                                                                                                                  |
| ccd005-city-data       | A datastore for city information in the CityCoins protocol.                                                          | An extension contract that uses the city ID as the key for storing city information. This contract is used by other CityCoins extensions to store and retrieve city information.                                                                                                                                                                                                                              |
| ccd006-city-mining     | A central city mining contract for the CityCoins protocol.                                                           | An extension that provides a mining interface per city, in which each mining participant spends STX per block for a weighted chance to mint new CityCoins per the issuance schedule.                                                                                                                                                                                                                          |
| ccd007-city-stacking   | A central city stacking contract for the CityCoins protocol.                                                         | An extension that provides a stacking interface per city, in which a user can lock their CityCoins for a specified number of cycles, in return for a proportion of the stacking rewards accrued by the related city wallet.                                                                                                                                                                                   |
| ccd008-city-activation | This extension allows anyone to vote on activating a city once it's been added to CCD005 City Data.                  | An extension contract that handles the voting process for activating a city and setting the related data.                                                                                                                                                                                                                                                                                                     |
| ccd009-auth-v2-adapter | Connects to the auth v2 contract in the CityCoins legacy protocol as an approver.                                    | An extension contract that allows the DAO to access protected contract functions in the legacy protocol as part of CCIP-010.                                                                                                                                                                                                                                                                                  |

### Active Legacy Contracts

The new DAO protocol will still utilize some of the legacy CityCoin protocol contracts, listed below.

| Contract Name                                                                                                                               | Description                                                                                                                                                  |
| ------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [citycoin-vrf-v2](https://explorer.stacks.co/txid/SPSCWDV3RKV5ZRN1FQD84YE1NQFEDJ9R1F4DYQ11.citycoin-vrf-v2?chain=mainnet)                   | a single contract used by all mining contracts, which takes a given Stacks block height and returns a random `uint` calculated by accessing the on-chain VRF |
| [citycoin-core-v2-trait](https://explorer.stacks.co/txid/SPSCWDV3RKV5ZRN1FQD84YE1NQFEDJ9R1F4DYQ11.citycoin-core-v2-trait?chain=mainnet)     | defines the functions in a `citycoin-core-*` contract around activation, mining, and stacking                                                                |
| [citycoin-token-v2-trait](https://explorer.stacks.co/txid/SPSCWDV3RKV5ZRN1FQD84YE1NQFEDJ9R1F4DYQ11.citycoin-token-v2-trait?chain=mainnet)   | defines the functions in a `citycoin-token-*` contract around token utilities and a send-many function                                                       |
| [miamicoin-token-v2](https://explorer.stacks.co/txid/SP1H1733V5MZ3SZ9XRW9FKYGEZT0JDGEB8Y634C7R.miamicoin-token-v2?chain=mainnet)            | The currently deployed MiamiCoin fungible token contract                                                                                                     |
| [newyorkcitycoin-token-v2](https://explorer.stacks.co/txid/SPSCWDV3RKV5ZRN1FQD84YE1NQFEDJ9R1F4DYQ11.newyorkcitycoin-token-v2?chain=mainnet) | The currently deployed NewYorkCityCoin fungible token contract                                                                                               |

### Deployer Addresses

| Deployer Type | Mainnet Address                                                                                                                                | Testnet Address                                                                                                                                |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| MIA           | SP1H1733V5MZ3SZ9XRW9FKYGEZT0JDGEB8Y634C7R [(link)](https://explorer.stacks.co/address/SP1H1733V5MZ3SZ9XRW9FKYGEZT0JDGEB8Y634C7R?chain=mainnet) | ST1H1733V5MZ3SZ9XRW9FKYGEZT0JDGEB8WRH7C6H [(link)](https://explorer.stacks.co/address/ST1H1733V5MZ3SZ9XRW9FKYGEZT0JDGEB8WRH7C6H?chain=testnet) |
| NYC           | SPSCWDV3RKV5ZRN1FQD84YE1NQFEDJ9R1F4DYQ11 [(link)](https://explorer.stacks.co/address/SPSCWDV3RKV5ZRN1FQD84YE1NQFEDJ9R1F4DYQ11?chain=mainnet)   | STSCWDV3RKV5ZRN1FQD84YE1NQFEDJ9R1D64KKHQ [(link)](https://explorer.stacks.co/address/STSCWDV3RKV5ZRN1FQD84YE1NQFEDJ9R1D64KKHQ?chain=testnet)   |
| DAO           | SP355N8734E5PVX9538H2QGMFP38RE211D9KV4MW8 [(link)](https://explorer.stacks.co/address/SP355N8734E5PVX9538H2QGMFP38RE211D9KV4MW8?chain=mainnet) | ST355N8734E5PVX9538H2QGMFP38RE211D9E2B4X5 [(link)](https://explorer.stacks.co/address/ST355N8734E5PVX9538H2QGMFP38RE211D9E2B4X5?chain=testnet) |
| Traits        | SPSCWDV3RKV5ZRN1FQD84YE1NQFEDJ9R1F4DYQ11 [(link)](https://explorer.stacks.co/address/SPSCWDV3RKV5ZRN1FQD84YE1NQFEDJ9R1F4DYQ11?chain=mainnet)   | ST1XQXW9JNQ1W4A7PYTN3HCHPEY7SHM6KPA085ES6 [(link)](https://explorer.stacks.co/address/ST1XQXW9JNQ1W4A7PYTN3HCHPEY7SHM6KPA085ES6?chain=testnet) |

## CityCoins Testnet Protocol

In order to facilitate testing of the legacy CityCoins protocol migration to the new structure outlined in [CCIP-013](https://github.com/citycoins/governance/blob/main/ccips/ccip-013/ccip-013-stabilize-protocol-and-simplify-contracts.md), the legacy CityCoins protocol is now deployed to testnet and activated for mining and stacking.

If you need testnet STX, MIA, or NYC for testing, reach out in the `#path-forward` channel on [Discord](https://chat.citycoins.co).

{% hint style="info" %}
The accounts for MIA, NYC, and the DAO deployments are the same for mainnet and testnet, with each address version linked above.\
\
The traits for the MIA/NYC protocol were deployed to `SPSCW...DYQ11` on mainnet and the separate account/address `ST1XQ...85ES6` on testnet.\
\
The traits for the CityCoins DAO will be deployed on mainnet by the same deployer as the DAO: `SP355...V4MW8`.
{% endhint %}

### Direct Execute

To facilitate faster testing, the list of approvers for the DAO's ccd001-direct-execute module all come from the same account and are noted below. On mainnet this will be a distributed group of signers.

* [`ST3AY0CM7SD9183QZ4Y7S2RGBZX9GQT54MJ6XY0BN`](https://explorer.stacks.co/address/ST3AY0CM7SD9183QZ4Y7S2RGBZX9GQT54MJ6XY0BN?chain=testnet)
* [`ST2D06VFWWTNCWHVB2FJ9KJ3EB30HFRTHB1A4BSP3`](https://explorer.stacks.co/address/ST2D06VFWWTNCWHVB2FJ9KJ3EB30HFRTHB1A4BSP3?chain=testnet)
* [`ST113N3MMPZRMJJRZH6JTHA5CB7TBZH1EH4C22GFV`](https://explorer.stacks.co/address/ST113N3MMPZRMJJRZH6JTHA5CB7TBZH1EH4C22GFV?chain=testnet)
* [`ST8YRW1THF2XT8E45XXCGYKZH2B70HYH71VC7737`](https://explorer.stacks.co/address/ST8YRW1THF2XT8E45XXCGYKZH2B70HYH71VC7737?chain=testnet)
* [`STX13Q7ZJDSFVDZMQ1PWDFGT4QSBMASRMCYE4NAP`](https://explorer.stacks.co/address/STX13Q7ZJDSFVDZMQ1PWDFGT4QSBMASRMCYE4NAP?chain=testnet)

### City Wallets

The following accounts represent the city wallet in the legacy version of the protocol on testnet, which will be retired in favor of the ccd002-treasury equivalents.

* MIA: [`ST3PM583Q21NF0GB428P79VFPYH8X5DQVKDDGD74T`](https://explorer.stacks.co/address/ST3PM583Q21NF0GB428P79VFPYH8X5DQVKDDGD74T?chain=testnet)
* NYC: [`ST7G6VDV48CXXSP6J2B4RRCKTFJ5NK3PBZSD3YW5`](https://explorer.stacks.co/address/ST7G6VDV48CXXSP6J2B4RRCKTFJ5NK3PBZSD3YW5?chain=testnet)

### Legacy Contracts

The following contracts are deployed on testnet for the legacy CityCoins protocol.

| General                                                                                                                                    | MIA                                                                                                                              | NYC                                                                                                                                         |
| ------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| [citycoin-vrf-v2](https://explorer.stacks.co/txid/ST1XQXW9JNQ1W4A7PYTN3HCHPEY7SHM6KPA085ES6.citycoin-vrf-v2?chain=testnet)                 | [miamicoin-auth-v2](https://explorer.stacks.co/txid/ST1H1733V5MZ3SZ9XRW9FKYGEZT0JDGEB8WRH7C6H.miamicoin-auth-v2?chain=testnet)   | [newyorkcitycoin-auth-v2](https://explorer.stacks.co/txid/STSCWDV3RKV5ZRN1FQD84YE1NQFEDJ9R1D64KKHQ.newyorkcitycoin-auth-v2?chain=testnet)   |
| [citycoin-core-v2-trait](https://explorer.stacks.co/txid/ST1XQXW9JNQ1W4A7PYTN3HCHPEY7SHM6KPA085ES6.citycoin-core-v2-trait?chain=testnet)   | [miamicoin-core-v2](https://explorer.stacks.co/txid/ST1H1733V5MZ3SZ9XRW9FKYGEZT0JDGEB8WRH7C6H.miamicoin-core-v2?chain=testnet)   | [newyorkcitycoin-core-v2](https://explorer.stacks.co/txid/STSCWDV3RKV5ZRN1FQD84YE1NQFEDJ9R1D64KKHQ.newyorkcitycoin-core-v2?chain=testnet)   |
| [citycoin-token-v2-trait](https://explorer.stacks.co/txid/ST1XQXW9JNQ1W4A7PYTN3HCHPEY7SHM6KPA085ES6.citycoin-token-v2-trait?chain=testnet) | [miamicoin-token-v2](https://explorer.stacks.co/txid/ST1H1733V5MZ3SZ9XRW9FKYGEZT0JDGEB8WRH7C6H.miamicoin-token-v2?chain=testnet) | [newyorkcitycoin-token-v2](https://explorer.stacks.co/txid/STSCWDV3RKV5ZRN1FQD84YE1NQFEDJ9R1D64KKHQ.newyorkcitycoin-token-v2?chain=testnet) |

These contracts will be migrated to the CityCoins DAO protocol per CCIP-013 on testnet prior to the same migration on mainnet.

## CityCoins (Legacy Info)

{% hint style="warning" %}
This section contains information that relates to an older version of the CityCoins protocol. See the section [CityCoins Protocol](#citycoins-protocol) above for the most up-to-date information.
{% endhint %}

|                                                                                                                                        V1                                                                                                                                       |                                                                                                                                           V2                                                                                                                                          |
| :-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |
|           <p><a href="https://explorer.stacks.co/txid/SP466FNC0P7JWTNM2R9T199QRZN1MYEDTAR0KP27.citycoin-vrf?chain=mainnet">citycoin-vrf</a><br>(<a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-006/ccip-006-citycoins-vrf.md">CCIP-006</a>)</p>          |         <p><a href="https://explorer.stacks.co/txid/SPSCWDV3RKV5ZRN1FQD84YE1NQFEDJ9R1F4DYQ11.citycoin-vrf-v2?chain=mainnet">citycoin-vrf-v2</a><br>(<a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-009/ccip-009-citycoins-vrf-v2.md">CCIP-009</a>)</p>         |
|  <p><a href="https://explorer.stacks.co/txid/SP466FNC0P7JWTNM2R9T199QRZN1MYEDTAR0KP27.citycoin-core-trait?chain=mainnet">citycoin-core-trait</a><br>(<a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-001/ccip-001-citycoins-traits.md">CCIP-001</a>)</p>  |  <p><a href="https://explorer.stacks.co/txid/SPSCWDV3RKV5ZRN1FQD84YE1NQFEDJ9R1F4DYQ11.citycoin-core-v2-trait?chain=mainnet">citycoin-core-v2-trait</a><br>(<a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-001/ccip-001-citycoins-traits.md">CCIP-001</a>)</p>  |
| <p><a href="https://explorer.stacks.co/txid/SP466FNC0P7JWTNM2R9T199QRZN1MYEDTAR0KP27.citycoin-token-trait?chain=mainnet">citycoin-token-trait</a><br>(<a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-001/ccip-001-citycoins-traits.md">CCIP-001</a>)</p> | <p><a href="https://explorer.stacks.co/txid/SPSCWDV3RKV5ZRN1FQD84YE1NQFEDJ9R1F4DYQ11.citycoin-token-v2-trait?chain=mainnet">citycoin-token-v2-trait</a><br>(<a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-001/ccip-001-citycoins-traits.md">CCIP-001</a>)</p> |

The VRF is a single contract used by all mining contracts, which takes a given Stacks block height and returns a random `uint` calculated by accessing the on-chain VRF.

* V1: includes a read-only function that calculates the value and returns it
* V2: includes a public function that will set the value to a map before returning it, and both the public and read-only function check the map for a value before calculating it

The core trait defines the functions in a `citycoin-core-*` contract around activation, mining, and stacking.

The token trait defines the functions in a `citycoin-token-*` contract around token utilities and a send-many function.

{% hint style="warning" %}
Clarity traits allow creating generalized functions where the contract to use within the function is provided as a parameter. This requires [extra security considerations](https://github.com/LNow/clarity-notes/blob/main/security/traits.md).
{% endhint %}

### MiamiCoin (MIA)

|                                                                                                                                                                                                                                                              V1                                                                                                                                                                                                                                                             |                                                                                                                                                                                                                                                              V2                                                                                                                                                                                                                                                              |
| :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |
|                                                                                                                              <p><a href="https://explorer.stacks.co/txid/SP466FNC0P7JWTNM2R9T199QRZN1MYEDTAR0KP27.miamicoin-auth?chain=mainnet">miamicoin-auth</a><br>(<a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-007/ccip-007-citycoins-auth.md">CCIP-007</a>)</p>                                                                                                                              |                                                                                                                          <p><a href="https://explorer.stacks.co/txid/SP1H1733V5MZ3SZ9XRW9FKYGEZT0JDGEB8Y634C7R.miamicoin-auth-v2?chain=mainnet">miamicoin-auth-v2</a><br>(<a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-010/ccip-010-citycoins-auth-v2.md">CCIP-010</a>)</p>                                                                                                                         |
| <p><a href="https://explorer.stacks.co/txid/SP466FNC0P7JWTNM2R9T199QRZN1MYEDTAR0KP27.miamicoin-core-v1?chain=mainnet">miamicoin-core-v1</a><br>(<a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-002/ccip-002-citycoins-activation.md">CCIP-002</a>, <a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-003/ccip-003-citycoins-mining.md">CCIP-003</a>, <a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-004/ccip-004-citycoins-stacking.md">CCIP-004</a>)</p> | <p><a href="https://explorer.stacks.co/txid/SP1H1733V5MZ3SZ9XRW9FKYGEZT0JDGEB8Y634C7R.miamicoin-core-v2?chain=mainnet">miamicoin-core-v2</a><br>(<a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-002/ccip-002-citycoins-activation.md">CCIP-002</a>, <a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-003/ccip-003-citycoins-mining.md">CCIP-003</a>, <a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-004/ccip-004-citycoins-stacking.md">CCIP-004</a>)</p> |
|                                                                                                                         <p><a href="https://explorer.stacks.co/txid/SP466FNC0P7JWTNM2R9T199QRZN1MYEDTAR0KP27.miamicoin-token?chain=mainnet">miamicoin-token</a><br>(<a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-005/ccip-005-citycoins-sip-010-token.md">CCIP-005</a>)</p>                                                                                                                        |                                                                                                                    <p><a href="https://explorer.stacks.co/txid/SP1H1733V5MZ3SZ9XRW9FKYGEZT0JDGEB8Y634C7R.miamicoin-token-v2?chain=mainnet">miamicoin-token-v2</a><br>(<a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-008/ccip-008-citycoins-sip-010-token-v2.md">CCIP-008</a>)</p>                                                                                                                    |

The auth, core, and token contract are created to interact with each other such that:

* The `core` contract enables activation/mining/stacking
* The `token` contract enables the CityCoin token operations
* The `auth` contract enables administrative utilities

The [Miami Wallet Address](https://explorer.stacks.co/address/SM2MARAVW6BEJCD13YV2RHGYHQWT7TDDNMNRB1MVT?chain=mainnet) is used by the contract for MiamiCoin protocol distribution.

### NewYorkCityCoin (NYC)

|                                                                                                                                                                                                                                                                    V1                                                                                                                                                                                                                                                                    |                                                                                                                                                                                                                                                                    V2                                                                                                                                                                                                                                                                   |
| :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |
|                                                                                                                              <p><a href="https://explorer.stacks.co/txid/SP2H8PY27SEZ03MWRKS5XABZYQN17ETGQS3527SA5.newyorkcitycoin-auth?chain=mainnet">newyorkcitycoin-auth</a><br>(<a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-007/ccip-007-citycoins-auth.md">CCIP-007</a>)</p>                                                                                                                              |                                                                                                                          <p><a href="https://explorer.stacks.co/txid/SPSCWDV3RKV5ZRN1FQD84YE1NQFEDJ9R1F4DYQ11.newyorkcitycoin-auth-v2?chain=mainnet">newyorkcitycoin-auth-v2</a><br>(<a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-010/ccip-010-citycoins-auth-v2.md">CCIP-010</a>)</p>                                                                                                                         |
| <p><a href="https://explorer.stacks.co/txid/SP2H8PY27SEZ03MWRKS5XABZYQN17ETGQS3527SA5.newyorkcitycoin-core-v1?chain=mainnet">newyorkcitycoin-core-v1</a><br>(<a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-002/ccip-002-citycoins-activation.md">CCIP-002</a>, <a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-003/ccip-003-citycoins-mining.md">CCIP-003</a>, <a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-004/ccip-004-citycoins-stacking.md">CCIP-004</a>)</p> | <p><a href="https://explorer.stacks.co/txid/SPSCWDV3RKV5ZRN1FQD84YE1NQFEDJ9R1F4DYQ11.newyorkcitycoin-core-v2?chain=mainnet">newyorkcitycoin-core-v2</a><br>(<a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-002/ccip-002-citycoins-activation.md">CCIP-002</a>, <a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-003/ccip-003-citycoins-mining.md">CCIP-003</a>, <a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-004/ccip-004-citycoins-stacking.md">CCIP-004</a>)</p> |
|                                                                                                                         <p><a href="https://explorer.stacks.co/txid/SP2H8PY27SEZ03MWRKS5XABZYQN17ETGQS3527SA5.newyorkcitycoin-token?chain=mainnet">newyorkcitycoin-token</a><br>(<a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-005/ccip-005-citycoins-sip-010-token.md">CCIP-005</a>)</p>                                                                                                                        |                                                                                                                    <p><a href="https://explorer.stacks.co/txid/SPSCWDV3RKV5ZRN1FQD84YE1NQFEDJ9R1F4DYQ11.newyorkcitycoin-token-v2?chain=mainnet">newyorkcitycoin-token-v2</a><br>(<a href="https://github.com/citycoins/governance/blob/main/ccips/ccip-008/ccip-008-citycoins-sip-010-token-v2.md">CCIP-008</a>)</p>                                                                                                                    |

The auth, core, and token contract are created to interact with each other such that:

* The `core` contract enables activation/mining/stacking
* The `token` contract enables the CityCoin token operations
* The `auth` contract enables administrative utilities

The [New York City Wallet Address](https://explorer.stacks.co/address/SM18VBF2QYAAHN57Q28E2HSM15F6078JZYZ2FQBCX?chain=mainnet) is used by the contract for NewYorkCityCoin protocol distribution.


# Integrations

A guide for integrating the Stacks blockchain and CityCoins protocol.

CityCoins are built on top of [the Stacks blockchain](https://stacks.co), with several options for integrating depending on the use case.

Since CityCoins are powered by Stacks, the options range from running a Stacks node to creating smart contracts or applications that interact with the CityCoins protocol.

For inspiration check out the [CityCoins blog](https://citycoins.co/blog) which highlights the ethos of the community and the [CityCoins Wiki](https://citycoins.wiki), both of which celebrate the successes of builders and community members working together toward a CityCoins future.


# Supporting Stacks

Implementing and interacting with a Stacks node and related software.

## Overview

In order to efficiently and reliably query the Stacks blockchain state, running a follower node allows for direct access to the same data as hosted APIs with the added benefit of decentralized control.

## Stacks Node API

The Stacks Node API provides both a self-contained Docker image and manual installation instructions for running a Stacks 2.0 blockchain and API instance.

Doing so provides access to a [robust API](https://hirosystems.github.io/stacks-blockchain-api/) that allows for querying accounts, transactions, smart contracts, and more.

* [Main Repository](https://github.com/hirosystems/stacks-blockchain-api)
* [Digital Ocean 1-Click App](https://marketplace.digitalocean.com/apps/stacks-blockchain)
* [Hiro Hosted Version](https://stacks-node-api.testnet.stacks.co/v2/info)
* [API Documentation](https://hirosystems.github.io/stacks-blockchain-api/)

## API Tech Stack

The Stacks Node API can be run on 4 GB memory / 80 GB disk, however it also requires a Bitcoin node to interact with, which have higher [disk space requirements](https://bitcoin.org/en/full-node#minimum-requirements).

The main elements of the API tech stack include:

* Postgres
* Stacks Blockchain API
* Stacks Blockchain Node
* Bitcoin Node

## Updates and Announcements

The [stacks-announce mailing list](https://groups.google.com/a/stacks.org/g/announce) is available to receive updates on new releases to the Stacks blockchain node.

* [Stacks API Releases](https://github.com/hirosystems/stacks-blockchain-api/releases)
* [Stacks Node Releases](https://github.com/blockstack/stacks-blockchain/releases/)

## Installation Methods

{% hint style="info" %}
The [Digital Ocean 1-Click App](https://marketplace.digitalocean.com/apps/stacks-blockchain) is the fastest way to get started, but the options above are available for custom implementations and environments.
{% endhint %}

* [Using Docker](https://github.com/hirosystems/stacks-blockchain-api/blob/master/running_an_api.md)
* [Install from Source](https://github.com/hirosystems/stacks-blockchain-api/blob/master/running_api_from_source.md)

The Syvita Guild also created the repository below, which contains a quick start script that sets up each component based on their cloned versions using Docker.

<https://github.com/syvita/stacks-api-node>&#x20;

## Optional: Stacks Explorer

The Stacks Explorer provides a web interface to interact with Stacks blockchain data, including accounts, transactions, contracts, and more.

Some examples include:

* [Hosted by Hiro](https://explorer.stacks.co)
* [Hosted by PlanBetter](https://explorer.planbetter.org/)

The Stacks Explorer is [available on GitHub](https://github.com/hirosystems/explorer) built with react, [next.js](https://github.com/zeit/next.js) and [@stacks/ui](https://github.com/blockstack/ui).

## Stacking STX

Stacking is the act of locking up STX for a set number of reward cycles and receiving a portion of the BTC spent by Stacks miners.

We call it "stacking" instead of "staking" because the protocol provides rewards of the *base currency* instead of the *same currency*.

The Stacking protocol is described in [SIP-007](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md).

A few high-level notes about the protocol:

* A STX holder must qualify for a reward slot by controlling a Stacks wallet with >= 0.02% of the total unlocked Stacks tokens (currently \~110,000 STX, and visible on [stacking.club](https://stacking.club/))
* A STX holder must broadcast a signed message before the reward cycle begins that:
  * Locks the associated Stacks tokens for a protocol-specified lockup period (reward cycles are 2,100 Stacks blocks in length, maximum of 12)
  * Specifies the Bitcoin address to receive the funds
  * Votes on a Stacks chain tip
* The required minimum for a reward slot is dynamic and can increase last minute. It only increases in steps of 10k STX
* It is possible that a reward slot receives 0 BTC because Stacks miners did not send any BTC when it was the slot's turn
* The more reward slots an address occupies, the closer the payouts will be to the average payout
* When the selected reward cycles are complete, the address must sit out for one cycle (a "cooldown period")

The PoX smart contract is the main tool and provides the functions to stack STX.

It is deployed at [SP000000000000000000002Q6VF78.pox](https://explorer.stacks.co/txid/0x41356e380d164c5233dd9388799a5508aae929ee1a7e6ea0c18f5359ce7b8c33?chain=mainnet).

The documentation is available at <https://docs.blockstack.org/references/stacking-contract>.

Additional Stacking information and statistics are available at <https://stacking.club/>


# Supporting CityCoins

Interacting with the CityCoins protocol.

## CityCoins Contracts

Each CityCoin is defined by a set of contracts for that city, including `core`, `token`, and `auth`.

The [Contracts page](/developer-resources/citycoin-contracts) lists the currently deployed CityCoins contracts with links to their on-chain source. The [GitHub repo](https://github.com/citycoins/citycoin/tree/main/contracts) is where the contracts are stored and updated before deployment.

## SIP-010 Standard

[SIP-010: Standard Trait Definition for Fungible Tokens](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md)

> Clarity, has built-in language primitives to define and use fungible tokens. Although those primitives exists, there is value in defining a common interface (known in Clarity as a "trait") that allows different smart contracts to interoperate with fungible token contracts in a reusable way. This SIP defines that trait.

SIP-010 includes function definitions for:

* transfer
* name (human-readable)
* symbol (ticker)
* decimals (CityCoins have 6)
* balance
* total supply
* token URI (externally hosted metadata)

## Send-Many Function

In addition to SIP-010, all CityCoins token contracts implement an additional `citycoin-token` trait that defines:

* activation
* set token URI
* mint
* burn
* send-many

The send-many function allows for sending to a list of up to 200 recipients in a single transaction.

The list must contain at least one entry with the following values:

* to: principal
* amount: uint
* memo: optional buff 34

## Token Metadata

[Metadata for CityCoins](https://github.com/citycoins/cdn/tree/main/cdn/metadata) are stored in a CDN available at [https://cdn.citycoins.co](https://cdn.citycoins.co/).

[MiamiCoin (MIA) example](https://cdn.citycoins.co/metadata/miamicoin.json):&#x20;

```
{
  "name": "MiamiCoin",
  "description": "A CityCoin for Miami, ticker is MIA, Stack it to earn Stacks (STX)",
  "image": "https://cdn.citycoins.co/logos/miamicoin.png"
}
```

## Brand Resources

More information on brand assets and guidelines for CityCoins can be found in the [CityCoins Resources](/citycoins-resources/general) section.

## Stacking CityCoins

CityCoins follow a similar protocol to [Stacking STX](https://github.com/citycoins/integrations/blob/main/README.md#stacking-stx) with a few key differences.

In the Stacks blockchain, 100% of what Stacks miners spend in BTC is transferred to Stackers.

In the CityCoins protocol, 30% of what CityCoin miners spend in STX is transferred to the custodied city wallet, and the remaining 70% is transferred to Stackers.

* Stacked CityCoins are transferred to the contract for the duration of the cycles
  * STX rewards for each cycle can be claimed after the cycle ends
  * Stacked CityCoins can be reclaimed after the final cycle ends
* Stacking rewards are distributed proportionately to the amount stacked, not in reward slots
* Reward cycles are also 2,100 Stacks blocks in length, but the maximum is 32 cycles

Additional common questions and answers can be found in the [Stacking Documentation](/core-protocol/stacking-citycoins#common-questions).


# Stacks Transactions

Creating, monitoring, and interacting with Stacks blockchain transactions.

## Stacks.js Libraries

These libraries include everything you need to work with the [Stacks blockchain](https://stacks.co).

* [Stacks.js Libraries](https://github.com/hirosystems/stacks.js)
* [Stacks.js Documentation](https://stacks.js.org)
* [micro-stacks Libraries](https://github.com/fungible-systems/micro-stacks/)
* [micro-stacks Documentation](https://docs.micro-stacks.dev/)

## Post-Conditions

By defining post conditions, users can create transactions that include pre-defined guarantees about what might happen in that contract.

One such post condition could be "I will transfer exactly 100 of X token", where "X token" is referenced as a specific contract's fungible token. When wallets and applications implement the transfer method, they should always use post conditions to specify that the user will transfer exactly the amount of tokens that they specify in the amount argument of the transfer function. Only in very specific circumstances should such a post condition not be included.

```
"post_conditions": [
    {
      "type": "fungible",
      "condition_code": "sent_equal_to",
      "amount": "241996",
      "principal": {
        "type_id": "principal_contract",
        "contract_name": "miamicoin-core-v1",
        "address": "SP466FNC0P7JWTNM2R9T199QRZN1MYEDTAR0KP27"
      },
      "asset": {
        "contract_name": "miamicoin-token",
        "asset_name": "miamicoin",
        "contract_address": "SP466FNC0P7JWTNM2R9T199QRZN1MYEDTAR0KP27"
      }
    }
  ],
```

Examples of how to use post-conditions are outlined in the [Code Examples](/developer-resources/code-examples).

## Fee Estimation

Depending on the number of transactions in the mempool, setting a competitive fee on a transaction can help ensure it's processed in a timely matter by Stacks miners.

Fees are automatically calculated by the [Hiro Web Wallet](https://wallet.hiro.so/wallet/install-web) when integrated.

Resources to view the Stacks mempool and more about Stacks transactions are below:

* [Haystack Mempool Explorer](https://haystack.tools/mempool)
* [Stacks data center: mempool](https://stacksdata.info/#mempool)
* [CityCoins: get network status script](https://github.com/citycoins/scripts/blob/main/src/get-network-status.ts)


# Additional Info

Community resources, implementations, and more.

See [CityCoins Resources](/citycoins-resources/general) for ways to connect with the community, plus applications and tools that support CityCoins.

Thanks to [Friedger](https://friedger.de) for a [great write-up on Stacking Pools](https://app.sigle.io/friedger.id/UOvy85BCSD-bjlrv_6q74) that was adapted for this guide.


# Activation

CityCoin contract functions related to activation and registration.

## Overview

The launch of a CityCoin happens in a three-step process:

1. The contract for a CityCoin is deployed mainnet on the Stacks blockchain
2. The auth contract is initialized (a one-time function to set everything up)
3. 20 unique wallets send a transaction to the contract signaling activation

Once the threshold is met, a 150 block (\~24hr) countdown begins after which anyone is eligible to try and mine the CityCoins within a given Stacks block.

There are no CityCoins issued or distributed prior to the start of mining.

## Details

Registration happens by calling the [`register-user`](#register-user) function in the CityCoin contract, which can be done with the [Stacks Web Wallet](https://hiro.so/wallet/install-web) through an interface like [minecitycoins.com](https://minecitycoins.com).

{% hint style="info" %}
An example of the code used in the CityCoins UI can be found in the [RegisterUser component](https://github.com/citycoins/citycoin-ui/blob/main/src/components/activation/RegisterUser.js) on GitHub.
{% endhint %}

A nominal transaction fee is required in order to send this transaction, paid in STX, and you can optionally include a memo of up to 50 characters that will be recorded on-chain.

Once the threshold is reached, the `register-user` function will:

* calculate the activation block height + the activation delay
* set the `core` as active in the core contract map in `auth`
* set the `token` as active and set the coinbase amounts and coinbase thresholds

  (based on the activation block height)
* set the coinbase amounts and thresholds in `core` to match that of `token`

## Functions

### [API Ref: Activation](https://api.citycoins.co/docs#tag/Activation)

### get-activation-block

Type: Read-only Function

Success: `(ok (var-get activationBlock)) returned as a uint`

Error: `ERR_CONTRACT_NOT_ACTIVATED u1005`

Returns the Stacks block height at which the city was activated, or an error if not.

### get-activation-delay

Type: Read-only Function

Returns: `(var-get activation-delay) as a uint`

Returns the activation delay for mining and stacking to become available.

### get-activation-status

Type: Read-only Function

Returns: `(var-get activationReached) as a boolean`

Returns the activation status of the contract.

get-activation-target

Type: Read-only Function

Returns: `(var-get activationTarget) as a uint`

Returns the activation target of the contract, which is the block mining and stacking will become available.

### get-activation-threshold

Type: Read-only Function

Returns: `(var-get activationThreshold) as uint`

Returns the number of users required to register for activation of the contract.

### get-registered-users-nonce

Type: Read-only Function

Returns: `(var-get usersNonce) as uint`

Returns the total number of registered users in the contract, including those registered after activation occurs.

### get-user-id

Type: Read-only Function

Input: `user as principal`

Returns: `(some uint) OR (none)`

Returns the user ID of a given principal.

### get-user

Type: Read-only Function

Input: `userId as uint`

Returns: `(some principal) OR (none)`

Returns the principal of a given user ID.

### register-user

Type: Public Function

Inputs: `optional memo as string-utf8, length 50`

Success: `(ok true)`&#x20;

Errors:

* `ERR_USER_ALREADY_REGISTERED u1001`
* `ERR_ACTIVATION_THRESHOLD_REACHED u1004`

Registration occurs through calling the `register-user` function in the contract, which optionally accepts up to 50 characters as a memo to record on-chain.


# Mining

CityCoin contract functions related to mining.

## Overview

Anyone can create a user interface for mining a CityCoin, one examples being [minecitycoins.com](https://minecitycoins.com).

Mining CityCoins happens by calling one of two functions in the contract: [`mine-tokens`](#mine-tokens) and [`mine-many`](#mine-many).

{% hint style="warning" %}
Miners can only participate once per block. Once STX are sent for mining a CityCoin **they are not returned,** they are distributed to the city's wallet and CityCoin Stackers.
{% endhint %}

A nominal transaction fee is required in order to send this transaction, paid in STX, and in a single mining transaction you can optionally include a memo that will be recorded on-chain.

## Details

To mine for a single block with `mine-tokens`:

* enter the amount you would like to bid for the block
* (optionally) enter a memo to be recorded on chain
* submit the transaction to the smart contract

To mine for multiple blocks with `mine-many`:

* select the number of blocks you would like to mine for
* enter the amount for each of the number of blocks selected
* submit the transaction to the smart contract

## Contract Functions

### [API Ref: Mining](https://api.citycoins.co/docs#tag/Mining)

### get-mining-stats-at-block

Type: Read-only Function

Input: `stacksHeight as uint`

Returns: `(some MiningStatsAtBlock) as a tuple` or `none`

Returns the mining stats at a given block height, including:

* `minersCount` -  total miners
* `amount` -  total amount committed
* `amountToCity` - amount transferred to city wallet
* `amountToStackers` - amount transferred to $MIA Stackers
* `rewardClaimed` - true/false if reward was claimed

### get-mining-stats-at-block-or-default

Type: Read-only Function

Input: `stacksHeight as uint`

Returns: `(some MiningStatsAtBlock) as a tuple, or defaults`

Returns the same as `get-mining-stats-at-block` above, except if no entry is found, returns the default structure of:

* `minersCount: 0`
* `amount: 0`
* `amountToCity: 0`
* `amountToStackers: 0`
* `rewardClaimed: false`

### has-mined-at-block

Type: Read-only Function

Input: `stacksHeight as uint` and `userId as uint`

Returns: `true` or `false`

Returns a boolean value indicating if the user's ID mined at a given block height.

### get-miner-at-block

Type: Read-only Function

Input: `stacksHeight as uint` and `userId as uint`

Returns: `(some MinersAtBlock) as a tuple` or `(none)`

Returns the mining stats for a given user ID and block height, including:

* `ustx` - total commitment in uSTX
* `lowValue` - used by VRF to determine winner
* `highValue` - used by VRF to determine winner
* `winner` - true/false updated *after* miner claims the reward

### get-miner-at-block-or-default

Type: Read-only Function

Input: `stacksHeight as uint` and `userId as uint`

Returns: `(some MinersAtBlock) as a tuple, or defaults`

Returns the same as `get-miner-at-block` above, except if no entry is found, returns the default structure of:

* `ustx: 0`
* `lowValue: 0`
* `highValue: 0`
* `winner: false`

### get-last-high-value-at-block

Type: Read-only Function

Input: `stacksHeight as uint`

Returns:`highValue as uint, or default (u0)`

Returns the last high value at a given block height, which is incremented with each miners' total commitment.

### get-block-winner-id

Type: Read-only Function

Input: `stacksHeight as uint`

Returns:  `(some userId) as uint` or `none`

Returns the user ID of the block winner *after* the  miner claims the reward.

### mine-tokens

Type: Public Function

Input: `amountUstx as uint` and `memo as buff 34 (optional)`

Success: `(ok true)`

Errors:

* `ERR_CONTRACT_NOT_ACTIVATED u1005`
* `ERR_USER_ALREADY_MINED u1006`
* `ERR_INSUFFICIENT_COMMITMENT u1007`
* `ERR_INSUFFICIENT_BALANCE u1008`
* `ERR_STACKING_NOT_AVAILABLE u1015`

Mining for a single block happens through calling the `mine-tokens` function in the contract, which optionally accepts up to 34 characters as a memo to record on-chain.

### mine-many

Type: Public Function

Input: `amounts as list of uints, up to 200`

Success: `(ok true)`

Errors:

* `ERR_CONTRACT_NOT_ACTIVATED u1005`
* `ERR_USER_ALREADY_MINED u1006`
* `ERR_INSUFFICIENT_COMMITMENT u1007`
* `ERR_INSUFFICIENT_BALANCE u1008`
* `ERR_STACKING_NOT_AVAILABLE u1015`

Mining for many blocks happens through calling the `mine-many` function in the contract, which accepts a list of amounts up to 200 items in length.


# Mining Claims

CityCoin contract functions related to mining claims.

## Overview

After miners send their STX to the contract, a winner is later calculated by a Verifiable Random Function (VRF) weighted by the individual miner's bid compared to the total miners' bids sent in that bloc&#x6B;*.*

{% hint style="info" %}
Example 1: Alice sends 10 STX and Bob sends 30 STX in a block. The total spent for the block is 40 STX.

* Alice has a 25% chance of winning (10/40 STX)
* Bob has a 75% chance of winning (30/40 STX)
  {% endhint %}

{% hint style="info" %}
Example 2: Alice sends 20 STX, Bob sends 30 STX, Carol sends 50 STX, and Dave sends 100 STX in a block. The total spent for the block is 200 STX.

* Alice has a 10% chance of winning (20/200)
* Bob has a 15% chance of winning (30/200)
* Carol has a 25% chance of winning (50/200)
* Dave has a 50% chance of winning (100/200)
  {% endhint %}

Claiming a mining reward happens by calling the [`claim-mining-reward`](#claim-mining-reward) function in the contract.

## Details

Miners must wait for a maturity window of 100 blocks (\~16 hours) before they can know the winner of a given block in order to protect the VRF seed.

After this window passes miners can claim their CityCoin block rewards at any time.

{% hint style="info" %}
CityCoins are not minted until miners claim them, and therefore the total supply will only increase when miners claim their CityCoins.
{% endhint %}

If the user won the block, the transaction will succeed and mint them the block reward per the [Emissions Schedule](/core-protocol/token-configuration#emissions-schedule).

{% hint style="warning" %}
If a user did not win the block, the transaction will fail.

Optionally, a user can call the [`is-block-winner`](#is-block-winner) and [`can-claim-mining-reward`](#can-claim-mining-reward) functions to see if their address can claim a given block before submitting the claim transaction.
{% endhint %}

## Functions

### [API Ref: Mining Claims](https://api.citycoins.co/docs#tag/Mining-Claims)

### claim-mining-reward

Type: Public Function

Input: `minerBlockHeight as uint`

Success: `(ok true)`

Errors:

* `ERR_USER_NOT_FOUND u1002`
* `ERR_USER_ID_NOT_FOUND u1003`
* `ERR_USER_DID_NOT_MINE_IN_BLOCK u1009`
* `ERR_CLAIMED_BEFORE_MATURITY u1010`
* `ERR_NO_MINERS_AT_BLOCK u1011`
* `ERR_REWARD_ALREADY_CLAIMED u1012`
* `ERR_MINER_DID_NOT_WIN u1013`
* `ERR_NO_VRF_SEED_FOUND u1014`
* `ERR_CLAIM_IN_WRONG_CONTRACT u1020`

Claiming mining rewards happens through calling the `claim-mining-reward` function in the contract, which accepts the block height the miner mined in, and checks if the VRF value is between the `lowValue` and `highValue` for the miner.

If the miner won the block, then the coinbase is minted for them based on block height of the claim and the [emissions schedule](/core-protocol/token-configuration#emissions-schedule).

### is-block-winner

Type: Read-only Function

Input: `user as principal` and `minerBlockHeight as uint`

Returns: `true` or `false`

Returns a boolean value indicating if the user's principal won at a given block height.

*Note: this function will always return false if the token maturity window of 100 blocks did not pass.*

### can-claim-mining-reward

Type: Read-only Function

Input: `user as principal` and `minerBlockHeight as uint`

Returns: `true` or `false`

Returns a boolean value indicating if the user's principal won and is eligible to claim the block reward at a given block height.

*Note: this function will always return false if the token maturity window of 100 blocks did not pass.*


# Stacking

CityCoin contract functions related to stacking.

## Overview

Anyone can create a user interface for Stacking CityCoins, one example being [minecitycoins.com](https://minecitycoins.com).

Stacking CityCoins happens by calling the contract function [`stack-tokens`](#stack-tokens).

{% hint style="warning" %}
You cannot Stack in the currently active reward cycle, only for the next reward cycle.

*e.g. if you select to Stack in a block height in reward cycle 1 then Stacking will begin in reward cycle 2.*
{% endhint %}

A nominal transaction fee is required in order to send this transaction, paid in STX.

## Details

The current reward cycle for a given block height can be found by calling [`get-reward-cycle`](#get-reward-cycle) in the core contract and supplying the block height.

Stacking statistics for a given cycle are available through [`get-stacking-stats-at-cycle`](#get-stacking-stats-at-cycle), and individual account Stacking details are available through [`get-stacker-at-cycle`](#get-stacker-at-cycle).

{% hint style="info" %}
Both functions for Stacking information also include a `-or-default` version that returns empty default values instead of `some` or `none` Clarity types.
{% endhint %}

To Stack CityCoins for a user with `stack-tokens`:

* enter the amount of CityCoins to Stack
* enter the number of reward cycles to Stack for
* submit the transaction to the smart contract

## Contract Functions

### [API Ref: Stacking](https://api.citycoins.co/docs#tag/Stacking)

### get-stacking-stats-at-cycle

Type: Read-only Function

Input: `rewardCycle as uint`

Returns: `(some StackingStatsAtCycle) as a tuple` or `(none)`

Returns the stacking stats at a given reward cycle, including:

* `amountUstx` - total rewards from miners in uSTX
* `amountToken` - total CityCoins Stacked

### get-stacking-stats-at-cycle-or-default

Type: Read-only Function

Input: `rewardCycle as uint`

Returns: `(some StackingStatsAtCycle) as a tuple, or defaults`

Returns the same as `get-stacking-stats-at-cycle` above, except if no entry is found, returns the default structure of:

* `amountUstx: 0`
* `amountToken: 0`

### get-stacker-at-cycle

Type: Read-only Function

Input: `rewardCycle as uint` and `userId as uint`

Returns: `(some StackerAtCycle) as a tuple` or `(none)`

Returns the stacking stats for a given user ID and reward cycle, including:

* `amountStacked` - the total amount of CityCoins Stacked
* `toReturn` - the total amount of CityCoins that can be reclaimed from the contract

### get-stacker-at-cycle-or-default

Type: Read-only Function

Input: `rewardCycle as uint` and `userId as uint`

Returns: `(some StackerAtCycle) as a tuple, or defaults`

Returns the same as `get-stacker-at-cycle` above, except if no entry is found, returns the default structure of:

* `amountStacked: 0`
* `toReturn: 0`

### get-reward-cycle

Type: Read-only Function

Input: `stacksHeight as uint`

Returns: `(some rewardCycle) as uint` or `(none)`

Returns the active reward cycle for a given block height.

### stacking-active-at-cycle

Type: Read-only Function

Input: `rewardCycle as uint`

Returns: `true` or `false`

Returns a boolean value indicating if stacking is active at a given reward cycle, meaning a positive number of CityCoins are Stacked for that cycle.

### get-first-stacks-block-in-reward-cycle

Type: Read-only Function

Input: `rewardCycle as uint`

Returns: `firstBlockInCycle as uint`

Returns the starting Stacks block height for a given reward cycle.

### stack-tokens

Type: Public Function

Input: `amountTokens as uint` and `lockPeriod as uint`

Success: `(ok true)`

Errors:

* `ERR_CONTRACT_NOT_ACTIVATED u1005`
* `ERR_STACKING_NOT_AVAILABLE u1015`
* `ERR_CANNOT_STACK u1016`

Stacking happens through calling the `stack-tokens` function in the contract, which accepts an amount of CityCoins to Stack in addition to a number of reward cycles to Stack them for.


# Stacking Claims

CityCoin contract functions related to stacking claims.

## Overview

After CityCoins are Stacked in the contract, Stackers are required to claim their rewards and unlocked CityCoins after a cycle ends.

Claiming rewards from Stacking CityCoins happens by calling the contract function [`claim-stacking-rewards`](#claim-stacking-reward).

## Details

The payouts are based on the amount Stacked by the user `R`, the total STX reward that cycle `S`, and the total of all Stackers`T`using the formula:\
`STX Rewards = (R * S) / T`

## Contract Functions

### [API Ref: Stacking Claims](https://api.citycoins.co/docs#tag/Stacking-Claims)

### claim-stacking-reward

Type: Public Function

Input: `targetCycle as uint`

Success: `(ok true)`

Errors:

* `ERR_USER_ID_NOT_FOUND u1003`
* `ERR_STACKING_NOT_AVAILABLE u1015`
* `ERR_REWARD_CYCLE_NOT_COMPLETED u1017`
* `ERR_NOTHING_TO_REDEEM u1018`

Claiming Stacking rewards happens through calling the `claim-stacking-reward` function in the contract, which accepts a reward cycle and checks both the entitled STX reward from miners and the amount of CityCoins to return, then transfers them to the user.

### get-stacking-reward

Type: Read-only Function

Input: `userId as uint` and `targetCycle as uint`

Returns: `entitledStackingReward as uint, or default (u0)`

Returns the amount of STX a user can claim in a given reward cycle in uSTX. This method will only return a positive value if:

* the current block height is in a subsequent reward cycle
* the Stacker locked up CityCoins in the target reward cycle
* the Stacker locked up *enough* CityCoins to receive at least one uSTX


# Token

CityCoin contract functions related to CityCoin tokens.

## Overview

The CityCoins token contract exists separate from the CityCoins core contract as part of the protocol, however there are some functions used by the core contract to interact with the token.

In addition to those functions, the token contract fully supports the [SIP-010 fungible token standard](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md) on the Stacks blockchain, including functions for [`transfer`](#transfer), [`get-balance`](#get-balance), and more.

CityCoins also support the [`send-many`](#send-many) function, allowing up to 200 transfer operations to be performed in a single transaction.

## Details

{% hint style="info" %}
CityCoins have 6 decimals, denoted with u for micro-.<br>

1 CityCoin = 1,000,000 micro-CityCoin

1 MIA = 1,000,000 uMIA

1 NYC = 1,000,000 uNYC
{% endhint %}

### Minting

CityCoins can only be minted by a core contract as part of the mining claim process.

CityCoins are not minted until miners claim them.

### Burning

CityCoins can be burned by their owners following the same checks and balances as the transfer function.

## Contract Functions

### [API Ref: Token](https://api.citycoins.co/docs#tag/Token)

### activate-token

Type: Public Function

Input: `coreContract as principal` and `stacksHeight as uint`

Success: `(ok true)`

Errors:

* `ERR_UNAUTHORIZED u2000`
* `ERR_TOKEN_ALREADY_ACTIVATED u2002`

A one-time use function to activate the token halving as defined in the [emissions schedule](/core-protocol/token-configuration#emissions-schedule) at a given Stacks block height. This function must be called by an active core contract, and once called, cannot be used again.

### get-coinbase-thresholds

*Note: this function is available both in the CityCoin core contract and the CityCoin token contract.*

Type: Read-only Function

Input: `none`

Returns: `(ok (coinbaseThresholds)) as a tuple` or `error`

Errors:

* citycoin-core: `ERR_CONTRACT_NOT_ACTIVATED u1005`
* citycoin-token: `ERR_TOKEN_NOT_ACTIVATED u2001`

Returns the coinbase thresholds based on the Stacks block height the token was activated, based on the [emissions schedule](/core-protocol/token-configuration#emissions-schedule) as a tuple.

* `coinbaseThreshold1` - bonus + first epoch
* `coinbaseThreshold2` - second epoch
* `coinbaseThreshold3` - third epoch
* `coinbaseThreshold4` - fourth epoch
* `coinbaseThreshold5` - fifth epoch

Note: after each threshold is completed above, the perpetual block reward will remain at 3,125 CityCoins per block based on the sixth epoch in the [emissions schedule](/core-protocol/token-configuration#emissions-schedule).

### get-coinbase-amount

Type: Read-only Function

Input: `minerBlockHeight as uint`

Returns: `mintedTokens as uint` based on the [emissions schedule](/core-protocol/token-configuration#emissions-schedule) at the given block height

### set-token-uri

Type: Public Function

Input: `newUri as optional string-utf8 256`

Success: `(ok true)`

Errors:

* `ERR_UNAUTHORIZED u2000`

Updating the token URI ([example: MiamiCoin](https://cdn.citycoins.co/metadata/miamicoin.json)) happens through calling the `set-token-uri` function, which accepts a new URI as an optional parameter.

### send-many

Type: Public Function

Input: `recipients as list of tuples, up to 200, including:`

* `to as principal`
* `amount as uint`
* `memo as optional buff 34`

Success: `(ok true)`

Errors:

* `ERR_UNAUTHORIZED u2000`

Sending to many recipients happens through calling the `send-many` function in the token contract, which accepts a list up to 200 items in length.

### burn

Type: Public Function

Input: `amount as uint` and `owner as principal`

Success: `(ok true)`

Errors:

* `ERR_UNAUTHORIZED u2000`

Allows a user or contract to burn tokens with the same guards as token transfers.

### convert-to-v2

Type: Public Function

Input: `none`

Success: `(ok true)`

Errors:

* `ERR_V1_BALANCE_NOT_FOUND u2003`

This function checks the V1 CityCoin balance for the user, burns the V1 amount, and mints the equivalent V2 CityCoin amount.

## SIP-010 Functions

[SIP-010](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md) is the standard for fungible tokens on the Stacks blockchain, similar to ERC-20 on Ethereum. As part of the standard, all SIP-010 compliant tokens use the functions defined below.

### transfer

Type: Public Function

Input: `amount as  uint`, `from as principal`, `to as principal`, `memo as  optional buff 34`

Success: `(ok true)`

Errors:

* `ERR_UNAUTHORIZED u2000`

Transferring CityCoins from one account to another happens through calling the `transfer` function in the token contract, which accepts information about the transfer and an optional memo that is printed on-chain.

### get-name

Type: Read-only Function

Input: `none`

Returns: `(ok tokenName)`

Returns the full name of a CityCoin.

### get-symbol

Type: Read-only Function

Input: `none`

Returns: `(ok tokenSymbol)`

Returns the symbol of a CityCoin.

### get-decimals

Type: Read-only Function

Input: `none`

Returns: `(ok tokenDecimals)`

Returns the number of decimals used for a CityCoin.

### get-balance

Type: Read-only Function

Input: `user as principal`

Returns: `(ok balance)`

Returns the balance for a given user's principal.

### get-total-supply

Type: Read-only Function

Input: `none`

Returns: `(ok totalSupply)`

Returns the total supply for a CityCoin.

*Note: the total supply only increases when miners claim their mining reward.*

### get-token-uri

Type: Read-only Function

Input: `none`

Returns: `(ok tokenUri)`

Returns the token URI for a CityCoin.


