# Introduction

What is CryptoCash?

[CryptoCash](https://stackers.cc) is a suite of open source [smart contracts](https://docs.stacks.co/clarity/overview) deployed on the [Stacks](https://stacks.co) blockchain, designed to support users via earning rewards in the form of CryptoCash & STX while [Mining](/introduction/mining-cryptocash) & [Stacking](/introduction/stacking-cryptocash).

CryptoCash's core features are: **Transferring**, **Mining**, **Stacking**, and **Programming**.&#x20;

* Anyone can Transfer CryptoCash by sending a `transfer` transaction to [.cryptocash-token](/latest/contracts/.cryptocash-token)\
  *(not your keys not your tokens) (no blacklists)*<br>
* Anyone can Mine CryptoCash by sending a `mine` transaction to [.cryptocash-core](/latest/contracts/.cryptocash-core) \
  (learn more about [Mining CryptoCash](/introduction/mining-cryptocash))<br>
* Anyone can Stack CryptoCash by sending a `stack` transaction to [.cryptocash-core](/latest/contracts/.cryptocash-core)\
  (learn more about [Stacking CryptoCash](/introduction/stacking-cryptocash))<br>
* Anyone can Program CryptoCash by using [Clarity](https://clarity-lang.org/), the smart contracting language on Stacks.\
  (enabling endless opportunities for entrepreneurs, developers, & engineers.)

Use the navigation on the left to learn more about CryptoCash


# Mining CryptoCash

An overview of the mining process of the CryptoCash protocol

Anyone can mine for CryptoCash by sending a `mine` transaction to the CryptoCash smart contract on the Stacks blockchain.

There are no hardware requirements and the protocol is open source, so anyone can build a web app/site that interacts with it.

{% hint style="warning" %}
**Miners can only participate once per block.**&#x20;
{% endhint %}

{% hint style="warning" %}
**Once STX is sent for mining CryptoCash, it is not returned.**\
\[STX is distributed to CryptoCash Stackers(95%) & Foundation (5%)**.**]
{% endhint %}

## **How it Works**

CryptoCash miners spend STX while competing to earn the CryptoCash block reward, which follows are halving emission schedule and begins at 3,200 CryptoCash per block.

* 95% of the STX that miners spend is are distributed to the people who Stacked their CryptoCash (Stackers)
* 5% of the STX that miners spend is sent directly the Foundation wallet.

{% hint style="warning" %}
**There is only one winning Miner per block that can claim the CryptoCash reward.**
{% endhint %}

<figure><img src="https://427742790-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FRq3PQcwTVzrBEgLX1rmG%2Fuploads%2Fww2OBKmqUJhIVUmYsSRJ%2FCC%20per%20STX_updated.gif?alt=media&amp;token=a3c6215a-8370-48fa-83c2-31c0020b063b" alt=""><figcaption></figcaption></figure>


# Stacking CryptoCash

An overview of the stacking process of the CryptoCash protocol

Anyone can *stack* CryptoCash by sending a `stack` transaction to the CryptoCash smart contract on the Stacks blockchain.

There are no hardware requirements and the protocol is open source, so anyone can build a web app/site that interacts with it.

{% hint style="warning" %}
**You cannot Stack in the currently active reward cycle, only for the next reward cycle(s).**\
*(eg if you called the stack function during cycle u2, your Stacking begins in cycle u3)*
{% endhint %}

{% hint style="warning" %}
**The amount of CryptoCash you Stack will be transferred to the smart contract and returned/unlocked upon claiming your final reward cycle.**&#x20;
{% endhint %}

## How it Works

CryptoCash miners spend STX while competing to earn the CryptoCash block reward, which follows are halving emission schedule and begins at 3,200 CryptoCash per block.

* 95% of the STX that miners spend is are distributed to the people who Stacked their CryptoCash (Stackers)
* 5% of the STX that miners spend is sent directly the Foundation wallet.

{% hint style="warning" %}
**Each Stacker receives rewards proportionate to what they stacked against the total amount of Stacked CryptoCash for the given reward cycle.**
{% endhint %}

<figure><img src="https://427742790-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FRq3PQcwTVzrBEgLX1rmG%2Fuploads%2Fww2OBKmqUJhIVUmYsSRJ%2FCC%20per%20STX_updated.gif?alt=media&amp;token=a3c6215a-8370-48fa-83c2-31c0020b063b" alt=""><figcaption></figcaption></figure>

**Is there a cooldown between cycles?**

Yes, when you are finished Stacking and reclaim your CryptoCash, you can then restack for the next cycle, however your stacking will begin the following Cycle.

**Can I Stack additional CryptoCash for a cycle?**

Yes, if you call the `stack` function before the cycle in question starts. However you can not add to a cycle that is currently active, eg you must invoke the `stack` call prior to the start of a target cycle.


# Token Configuration

An overview of the token configuration of the CryptoCash protocol

## Overview

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

Once the CryptoCash contracts are deployed and activated, the emission schedule begins and winning miners mint the CryptoCash into existence.&#x20;

CryptoCash can be sent & received using a STX address, used for payments in smart contracts, and more.&#x20;

## Emissions Schedule

Miners receive coinbase rewards for mining CryptoCash, the amount is dependent on what block they mined. Each Epoch has a different reward per block.&#x20;

<table data-header-hidden><thead><tr><th width="97" align="center"></th><th width="162"></th><th width="164"></th><th></th></tr></thead><tbody><tr><td align="center">Epoch</td><td>Blocks per Epoch</td><td>Reward per Block</td><td>Max Total Supply (at end of Epoch)</td></tr><tr><td align="center">0</td><td>210,000</td><td>3200</td><td>672,000,000</td></tr><tr><td align="center">1</td><td>210,000</td><td>1600</td><td>1,008,000,000</td></tr><tr><td align="center">2</td><td>210,000</td><td>800</td><td>1,176,000,000</td></tr><tr><td align="center">3</td><td>210,000</td><td>400</td><td>1,260,000,000</td></tr><tr><td align="center">4</td><td>210,000</td><td>200</td><td>1,302,000,000</td></tr><tr><td align="center">5</td><td>continuous</td><td>100</td><td>1,302,000,000 (+100 per new block)</td></tr></tbody></table>

{% hint style="info" %}
After the final halving (from epoch 4 to 5) the total supply will increase by 100 every newly mined block.
{% endhint %}


# History

Origin of CryptoCash

CryptoCash ("CC") was created by the founders of [Derupt](https://derupt.io), in response to [CCIP-020](https://github.com/citycoins/governance/pull/30)&#x20;

CC was inspired by CityCoins, but has some key differences:

* CC Mining halving only, unlike CityCoins, CC does not have early block bonuses leading to whales.&#x20;
* CC Mining rewards claims multiple blocks at a time, up to 200x more efficient than CityCoins.
* CC Stacking, 95% of Miner input (STX) is proportionally yielded (CityCoins was only 70%).
* CC Stacking reward claims multiple cycles at a time, up to 32x more efficient than CityCoins.
* CC has a Foundation that improves the user experience & does not have ties to City governments.
* CC is unstoppable, unlike CityCoins, CC does not have any shut down functionality.


# Contracts

Explore the documentation for the CryptoCash Smart Contracts.

{% content-ref url="/pages/BMxHDvXzOEbqQ1GCG9ra" %}
[Testnet Addresses (old)](/archives/testnet-contracts/testnet-old)
{% endcontent-ref %}

{% content-ref url="/pages/dCyOV0IFvUNtgH4ksLMo" %}
[Mainnet Addresses](/latest/contracts/mainnet)
{% endcontent-ref %}

{% content-ref url="/pages/AEllMXhp7ssG4flGWOqM" %}
[.cryptocash-vrf](/latest/contracts/.cryptocash-vrf)
{% endcontent-ref %}

{% content-ref url="/pages/T1C2d6d9nLcomEJ0LvsC" %}
[.cryptocash-token-trait](/latest/contracts/.cryptocash-token-trait)
{% endcontent-ref %}

{% content-ref url="/pages/S7Ukx0pIecZxSWmZPusV" %}
[.cryptocash-core-trait](/latest/contracts/.cryptocash-core-trait)
{% endcontent-ref %}

{% content-ref url="/pages/lielvJFeRjS02PvvufxU" %}
[.cryptocash-token](/latest/contracts/.cryptocash-token)
{% endcontent-ref %}

{% content-ref url="/pages/fCPF9vgGwU5LjcibRMSv" %}
[.cryptocash-core](/latest/contracts/.cryptocash-core)
{% endcontent-ref %}


# Testnet Addresses

Deployed by: ST1ZK4MRVTQQJMVAAJQWBV2WPQ87QV2851YCTHD7X

**View CryptoCash Testnet Contracts on Explorer:**

* [.cryptocash-vrf](https://explorer.hiro.so/txid/0xa3bc0bdf3200b5992f4b24326fd451979988a71ae763427e40c26321002a811c?chain=testnet)
* [.cryptocash-token-trait](https://explorer.hiro.so/txid/0x96ab312bf7a9acea8edbf848b9010ae7b5f96741d7966157b7ac519f48956b61?chain=testnet)
* [.cryptocash-core-trait](https://explorer.hiro.so/txid/0xdaa189acf8ec6fb558768a3f9edf79abf7abe979ac67a81c52dc33fc1116aa38?chain=testnet)
* [.cryptocash-token](https://explorer.hiro.so/txid/0x714db9888ab68f76decf4a81e97cc376cfe74e17748ad6ef215ccb0122304ab7?chain=testnet)
* [.cryptocash-core](https://explorer.hiro.so/txid/0x87f659ef8fd78cb40f192a323f6f72cfda95eec5b4248b88e03626d47ca27d1a?chain=testnet)

Other sips deployed

* [.sip-009-trait-nft-standard](https://explorer.hiro.so/txid/0x615cfbd1d65ca58ec9be371052b96127c4dd84a176d1db3ea569fb8b338999cd?chain=testnet)
* [.sip-010-trait-ft-standard](https://explorer.hiro.so/txid/0x5ad5763016549b35a62182bdff2f7833e617aee6fe66d94cdbbc7cb038087fa7?chain=testnet)
* [.sip-013-trait-sft-standard](https://explorer.hiro.so/txid/0xc17800fa3b05e6cce40e0cc28c948977feef5971c894148d9de3f4efe4e5cdb3?chain=testnet)


# Mainnet Addresses

Deployed by YTBD

**View CryptoCash Mainnet Contracts on Explorer:**

* .cryptocash-vrf
* .cryptocash-token-trait
* .cryptocash-core-trait
* .cryptocash-token
* .cryptocash-core

Other sips deployed

* .sip-009-trait-nft-standard
* .sip-010-trait-ft-standard
* .sip-013-trait-sft-standard


# .cryptocash-vrf

.cryptocash-vrf contract documentation

{% hint style="info" %}
Work in Progress
{% endhint %}

```
;; title: cryptocash-vrf
;; version: 1.3.1
;; summary: CryptoCash VRF Contract
;; description: used to randomly select the winners of mining. 

;; Read the on-chain burn block header-hash and turn the lower 16 bytes into a uint
;; in order to sample the set of miners and determine
;; which one may claim the token batch for the given block height.
(define-read-only (get-random-uint-at-block (blockHeight uint))
  (let (
    (vrf-lower-uint-opt
      (match (get-burn-block-info? header-hash blockHeight)
        header-hash (some (buff-to-uint-le (lower-16-le header-hash)))
        none))
  )
  (print {event:"get-random-uint-at-block", blockHeight: blockHeight, hash: vrf-lower-uint-opt})
  vrf-lower-uint-opt)
)

;; ;; UTILITIES

;; ;; lookup table for converting 1-byte buffers to uints via index-of
(define-constant BUFF_TO_BYTE (list 
    0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0a 0x0b 0x0c 0x0d 0x0e 0x0f
    0x10 0x11 0x12 0x13 0x14 0x15 0x16 0x17 0x18 0x19 0x1a 0x1b 0x1c 0x1d 0x1e 0x1f
    0x20 0x21 0x22 0x23 0x24 0x25 0x26 0x27 0x28 0x29 0x2a 0x2b 0x2c 0x2d 0x2e 0x2f
    0x30 0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 0x39 0x3a 0x3b 0x3c 0x3d 0x3e 0x3f
    0x40 0x41 0x42 0x43 0x44 0x45 0x46 0x47 0x48 0x49 0x4a 0x4b 0x4c 0x4d 0x4e 0x4f
    0x50 0x51 0x52 0x53 0x54 0x55 0x56 0x57 0x58 0x59 0x5a 0x5b 0x5c 0x5d 0x5e 0x5f
    0x60 0x61 0x62 0x63 0x64 0x65 0x66 0x67 0x68 0x69 0x6a 0x6b 0x6c 0x6d 0x6e 0x6f
    0x70 0x71 0x72 0x73 0x74 0x75 0x76 0x77 0x78 0x79 0x7a 0x7b 0x7c 0x7d 0x7e 0x7f
    0x80 0x81 0x82 0x83 0x84 0x85 0x86 0x87 0x88 0x89 0x8a 0x8b 0x8c 0x8d 0x8e 0x8f
    0x90 0x91 0x92 0x93 0x94 0x95 0x96 0x97 0x98 0x99 0x9a 0x9b 0x9c 0x9d 0x9e 0x9f
    0xa0 0xa1 0xa2 0xa3 0xa4 0xa5 0xa6 0xa7 0xa8 0xa9 0xaa 0xab 0xac 0xad 0xae 0xaf
    0xb0 0xb1 0xb2 0xb3 0xb4 0xb5 0xb6 0xb7 0xb8 0xb9 0xba 0xbb 0xbc 0xbd 0xbe 0xbf
    0xc0 0xc1 0xc2 0xc3 0xc4 0xc5 0xc6 0xc7 0xc8 0xc9 0xca 0xcb 0xcc 0xcd 0xce 0xcf
    0xd0 0xd1 0xd2 0xd3 0xd4 0xd5 0xd6 0xd7 0xd8 0xd9 0xda 0xdb 0xdc 0xdd 0xde 0xdf
    0xe0 0xe1 0xe2 0xe3 0xe4 0xe5 0xe6 0xe7 0xe8 0xe9 0xea 0xeb 0xec 0xed 0xee 0xef
    0xf0 0xf1 0xf2 0xf3 0xf4 0xf5 0xf6 0xf7 0xf8 0xf9 0xfa 0xfb 0xfc 0xfd 0xfe 0xff
))

;; ;; Convert a 1-byte buffer into its uint representation.
(define-private (buff-to-u8 (byte (buff 1)))
  (unwrap-panic (index-of BUFF_TO_BYTE byte))
)

;; ;; Inner fold function for converting a 16-byte buff into a uint.
(define-private (add-and-shift-uint-le (idx uint) (input { acc: uint, data: (buff 16) }))
  (let (
    (acc (get acc input))
    (data (get data input))
    (byte (buff-to-u8 (unwrap-panic (element-at data idx))))
  )
  (print {
    event:"add-and-shift-uint-le",
    acc: (+ (* byte (pow u2 (* u8 (- u15 idx)))) acc),
    data: data
  })
  {
    acc: (+ (* byte (pow u2 (* u8 (- u15 idx)))) acc),
    data: data
  })
)

;; ;; Convert the lower 16 bytes of a buff into a little-endian uint.
(define-private (lower-16-le (input (buff 32)))
  (get acc
    (fold lower-16-le-closure (list u16 u17 u18 u19 u20 u21 u22 u23 u24 u25 u26 u27 u28 u29 u30 u31) { acc: 0x, data: input })
  )
)

;; ;; Inner closure for obtaining the lower 16 bytes of a 32-byte buff
(define-private (lower-16-le-closure (idx uint) (input { acc: (buff 16), data: (buff 32) }))
  (let (
    (acc (get acc input))
    (data (get data input))
    (byte (unwrap-panic (element-at data idx)))
  )
  (print {
    acc: (unwrap-panic (as-max-len? (concat acc byte) u16)),
    data: data
  })
  {
    acc: (unwrap-panic (as-max-len? (concat acc byte) u16)),
    data: data
  })
)
```


# .cryptocash-token-trait

.cryptocash-token-trait contract documentation

{% hint style="info" %}
Work in Progress
{% endhint %}

```
;; title: cryptocash-token-trait
;; version: 1.3.1
;; summary: CryptoCash Token Trait Contract

(define-trait cryptocash-token
  (
    (activate-token (uint)
      (response bool uint)
    )

    (set-token-uri ((optional (string-utf8 256)))
      (response bool uint)
    )

    (mint (uint principal)
      (response bool uint)
    )

    (burn (uint principal)
      (response bool uint)
    )

    (transfer (uint principal principal (optional (buff 34))) (response bool uint))

    (get-name () (response (string-ascii 32) uint))

    (get-symbol () (response (string-ascii 32) uint))

    (get-decimals () (response uint uint))

    (get-balance (principal) (response uint uint))

    (get-total-supply () (response uint uint))

    (get-token-uri () (response (optional (string-utf8 256)) uint))

    (send-many ((list 200 { to: principal, amount: uint, memo: (optional (buff 34)) }))
      (response bool uint)
    )
  )
)
```


# .cryptocash-core-trait

.cryptocash-core-trait contract documentation

{% hint style="info" %}
Work in Progress
{% endhint %}

```
;; title: cryptocash-core-trait
;; version: 1.3.1
;; summary: CryptoCash Core Trait Contract

(define-trait cryptocash-core
  (
    (mine ((list 200 uint))
      (response bool uint)
    )

    (claim-mining-reward (uint)
      (response bool uint)
    )

    (stack (uint uint)
      (response bool uint)
    )

    (claim-stacking-reward (uint)
      (response bool uint)
    )

    (set-foundation-wallet (principal)
      (response bool uint)
    )   

  )
)
```


# .cryptocash-token

.cryptocash-token contract documentation

{% hint style="info" %}
Work in Progress
{% endhint %}

````
;; title: cryptocash-token
;; version: 1.3.1
;; summary: CryptoCash Token Contract
;; description: used to handle CryptoCash token logic

;; CONTRACT OWNER
(define-constant CONTRACT_OWNER tx-sender)

;; TRAIT DEFINITIONS
(impl-trait .cryptocash-token-trait.cryptocash-token)
(use-trait coreTrait .cryptocash-core-trait.cryptocash-core)

;; ERROR CODES
(define-constant ERR_UNAUTHORIZED u2000)
(define-constant ERR_TOKEN_NOT_ACTIVATED u2001)
(define-constant ERR_TOKEN_ALREADY_ACTIVATED u2002)
(define-constant ERR_INVALID_AMOUNT u2003)
(define-constant ERR_SELF_TRANSFER u2004)
(define-constant ERR_INVALID_URI u2005)
(define-constant ERR_INVALID_RECIPIENT u2006)

(define-constant cryptocash-core .cryptocash-core)

;; SIP-010 DEFINITION
(impl-trait 'ST1ZK4MRVTQQJMVAAJQWBV2WPQ87QV2851YCTHD7X.sip-010-trait-ft-standard.sip-010-trait)

(define-fungible-token CC)

;; SIP-010 FUNCTIONS
(define-public (transfer (amount uint) (from principal) (to principal) (memo (optional (buff 34))))
  (begin
    (asserts! (is-eq from tx-sender) (err ERR_UNAUTHORIZED))
    (asserts! (not (is-eq from to)) (err ERR_SELF_TRANSFER))
    (asserts! (> amount u0) (err ERR_INVALID_AMOUNT))
    (if (is-some memo)
      (print memo)
      none
    )
    (ft-transfer? CC amount from to)
  )
)


(define-read-only (get-name)
  (ok "CryptoCash")
)

(define-read-only (get-symbol)
  (ok "CC")
)

(define-read-only (get-decimals)
  (ok u0)
)

(define-read-only (get-balance (user principal))
  (ok (ft-get-balance CC user))
)

(define-read-only (get-total-supply)
  (ok (ft-get-supply CC))
)

(define-read-only (get-token-uri)
  (ok (var-get tokenUri))
)

;; TOKEN CONFIGURATION

;; how many blocks until the next halving occurs
(define-constant TOKEN_HALVING_BLOCKS u210000)

;; store block height at each halving, set by register-user in core contract 
(define-data-var coinbaseThreshold1 uint u0)
(define-data-var coinbaseThreshold2 uint u0)
(define-data-var coinbaseThreshold3 uint u0)
(define-data-var coinbaseThreshold4 uint u0)
(define-data-var coinbaseThreshold5 uint u0)

;; once activated, thresholds cannot be updated again
(define-data-var tokenActivated bool false)

;; core contract states
(define-constant STATE_DEPLOYED u0)
(define-constant STATE_ACTIVE u1)
(define-constant STATE_INACTIVE u2)

;; one-time function to activate the token
(define-public (activate-token (blockHeight uint))
  (begin
    (asserts! (> blockHeight u0) (err ERR_UNAUTHORIZED))
    (asserts! (is-eq CONTRACT_OWNER tx-sender) (err ERR_UNAUTHORIZED))
    (asserts! (not (var-get tokenActivated)) (err ERR_TOKEN_ALREADY_ACTIVATED))
    (var-set tokenActivated true)
    (var-set coinbaseThreshold1 (+ blockHeight TOKEN_HALVING_BLOCKS))
    (var-set coinbaseThreshold2 (+ blockHeight (* u2 TOKEN_HALVING_BLOCKS)))
    (var-set coinbaseThreshold3 (+ blockHeight (* u3 TOKEN_HALVING_BLOCKS)))
    (var-set coinbaseThreshold4 (+ blockHeight (* u4 TOKEN_HALVING_BLOCKS)))
    (var-set coinbaseThreshold5 (+ blockHeight (* u5 TOKEN_HALVING_BLOCKS)))
    (ok true)
 )
)

;; return coinbase thresholds if token activated
(define-read-only (get-coinbase-thresholds)
  (let
    (
      (activated (var-get tokenActivated))
    )
    (asserts! activated (err ERR_TOKEN_NOT_ACTIVATED))
    (ok {
      coinbaseThreshold1: (var-get coinbaseThreshold1),
      coinbaseThreshold2: (var-get coinbaseThreshold2),
      coinbaseThreshold3: (var-get coinbaseThreshold3),
      coinbaseThreshold4: (var-get coinbaseThreshold4),
      coinbaseThreshold5: (var-get coinbaseThreshold5)
    })
  )
)

;; UTILITIES

(define-data-var tokenUri (optional (string-utf8 256)) (some u"https://stackers.cc/cryptocash.json"))

;; set token URI to new value, only accessible by Auth
(define-public (set-token-uri (newUri (optional (string-utf8 256))))
    (begin
        (try! (is-authorized-auth)) ;; Check authorization, returns error if unauthorized
        (asserts! (not (is-none newUri)) (err ERR_INVALID_URI)) ;; Ensure `newUri` is present

        (ok (var-set tokenUri newUri))
    )
)

;; mint new tokens, only accessible by a Core contract
(define-public (mint (amount uint) (recipient principal))
    (let
        (
            (check (is-eq contract-caller cryptocash-core))
        )
        (begin
            (asserts! check (err ERR_UNAUTHORIZED))
            (asserts! (not (is-eq recipient cryptocash-core)) (err ERR_INVALID_RECIPIENT)) ;; Ensure recipient is not cryptocash-core
            (asserts! (> amount u0) (err ERR_INVALID_AMOUNT)) ;; Ensure amount is greater than zero

            ;; Additional checks for recipient can go here if necessary

            (if check
                (ft-mint? CC amount recipient)
                (ok false)
            )
        )
    )
)


(define-public (burn (amount uint) (owner principal))
  (begin
    (asserts! (is-eq tx-sender owner) (err ERR_UNAUTHORIZED))
    (asserts! (> amount u0) (err ERR_INVALID_AMOUNT))
    (ft-burn? CC amount owner)
  )
)

;; checks if caller is Auth contract
(define-private (is-authorized-auth)
    (if (is-eq tx-sender CONTRACT_OWNER)
        (ok true)
        (err ERR_UNAUTHORIZED)
    )
) ;; Return an error if unauthorized


;; SEND-MANY

(define-public (send-many (recipients (list 200 { to: principal, amount: uint, memo: (optional (buff 34)) })))
  (fold check-err
    (map send-token recipients)
    (ok true)
  )
)

(define-private (check-err (result (response bool uint)) (prior (response bool uint)))
  (match prior ok-value result
               err-value (err err-value)
  )
)

(define-private (send-token (recipient { to: principal, amount: uint, memo: (optional (buff 34)) }))
  (send-token-with-memo (get amount recipient) (get to recipient) (get memo recipient))
)

(define-private (send-token-with-memo (amount uint) (to principal) (memo (optional (buff 34))))
  (let
    (
      (transferOk (try! (transfer amount tx-sender to memo)))
    )
    (ok transferOk)
  )
)
```
````


# .cryptocash-core

.cryptocash-core contract documentation

{% hint style="info" %}
Work in Progress
{% endhint %}

```
;; title: cryptocash-core
;; version: 1.3.1
;; summary: CryptoCash Core Contract
;; description: used to handle core CryptoCash logic

;; GENERAL CONFIGURATION
 
(impl-trait 'ST1ZK4MRVTQQJMVAAJQWBV2WPQ87QV2851YCTHD7X.cryptocash-core-trait.cryptocash-core)
(define-constant CONTRACT_OWNER tx-sender)

;; ERROR CODES

(define-constant ERR_UNAUTHORIZED u1000)
(define-constant ERR_USER_ALREADY_REGISTERED u1001)
(define-constant ERR_USER_NOT_FOUND u1002)
(define-constant ERR_USER_ID_NOT_FOUND u1003)
(define-constant ERR_ACTIVATION_THRESHOLD_REACHED u1004)
(define-constant ERR_CONTRACT_NOT_ACTIVATED u1005)
(define-constant ERR_USER_ALREADY_MINED u1006)
(define-constant ERR_INSUFFICIENT_COMMITMENT u1007)
(define-constant ERR_INSUFFICIENT_BALANCE u1008)
(define-constant ERR_USER_DID_NOT_MINE_IN_BLOCK u1009)
(define-constant ERR_CLAIMED_BEFORE_MATURITY u1010)
(define-constant ERR_NO_MINERS_AT_BLOCK u1011)
(define-constant ERR_DUPLICATE_CLAIM u1012)
(define-constant ERR_MINER_DID_NOT_WIN u1013)
(define-constant ERR_NO_VRF_SEED_FOUND u1014)
(define-constant ERR_STACKING_NOT_AVAILABLE u1015)
(define-constant ERR_CANNOT_STACK u1016)
(define-constant ERR_REWARD_CYCLE_NOT_COMPLETED u1017)
(define-constant ERR_NOTHING_TO_REDEEM u1018)
(define-constant ERR_UNABLE_TO_FIND_FOUNDATION_WALLET u1019)
(define-constant ERR_CLAIM_IN_WRONG_CONTRACT u1020)
(define-constant ERR_INVALID_WALLET u1021)
(define-constant ERR_INVALID_MEMO u1022)
(define-constant ERR_FUTURE_BLOCK u1023)
(define-constant ERR_INVALID_LOCK_PERIOD u1024)
(define-constant ERR_INVALID_AMOUNT u1025)
(define-constant ERR_INVALID_CYCLE u1026)
(define-constant ERR_VALIDATING_CLAIM_MINING_LIST u1027)
(define-constant ERR_VALIDATING_CLAIM_STACKING_LIST u1028)

;; FOUNDATION WALLET MANAGEMENT

;; initial value for foundation wallet, set to this
(define-data-var foundationWallet principal 'ST337NP61BD34ES77QK4XZP6R9AXV235GV52G1BDF)

;; returns set foundation wallet principal
(define-read-only (get-foundation-wallet)
  (var-get foundationWallet)
)

;; protected function to update foundation wallet variable
(define-public (set-foundation-wallet (newFoundationWallet principal))
    (if (is-eq tx-sender (get-foundation-wallet))
        (begin
            (asserts! (not (is-eq newFoundationWallet (get-foundation-wallet))) (err ERR_INVALID_WALLET)) ;; Ensure it's not the same as the current wallet
            (ok (var-set foundationWallet newFoundationWallet))
        )
        (ok false)
    )
)


;; REGISTRATION

(define-data-var activationBlock uint u340282366920938463463374607431768211455)
;; (define-data-var activationDelay uint u120)
(define-data-var activationReached bool false)

;; (define-data-var activationThreshold uint u20)
(define-data-var usersNonce uint u0)

;; returns block activation block height if activated
(define-read-only (get-activation-block)
  (let
    (
      (activated (var-get activationReached))
    )
    (asserts! activated (err ERR_CONTRACT_NOT_ACTIVATED))
    (ok (var-get activationBlock))
  )
)

;; returns activation status as boolean
(define-read-only (get-activation-status)
  (var-get activationReached)
)

;; returns number of registered users, used for activation and tracking user IDs
(define-read-only (get-registered-users-nonce)
  (var-get usersNonce)
)

;; store user principal by user id
(define-map Users
  uint
  principal
)

;; store user id by user principal
(define-map UserIds
  principal
  uint
)

;; returns (some userId) or none
(define-read-only (get-user-id (user principal))
  (map-get? UserIds user)
)

;; returns (some userPrincipal) or none
(define-read-only (get-user (userId uint))
  (map-get? Users userId)
)

;; returns user ID if it has been created, or creates and returns new ID
(define-private (get-or-create-user-id (user principal))
  (match
    (map-get? UserIds user)
    value value
    (let
      (
        (newId (+ u1 (var-get usersNonce)))
      )
      (map-set Users newId user)
      (map-set UserIds user newId)
      (var-set usersNonce newId)
      newId
    )
  )
)

;; MINING CONFIGURATION

;; define split to custodied wallet address for the foundation
(define-constant FOUNDATION_PCT u5)

;; how long a miner must wait before block winner can claim their minted tokens
(define-data-var tokenRewardMaturity uint u100)

;; At a given block height:
;; - how many miners were there
;; - what was the total amount submitted
;; - what was the total amount submitted to the Foundation
;; - what was the total amount submitted to Stackers
;; - was the block reward claimed
(define-map MiningStatsAtBlock
  uint
  {
    minersCount: uint,
    amount: uint,
    amountToFoundation: uint,
    amountToStackers: uint,
    rewardClaimed: bool
  }
)

;; returns map MiningStatsAtBlock at a given block height if it exists
(define-read-only (get-mining-stats-at-block (blockHeight uint))
  (map-get? MiningStatsAtBlock blockHeight)
)

;; returns map MiningStatsAtBlock at a given block height
;; or, an empty structure
(define-read-only (get-mining-stats-at-block-or-default (blockHeight uint))
  (default-to {
      minersCount: u0,
      amount: u0,
      amountToFoundation: u0,
      amountToStackers: u0,
      rewardClaimed: false
    }
    (map-get? MiningStatsAtBlock blockHeight)
  )
)

;; At a given block height and user ID:
;; - what is their ustx commitment
;; - what are the low/high values (used for VRF)
(define-map MinersAtBlock
  {
    blockHeight: uint,
    userId: uint
  }
  {
    ustx: uint,
    lowValue: uint,
    highValue: uint,
    winner: bool
  }
)

;; returns true if a given miner has already mined at a given block height
(define-read-only (has-mined-at-block (blockHeight uint) (userId uint))
  (is-some 
    (map-get? MinersAtBlock { blockHeight: blockHeight, userId: userId })
  )
)

;; returns map MinersAtBlock at a given block height for a user ID
(define-read-only (get-miner-at-block (blockHeight uint) (userId uint))
  (map-get? MinersAtBlock { blockHeight: blockHeight, userId: userId })
)

;; returns map MinersAtBlock at a given block height for a user ID
;; or, an empty structure
(define-read-only (get-miner-at-block-or-default (blockHeight uint) (userId uint))
  (default-to {
    highValue: u0,
    lowValue: u0,
    ustx: u0,
    winner: false
  }
    (map-get? MinersAtBlock { blockHeight: blockHeight, userId: userId }))
)

;; At a given block height:
;; - what is the max highValue from MinersAtBlock (used for VRF)
(define-map MinersAtBlockHighValue
  uint
  uint
)

;; returns last high value from map MinersAtBlockHighValue
(define-read-only (get-last-high-value-at-block (blockHeight uint))
  (default-to u0
    (map-get? MinersAtBlockHighValue blockHeight))
)

;; At a given block height:
;; - what is the userId of miner who won this block
(define-map BlockWinnerIds
  uint
  uint
)

(define-read-only (get-block-winner-id (blockHeight uint))
  (map-get? BlockWinnerIds blockHeight)
)

;; Return the current burn-block-height
(define-read-only (get-current-burn-block-height)
  (ok burn-block-height)
)

;; MINING ACTIONS
(define-public (mine (amounts (list 200 uint)))
  (begin
    (asserts! (get-activation-status) (err ERR_CONTRACT_NOT_ACTIVATED))
    (asserts! (> (fold + amounts u0) u0) (err ERR_INSUFFICIENT_COMMITMENT))
    (match (fold mine-block amounts (ok { userId: (get-or-create-user-id tx-sender), toStackers: u0, toFoundation: u0, blockHeight: burn-block-height }))
      okReturn 
      (begin
        (asserts! (>= (stx-get-balance tx-sender) (+ (get toStackers okReturn) (get toFoundation okReturn))) (err ERR_INSUFFICIENT_BALANCE))
        (if (> (get toStackers okReturn ) u0)
          (try! (stx-transfer? (get toStackers okReturn ) tx-sender (as-contract tx-sender)))
          false
        )
        (try! (stx-transfer? (get toFoundation okReturn) tx-sender (var-get foundationWallet)))

        ;; Event log
        (print 
          { 
            event: "mine", 
            who: tx-sender,
            userId: (get-or-create-user-id tx-sender),
            total: (fold + amounts u0),
            firstBlock: burn-block-height, 
            lastBlock: (- (+ burn-block-height (len amounts)) u1),
            totalBlocks: (len amounts)
          }
        )

        (ok true)
      )
      errReturn (err errReturn)
    )
  )
)

(define-private (mine-block 
  (amountUstx uint) 
  (return (response 
    { 
      userId: uint,
      toStackers: uint,
      toFoundation: uint,
      blockHeight: uint
    }
    uint
  )))
  
  (match return okReturn
    (let
      (
        (blockHeight (get blockHeight okReturn))
        (rewardCycle (default-to u0 (get-reward-cycle blockHeight)))
        (stackingActive (stacking-active-at-cycle rewardCycle))
        (toFoundation
          (if stackingActive
            (/ (* FOUNDATION_PCT amountUstx) u100)
            amountUstx
          )
        )
        (toStackers (- amountUstx toFoundation))
      )
      (asserts! (not (has-mined-at-block blockHeight (get userId okReturn))) (err ERR_USER_ALREADY_MINED))
      (asserts! (> amountUstx u0) (err ERR_INSUFFICIENT_COMMITMENT))
      (try! (set-tokens-mined (get userId okReturn) blockHeight amountUstx toStackers toFoundation))
      (ok (merge okReturn 
        {
          toStackers: (+ (get toStackers okReturn) toStackers),
          toFoundation: (+ (get toFoundation okReturn) toFoundation),
          blockHeight: (+ blockHeight u1)
        }
      ))
    )
    errReturn (err errReturn)
  ) 
)

(define-private (set-tokens-mined (userId uint) (blockHeight uint) (amountUstx uint) (toStackers uint) (toFoundation uint))
  (let
    (
      (blockStats (get-mining-stats-at-block-or-default blockHeight))
      (newMinersCount (+ (get minersCount blockStats) u1))
      (minerLowVal (get-last-high-value-at-block blockHeight))
      (rewardCycle (unwrap! (get-reward-cycle blockHeight)
        (err ERR_STACKING_NOT_AVAILABLE)))
      (rewardCycleStats (get-stacking-stats-at-cycle-or-default rewardCycle))
    )
    (map-set MiningStatsAtBlock
      blockHeight
      {
        minersCount: newMinersCount,
        amount: (+ (get amount blockStats) amountUstx),
        amountToFoundation: (+ (get amountToFoundation blockStats) toFoundation),
        amountToStackers: (+ (get amountToStackers blockStats) toStackers),
        rewardClaimed: false
      }
    )
    (map-set MinersAtBlock
      {
        blockHeight: blockHeight,
        userId: userId
      }
      {
        ustx: amountUstx,
        lowValue: (if (> minerLowVal u0) (+ minerLowVal u1) u0),
        highValue: (+ minerLowVal amountUstx),
        winner: false
      }
    )
    (map-set MinersAtBlockHighValue
      blockHeight
      (+ minerLowVal amountUstx)
    )
    (if (> toStackers u0)
      (map-set StackingStatsAtCycle
        rewardCycle
        {
          amountUstx: (+ (get amountUstx rewardCycleStats) toStackers),
          amountToken: (get amountToken rewardCycleStats)
        }
      )
      false
    )
    (ok true)
  )
)

;; MINING REWARD CLAIM ACTIONS

;; calls function to claim mining reward in active logic contract
(define-public (claim-mining-reward (minerBlockHeight uint))
    (begin
        (asserts! (<= minerBlockHeight burn-block-height) (err ERR_FUTURE_BLOCK)) ;; Ensure it's not in the future
        ;; Call claim-mining-reward-at-block after validation
        (try! (claim-mining-reward-at-block tx-sender burn-block-height minerBlockHeight))
        (ok true)
    )
)

;; Helper function for validation phase of claim-mining-reward-list
(define-private (validate-mining-claim-list (blockHeight uint) (acc (response bool uint)))
  (if (is-ok acc)
    ;; If accumulator is ok, proceed to validate the current block
    (if (can-claim-mining-reward tx-sender blockHeight)
      (ok true)
      (err ERR_VALIDATING_CLAIM_MINING_LIST)
    )
    ;; If accumulator is an error, propagate it
    acc
  )
)


;; Helper function for execution phase of claim-mining-reward-list
(define-private (execute-mining-claim-list (blockHeight uint) (acc (response bool uint)))
  (if (is-ok acc)
    ;; If accumulator is ok, proceed to process the current claim
    (let ((claim-result (claim-mining-reward blockHeight)))
      (if (is-ok claim-result)
        (ok true)
        claim-result  ;; Propagate the error from claim-mining-reward
      )
    )
    ;; If accumulator is an error, propagate it
    acc
  )
)

(define-public (claim-mining-reward-list (minerBlockHeights (list 200 uint)))
  (let
    (
      ;; First, validate all mining claims
      (validation (fold validate-mining-claim-list minerBlockHeights (ok true)))
    )
    (if (is-ok validation)
      ;; If all validations pass, execute all mining claims
      (let
        (
          ;; Process all mining claims, ensuring any error halts execution
          (results (fold execute-mining-claim-list minerBlockHeights (ok true)))
        )
        results
      )
      ;; If validation fails, return the error
      validation
    )
  )
)

;; Determine whether or not the given principal can claim the mined tokens at a particular block height,
;; given the miners record for that block height, a random sample, and the current block height.
(define-private (claim-mining-reward-at-block (user principal) (blockHeight uint) (minerBlockHeight uint))
  (let
    (
      (maturityHeight (+ (var-get tokenRewardMaturity) minerBlockHeight))
      (userId (unwrap! (get-user-id user) (err ERR_USER_ID_NOT_FOUND)))
      (blockStats (unwrap! (get-mining-stats-at-block minerBlockHeight) (err ERR_NO_MINERS_AT_BLOCK)))
      (minerStats (unwrap! (get-miner-at-block minerBlockHeight userId) (err ERR_USER_DID_NOT_MINE_IN_BLOCK)))
      (isMature (asserts! (> blockHeight maturityHeight) (err ERR_CLAIMED_BEFORE_MATURITY)))
      (vrfSample (unwrap! (contract-call? .cryptocash-vrf get-random-uint-at-block maturityHeight) (err ERR_NO_VRF_SEED_FOUND)))
      (commitTotal (get-last-high-value-at-block minerBlockHeight))
      (winningValue (mod vrfSample commitTotal))
    )
    (asserts! (not (get rewardClaimed blockStats)) (err ERR_DUPLICATE_CLAIM))
    (asserts! (and (>= winningValue (get lowValue minerStats)) (<= winningValue (get highValue minerStats)))
      (err ERR_MINER_DID_NOT_WIN))
    (try! (set-mining-reward-claimed userId minerBlockHeight))

    ;; Event log
    (print {
      event: "claim-mining-reward",
      who: tx-sender,
      userId: userId,
      claimHeight: minerBlockHeight
    })

    (ok true)
  )
)

(define-private (set-mining-reward-claimed (userId uint) (minerBlockHeight uint))
  (let
    (
      (blockStats (get-mining-stats-at-block-or-default minerBlockHeight))
      (minerStats (get-miner-at-block-or-default minerBlockHeight userId))
      (user (unwrap! (get-user userId) (err ERR_USER_NOT_FOUND)))
    )
    (map-set MiningStatsAtBlock
      minerBlockHeight
      {
        minersCount: (get minersCount blockStats),
        amount: (get amount blockStats),
        amountToFoundation: (get amountToFoundation blockStats),
        amountToStackers: (get amountToStackers blockStats),
        rewardClaimed: true
      }
    )
    (map-set MinersAtBlock
      {
        blockHeight: minerBlockHeight,
        userId: userId
      }
      {
        ustx: (get ustx minerStats),
        lowValue: (get lowValue minerStats),
        highValue: (get highValue minerStats),
        winner: true
      }
    )
    (map-set BlockWinnerIds
      minerBlockHeight
      userId
    )
    (try! (mint-coinbase user minerBlockHeight))
    (ok true)
  )
)

(define-read-only (is-block-winner (user principal) (minerBlockHeight uint))
  (is-block-winner-and-can-claim user minerBlockHeight false)
)

(define-read-only (can-claim-mining-reward (user principal) (minerBlockHeight uint))
  (is-block-winner-and-can-claim user minerBlockHeight true)
)

(define-private (is-block-winner-and-can-claim (user principal) (minerBlockHeight uint) (testCanClaim bool))
  (let
    (
      (userId (unwrap! (get-user-id user) false))
      (blockStats (unwrap! (get-mining-stats-at-block minerBlockHeight) false))
      (minerStats (unwrap! (get-miner-at-block minerBlockHeight userId) false))
      (maturityHeight (+ (var-get tokenRewardMaturity) minerBlockHeight))
      (vrfSample (unwrap! (contract-call? .cryptocash-vrf get-random-uint-at-block maturityHeight) false))
      (commitTotal (get-last-high-value-at-block minerBlockHeight))
      (winningValue (mod vrfSample commitTotal))
    )
    (if (and (>= winningValue (get lowValue minerStats)) (<= winningValue (get highValue minerStats)))
      (if testCanClaim (not (get rewardClaimed blockStats)) true)
      false
    )
  )
)

;; STACKING CONFIGURATION

(define-constant MAX_REWARD_CYCLES u32)
(define-constant REWARD_CYCLE_INDEXES (list u0 u1 u2 u3 u4 u5 u6 u7 u8 u9 u10 u11 u12 u13 u14 u15 u16 u17 u18 u19 u20 u21 u22 u23 u24 u25 u26 u27 u28 u29 u30 u31))

;; how long a reward cycle is
(define-data-var rewardCycleLength uint u2100)

;; At a given reward cycle:
;; - how many Stackers were there
;; - what is the total uSTX submitted by miners
;; - what is the total amount of tokens stacked
(define-map StackingStatsAtCycle
  uint
  {
    amountUstx: uint,
    amountToken: uint
  }
)

;; returns the total stacked tokens and committed uSTX for a given reward cycle
(define-read-only (get-stacking-stats-at-cycle (rewardCycle uint))
  (map-get? StackingStatsAtCycle rewardCycle)
)

;; returns the total stacked tokens and committed uSTX for a given reward cycle
;; or, an empty structure
(define-read-only (get-stacking-stats-at-cycle-or-default (rewardCycle uint))
  (default-to { amountUstx: u0, amountToken: u0 }
    (map-get? StackingStatsAtCycle rewardCycle))
)

;; At a given reward cycle and user ID:
;; - what is the total tokens Stacked?
;; - how many tokens should be returned? (based on Stacking period)
(define-map StackerAtCycle
  {
    rewardCycle: uint,
    userId: uint
  }
  {
    amountStacked: uint,
    toReturn: uint
  }
)

(define-read-only (get-stacker-at-cycle (rewardCycle uint) (userId uint))
  (map-get? StackerAtCycle { rewardCycle: rewardCycle, userId: userId })
)

(define-read-only (get-stacker-at-cycle-or-default (rewardCycle uint) (userId uint))
  (default-to { amountStacked: u0, toReturn: u0 }
    (map-get? StackerAtCycle { rewardCycle: rewardCycle, userId: userId }))
)

;; get the reward cycle for a given block height
(define-read-only (get-reward-cycle (blockHeight uint))
  (let
    (
      (firstStackingBlock (var-get activationBlock))
      (rcLen (var-get rewardCycleLength))
    )
    (if (>= blockHeight firstStackingBlock)
      (some (/ (- blockHeight firstStackingBlock) rcLen))
      none)
  )
)

;; determine if stacking is active in a given cycle
(define-read-only (stacking-active-at-cycle (rewardCycle uint))
  (is-some
    (get amountToken (map-get? StackingStatsAtCycle rewardCycle))
  )
)

;; get the first block height for a given reward cycle.
(define-read-only (get-first-block-in-reward-cycle (rewardCycle uint))
  (+ (var-get activationBlock) (* (var-get rewardCycleLength) rewardCycle))
)

;; getter for get-entitled-stacking-reward that specifies block height
(define-read-only (get-stacking-reward (userId uint) (targetCycle uint))
  (get-entitled-stacking-reward userId targetCycle burn-block-height)
)

;; get uSTX a Stacker can claim, given reward cycle they stacked in and current block height
;; this method only returns a positive value if:
;; - the current block height is in a subsequent reward cycle
;; - the stacker actually locked up tokens in the target reward cycle
;; - the stacker locked up _enough_ tokens to get at least one uSTX
;; it is possible to Stack tokens and not receive uSTX:
;; - if no miners commit during this reward cycle
;; - the amount stacked by user is too few that you'd be entitled to less than 1 uSTX
(define-private (get-entitled-stacking-reward (userId uint) (targetCycle uint) (blockHeight uint))
  (let
    (
      (rewardCycleStats (get-stacking-stats-at-cycle-or-default targetCycle))
      (stackerAtCycle (get-stacker-at-cycle-or-default targetCycle userId))
      (totalUstxThisCycle (get amountUstx rewardCycleStats))
      (totalStackedThisCycle (get amountToken rewardCycleStats))
      (userStackedThisCycle (get amountStacked stackerAtCycle))
    )
    (match (get-reward-cycle blockHeight)
      currentCycle
      (if (or (<= currentCycle targetCycle) (is-eq u0 userStackedThisCycle))
        ;; this cycle hasn't finished, or Stacker contributed nothing
        u0
        ;; (totalUstxThisCycle * userStackedThisCycle) / totalStackedThisCycle
        (/ (* totalUstxThisCycle userStackedThisCycle) totalStackedThisCycle)
      )
      ;; before first reward cycle
      u0
    )
  )
)

;; STACKING ACTIONS

(define-public (stack (amountTokens uint) (lockPeriod uint))
    (let
        (
            (userId (get-or-create-user-id tx-sender))
        )
        (begin
            ;; Ensure amountTokens is greater than zero
            (asserts! (> amountTokens u0) (err ERR_INVALID_AMOUNT))
            
            ;; Validate lockPeriod to ensure it's between 1 and 32 cycles
            (asserts! (>= lockPeriod u1) (err ERR_INVALID_LOCK_PERIOD))
            (asserts! (<= lockPeriod u32) (err ERR_INVALID_LOCK_PERIOD))
            
            ;; Call stack-tokens-at-cycle after validations
            (try! (stack-tokens-at-cycle tx-sender userId amountTokens burn-block-height lockPeriod))
            (ok true)
        )
    )
)

(define-private (stack-tokens-at-cycle (user principal) (userId uint) (amountTokens uint) (startHeight uint) (lockPeriod uint))
  (let
    (
      (currentCycle (unwrap! (get-reward-cycle startHeight) (err ERR_STACKING_NOT_AVAILABLE)))
      (targetCycle (+ u1 currentCycle))
      (commitment {
        stackerId: userId,
        amount: amountTokens,
        first: targetCycle,
        last: (+ targetCycle lockPeriod)
      })
    )
    (asserts! (get-activation-status) (err ERR_CONTRACT_NOT_ACTIVATED))
    (asserts! (and (> lockPeriod u0) (<= lockPeriod MAX_REWARD_CYCLES))
      (err ERR_CANNOT_STACK))
    (asserts! (> amountTokens u0) (err ERR_CANNOT_STACK))
    (try! (contract-call? .cryptocash-token transfer amountTokens tx-sender (as-contract tx-sender) none))

    ;; Event log
    (print {
      event:"stack",
      who: tx-sender,
      userId: userId,
      amountStacked: amountTokens,
      firstCycle: targetCycle, 
      lastCycle: (- (+ targetCycle lockPeriod) u1),
      lockPeriod: lockPeriod
    })

    (match (fold stack-tokens-closure REWARD_CYCLE_INDEXES (ok commitment))
      okValue (ok true)
      errValue (err errValue)
    )
  )
)

(define-private (stack-tokens-closure (rewardCycleIdx uint)
  (commitmentResponse (response 
    {
      stackerId: uint,
      amount: uint,
      first: uint,
      last: uint
    }
    uint
  )))

  (match commitmentResponse
    commitment 
    (let
      (
        (stackerId (get stackerId commitment))
        (amountToken (get amount commitment))
        (firstCycle (get first commitment))
        (lastCycle (get last commitment))
        (targetCycle (+ firstCycle rewardCycleIdx))
        (stackerAtCycle (get-stacker-at-cycle-or-default targetCycle stackerId))
        (amountStacked (get amountStacked stackerAtCycle))
        (toReturn (get toReturn stackerAtCycle))
      )
      (begin
        (if (and (>= targetCycle firstCycle) (< targetCycle lastCycle))
          (begin
            (if (is-eq targetCycle (- lastCycle u1))
              (set-tokens-stacked stackerId targetCycle amountToken amountToken)
              (set-tokens-stacked stackerId targetCycle amountToken u0)
            )
            true
          )
          false
        )
        commitmentResponse
      )
    )
    errValue commitmentResponse
  )
)

(define-private (set-tokens-stacked (userId uint) (targetCycle uint) (amountStacked uint) (toReturn uint))
  (let
    (
      (rewardCycleStats (get-stacking-stats-at-cycle-or-default targetCycle))
      (stackerAtCycle (get-stacker-at-cycle-or-default targetCycle userId))
    )
    (map-set StackingStatsAtCycle
      targetCycle
      {
        amountUstx: (get amountUstx rewardCycleStats),
        amountToken: (+ amountStacked (get amountToken rewardCycleStats))
      }
    )
    (map-set StackerAtCycle
      {
        rewardCycle: targetCycle,
        userId: userId
      }
      {
        amountStacked: (+ amountStacked (get amountStacked stackerAtCycle)),
        toReturn: (+ toReturn (get toReturn stackerAtCycle))
      }
    )
  )
)

;; STACKING REWARD CLAIMS

;; calls function to claim stacking reward in active logic contract
(define-public (claim-stacking-reward (targetCycle uint))
    (begin
        ;; Get the current reward cycle based on the current block height
        (let
            (
                (currentCycle (unwrap! (get-reward-cycle burn-block-height) (err ERR_INVALID_CYCLE)))
            )
            ;; Ensure that the target cycle is not in the future
            (asserts! (<= targetCycle currentCycle) (err ERR_INVALID_CYCLE))
            
            ;; Call claim-stacking-reward-at-cycle after validation
            (try! (claim-stacking-reward-at-cycle tx-sender burn-block-height targetCycle))
            (ok true)
        )
    )
)


;; Helper function for execution phase of claim-stacking-reward-list
(define-private (execute-stacking-claim-list (targetCycle uint) (acc (response bool uint)))
  (let 
    ((res  (claim-stacking-reward targetCycle)))
    (if (is-ok acc) 
      (asserts! (is-ok res) (err ERR_VALIDATING_CLAIM_STACKING_LIST))
      false
    )
    res
  )
)

(define-public (claim-stacking-reward-list (targetCycles (list 32 uint)))
  (begin 
      (asserts!          
          (is-ok 
            (fold execute-stacking-claim-list targetCycles (ok true))
          )       
      (err ERR_VALIDATING_CLAIM_STACKING_LIST))
    (ok true)
  )
)


(define-private (claim-stacking-reward-at-cycle (user principal) (blockHeight uint) (targetCycle uint))
  (let
    (
      (currentCycle (unwrap! (get-reward-cycle blockHeight) (err ERR_STACKING_NOT_AVAILABLE)))
      (userId (unwrap! (get-user-id user) (err ERR_USER_ID_NOT_FOUND)))
      (entitledUstx (get-entitled-stacking-reward userId targetCycle blockHeight))
      (stackerAtCycle (get-stacker-at-cycle-or-default targetCycle userId))
      (toReturn (get toReturn stackerAtCycle))
    )

    ;; Event log
    (print {
      event: "claim-stacking-reward", 
      who: user, 
      userId: userId,
      reward: entitledUstx, 
      amountStacked: toReturn,
      targetCycle: targetCycle
    })

    (asserts! (or
      ;; Compare current cycle and target cycle
      (> currentCycle targetCycle))
      (err ERR_REWARD_CYCLE_NOT_COMPLETED))
    (asserts! (or (> toReturn u0) (> entitledUstx u0)) (err ERR_NOTHING_TO_REDEEM))
    ;; disable ability to claim again
    (map-set StackerAtCycle
      {
        rewardCycle: targetCycle,
        userId: userId
      }
      {
        amountStacked: u0,
        toReturn: u0
      }
    )
    ;; send back tokens if user was eligible
    (if (> toReturn u0)
      (try! (as-contract (contract-call? .cryptocash-token transfer toReturn tx-sender user none)))
      true
    )
    ;; send back rewards if user was eligible
    (if (> entitledUstx u0)
      (try! (as-contract (stx-transfer? entitledUstx tx-sender user)))
      true
    )
    (ok true)
  )
)

;; Check to see if the given user principal can claim a stacking reward for the given targetCycle
(define-read-only (can-claim-stacking-reward (user principal) (targetCycle uint))
  (let
    (
      (currentCycleOpt (get-reward-cycle burn-block-height))
      (userIdOpt (get-user-id user))
    )
    (if (and (is-some currentCycleOpt) (is-some userIdOpt))
      (let
        (
          (currentCycle (unwrap! currentCycleOpt false))
          (userId (unwrap! userIdOpt false))
        )
        (if (> currentCycle targetCycle)
          (let
            (
              (entitledUstx (get-entitled-stacking-reward userId targetCycle burn-block-height))
              (stackerAtCycle (get-stacker-at-cycle-or-default targetCycle userId))
              (toReturn (get toReturn stackerAtCycle))
            )
            (or (> toReturn u0) (> entitledUstx u0))
          )
          false
        )
        false
      )
      false
    )
  )
)

;; TOKEN CONFIGURATION

;; store block height at each halving, set during activate-cryptocash
(define-data-var coinbaseThreshold1 uint u0)
(define-data-var coinbaseThreshold2 uint u0)
(define-data-var coinbaseThreshold3 uint u0)
(define-data-var coinbaseThreshold4 uint u0)
(define-data-var coinbaseThreshold5 uint u0)

(define-private (set-coinbase-thresholds)
  (let
    (
      (coinbaseAmounts (try! (contract-call? .cryptocash-token get-coinbase-thresholds)))
    )
      (var-set coinbaseThreshold1 (get coinbaseThreshold1 coinbaseAmounts))
      (var-set coinbaseThreshold2 (get coinbaseThreshold2 coinbaseAmounts))
      (var-set coinbaseThreshold3 (get coinbaseThreshold3 coinbaseAmounts))
      (var-set coinbaseThreshold4 (get coinbaseThreshold4 coinbaseAmounts))
      (var-set coinbaseThreshold5 (get coinbaseThreshold5 coinbaseAmounts))
      (ok true)
  )
)

;; return coinbase thresholds if contract activated
(define-read-only (get-coinbase-thresholds)
  (let
    (
      (activated (var-get activationReached))
    )
    (asserts! activated (err ERR_CONTRACT_NOT_ACTIVATED))
    (ok {
      coinbaseThreshold1: (var-get coinbaseThreshold1),
      coinbaseThreshold2: (var-get coinbaseThreshold2),
      coinbaseThreshold3: (var-get coinbaseThreshold3),
      coinbaseThreshold4: (var-get coinbaseThreshold4),
      coinbaseThreshold5: (var-get coinbaseThreshold5)
    })
  )
)

;; function for deciding how many tokens to mint, depending on when they were mined
(define-read-only (get-coinbase-amount (minerBlockHeight uint))
  (begin
    ;; if contract is not active, return 0
    (asserts! (>= minerBlockHeight (var-get activationBlock)) u0)
    ;; if contract is active, return based on issuance schedule
    ;; halvings occur every 210,000 blocks for 1,050,000 blocks
    ;; then mining continues indefinitely with 100 tokens as the reward
    (asserts! (> minerBlockHeight (var-get coinbaseThreshold1)) u3200)
    (asserts! (> minerBlockHeight (var-get coinbaseThreshold2)) u1600)
    (asserts! (> minerBlockHeight (var-get coinbaseThreshold3)) u800)
    (asserts! (> minerBlockHeight (var-get coinbaseThreshold4)) u400)
    (asserts! (> minerBlockHeight (var-get coinbaseThreshold5)) u200)
    ;; default value after 5th halving
    u100
  )
)

;; mint new tokens for claimant who won at given block height
(define-private (mint-coinbase (recipient principal) (blockHeight uint))
  (begin 
    (print {recipient:recipient, blockHeight:blockHeight, coinbaseAmount:(get-coinbase-amount blockHeight)})
    (as-contract (contract-call? .cryptocash-token mint (get-coinbase-amount blockHeight) recipient))
  )
)

;; check if contract caller is foundation wallet
(define-private (is-authorized-founder)
  (is-eq contract-caller (var-get foundationWallet))
)

;; check if contract caller is contract owner
(define-private (is-authorized-owner)
  (is-eq contract-caller CONTRACT_OWNER)
)

(define-public (activate-cryptocash)
  (let
    (
      (activationBlockVal (+ burn-block-height u100))
    )
      (asserts! (is-eq tx-sender CONTRACT_OWNER) (err ERR_UNAUTHORIZED))
      (try! (contract-call? .cryptocash-token activate-token activationBlockVal))
      (try! (set-coinbase-thresholds))
      (var-set activationReached true)
      (var-set activationBlock activationBlockVal)
      (ok true)
  )
)
```


# Testnet Contracts


# Testnet Addresses (old)

Deployed by ST1ZK0A249B4SWAHVXD70R13P6B5HNKZAA0WNTJTR

**View CryptoCash Nakamoto Testnet Contracts on Explorer:**

* [.cryptocash-vrf](https://explorer.hiro.so/txid/0xeb7f32c17644df0f1b3ad73266c7963e41105e695ee6807d05738b295381467e?chain=testnet\&api=https://api.nakamoto.testnet.hiro.so)
* [.cryptocash-token-trait](https://explorer.hiro.so/txid/0x5dbcaf81883cb17869c62d58f14262fd9f4147cfc2995017a59da758f21b7d25?chain=testnet\&api=https://api.nakamoto.testnet.hiro.so)
* [.cryptocash-core-trait](https://explorer.hiro.so/txid/0x6f15c4d696af7347e6030d608b158ee738cd1b1faa77863025cdc01f693e1d12?chain=testnet\&api=https://api.nakamoto.testnet.hiro.so)
* [.cryptocash-token](https://explorer.hiro.so/txid/0xb6aba9fb6066bccc85c6ee92cffb4629d54aacd63fb6002cb1d0d6494a5f8d35?chain=testnet\&api=https://api.nakamoto.testnet.hiro.so)
* [.cryptocash-core](https://explorer.hiro.so/txid/0xb914416a4fad2912bac26dc6bbbd21b9142f0bf73260b3144ccef6d1e7968eee?chain=testnet\&api=https://api.nakamoto.testnet.hiro.so)


# Testnet Addresses (old2)

Deployed by: ST32BYC2A9RGZ6ENVG4G6QZBDPDGW8V9QWN81H5XC

**View CryptoCash Nakamoto Testnet Contracts on Explorer:**

* [.sip-010-trait-ft-standard](https://explorer.hiro.so/txid/0x2ee049901df8b51b3edbf160ee9b9844d728e7029a1021d4888af3fb1c332180?chain=testnet\&api=https://api.nakamoto.testnet.hiro.so)
* [.cryptocash-vrf](https://explorer.hiro.so/txid/0x00b7ee116a7972021d044643adbfdd435e5cdb3eaf6dd41906564e056c5c1316?chain=testnet\&api=https://api.nakamoto.testnet.hiro.so)
* [.cryptocash-token-trait](https://explorer.hiro.so/txid/0xac2477294d021cb1b2284748a081fb5cf82b1d86d7b82d6f9269b7210b192ac5?chain=testnet\&api=https://api.nakamoto.testnet.hiro.so)
* [.cryptocash-core-trait](https://explorer.hiro.so/txid/0x8dba7c2bf606d5fa5c17e0a2149c36ab0e62894f922465cf60f435a9db885413?chain=testnet\&api=https://api.nakamoto.testnet.hiro.so)
* [.cryptocash-token](https://explorer.hiro.so/txid/0xe40e4ed620c5c9a44c6887fb8b9458ba93dbf8a5bf64247c304f9e44055623da?chain=testnet\&api=https://api.nakamoto.testnet.hiro.so)
* [.cryptocash-core](https://explorer.hiro.so/txid/0xff21932ca0289c23ce02bbdd50fbc54209dd6fde24ca157f7cb6f804f3668268?chain=testnet\&api=https://api.nakamoto.testnet.hiro.so)


# Testnet Addresses (broken)

Deployed by ST3HNWNVVCP31S8CVQCD8WDVFXZJGKFP8VVGKVENW

**View CryptoCash Nakamoto Testnet Contracts on Explorer:**

* [.cryptocash-vrf](https://explorer.hiro.so/txid/0x3cc33452b4c827a2c94159109f5091b19d88345f8c4e5dc4581fb5b18abeef1b?chain=testnet\&api=https://api.nakamoto.testnet.hiro.so)
* [.cryptocash-token-trait](https://explorer.hiro.so/txid/0x288bb5dc02531fa2a7c3f4e0048ece0d99c76c817cd4bb726011698b1c8659ab?chain=testnet\&api=https://api.nakamoto.testnet.hiro.so)
* [.cryptocash-core-trait](https://explorer.hiro.so/txid/0x46768890551a0ed37fc75ff16f084d80ca5a2c6bfa0d8edc52550ac69f1e3c31?chain=testnet\&api=https://api.nakamoto.testnet.hiro.so)
* [.cryptocash-token](https://explorer.hiro.so/txid/0x49e4280ecf55f74daa782c4f5a6a0dbeb03c8648a2e038a783ccc639e84eaa5d?chain=testnet\&api=https://api.nakamoto.testnet.hiro.so)
* [.cryptocash-core](https://explorer.hiro.so/txid/0x515a6fe5933563be38486a60a60eecc9cb8b4ae3c237c9f2e5bf837215b50a66?chain=testnet\&api=https://api.nakamoto.testnet.hiro.so)


