Token management program (vesting and mining) implemented in Anchor

Overview

Deep Dive into Anchor by Implementing Token Management Program

Author: @ironaddicteddog, @emersonliuuu

[Updated at 2022.5.21]

You can find the full code base here

What is Anchor?

There is a comprehensive explanation on the official website. Let me just quote relative paragraphs here:

Anchor is a framework for Solana's Sealevel runtime providing several convenient developer tools.

If you're familiar with developing in Ethereum's Solidity, Truffle, web3.js, then the experience will be familiar. Although the DSL syntax and semantics are targeted at Solana, the high level flow of writing RPC request handlers, emitting an IDL, and generating clients from IDL is the same.

In short, Anchor gives you the following handy tools for developing Solana programs:

  • Rust crates and eDSL for writing Solana programs
  • IDL specification
  • TypeScript package for generating clients from IDL
  • CLI and workspace management for developing complete applications

You can watch this awesome talk given by Armani Ferrante at Breakpoint 2021 to feel the power of Anchor.

Workflow

  1. Develop the program (Smart Contract)
  2. Build the program and export the IDL
  3. Generate the client representation of program from the IDL to interact with the program

Why Anchor?

  • Anchor is the new standard
  • Productivity
    • Make Solana program more intuitive to understand
    • More clear buisness Logic
    • Remove a ton of biolderplate code
  • Security
    • Use discriminator
      • Discriminator is generated and inserted into the first 8 bytes of account data. Ex: sha256("account:<MyAccountName>")[..8] || borsh(account_struct)
      • Used for more secure account validation and function dispatch
      • See this Twitter thread for more details
      • See here and here for the actual implementation
    • Implement most of the best practices of secure program

Where can I learn more about Anchor?

Overview of Token Management

Note: These programs are originated from Serum's stake program developed by Armani Ferrante. There are a few things evolved from the original version:

  • Upgrade Anchor to latest version (Currently 0.24.2)
  • Optimize some function invocation to avoid stack frame limit
  • Rename struct and module to make them better reveal its designed purpose

In short, token management consist of two modules:

  • Locker Manager, which manages the vesting of locked tokens
  • Pool Manager, which manages the mining of rewarded tokens

Vesting and Mining

  • Token vesting and mining are two fundenmental components of DeFi tokenomics
  • There are existed solutions.
    • Bonfida vesting
    • Quarry
    • ...
  • anchor-token-management intergates vesting and mining modules and has the following features:
    • Written in Anchor
    • Modular and customizable condition of releasing rewards
    • Control funds even if its locked in locker. For example: desposit to pool from locker. (Not covered in this tutorial)

Architecture

Interfaces

Locker
Pool (Rewarder)
Pool (Staker)

Implementing Token Management Program in Anchor

Prerequisites

  • Basic layouts of Anchor programs
    • program
    • context
    • state
    • error
    • ...
  • Anchor Constraints
    • [account(mut)]
    • [account(init)]
    • ...
  • Token Program
    • Token Account
    • Mint
    • Transfer
    • Burn
  • anchor-escrow

To Be Covered

  • PDA account creation and derivation
  • Access control
  • CPI usage
  • Custimized Error

Step 1: Scaffolding

  • Checkout to step-1 branch to see the full code
  • In this step, we scaffold the programs by following the interfaces explained above:
    • Implement LockerManager
    • Implement PoolManager
    • Implement PoolRewardKeeper

Part 2: Implementing

  • Checkout to step-2 branch to see the full code
  • In this step, we implement all the functions, context and states without concerning the security issues:
    • Add all contexts and states
    • Add utils
      • calculator
      • RewardQueue
    • Add constraints
      • PDA creation and derivation
      • has_one
      • Raw constraints
      • ...

Tips: you can use git diff to see what changes have been made:

$ git checkout step-2
$ git diff step-1

Part 3: Improving Security

  • Checkout to step-3 branch to see the full code
  • In this step, we improve the security:
    • Implement access control and security check
    • Customize error

Tips: you can use git diff to see what changes have been made:

$ git checkout step-3
$ git diff step-2

More Advanced Topics

Control funds even if its locked in locker. For example: desposit to pool from locker. See the full code base for details.

  • withdraw_to_whitelist
  • deposit_from_locker
  • withdraw_to_locker

Referneces

You might also like...
Simple (not simplest) UST vault that integrate with Anchor Protocol

Simple (not simplest) UST Vault Building a simple UST Vault that generate yield from Anchor while also have UST reserved for lending, and etc. This co

Anchor Design of contract - Accounts, Parameters

MarketplaceDesign Anchor Design of contract - Accounts, Parameters Main Instructions are Initialize ListForSale AcceptOffer CancelList MakeOffer Cance

Write Anchor-compatible Solana programs in TypeScript

Axolotl Write Achor-compatible Solana programs using TypeScript. Writing Rust is hard, but safe. It's also the go-to language for writing Solana progr

NFT & Marketplace Contracts with royalties and fungible token support. Sample React app included.
NFT & Marketplace Contracts with royalties and fungible token support. Sample React app included.

NFT Market Reference Implementation A PoC backbone for NFT Marketplaces on NEAR Protocol. Reference Changelog Changelog Progress: basic purchase of NF

Dfinity's fungible token standard. Any PRs and comments are welcome,collaborate with us to build this standard

Dfinity's fungible token standard. Any PRs and comments are welcome,collaborate with us to build this standard

All the data an IC app needs to make seamless experiences, accessible directly on the IC. DAB is an open internet service for NFT, Token, Canister, and Dapp registries.
All the data an IC app needs to make seamless experiences, accessible directly on the IC. DAB is an open internet service for NFT, Token, Canister, and Dapp registries.

DAB 👀 Overview An Internet Computer open internet service for data. All the data an IC app needs to make a seamless experience, accessible directly o

ARYA Network is a polkadot/substrate based chain for Non-fungible Token platform on which we can own sell and buy the NFT's on polkadot network.

ARYA Network ARYA Network is a polkadot/substrate based chain for Non-fungible Token platform on which we can own sell and buy the NFT's on polkadot n

An all-in-one IBC protocol providing fungible token transfer, interchain account, and async query functionalities

ICS-999 An all-in-one IBC protocol providing fungible token transfer, interchain account (ICA), and query (ICQ) functionalities, implemented in CosmWa

Dank - The Internet Computer Decentralized Bank - A collection of Open Internet Services - Including the Cycles Token (XTC)
Dank - The Internet Computer Decentralized Bank - A collection of Open Internet Services - Including the Cycles Token (XTC)

Dank - The Internet Computer Decentralized Bank Dank is a collection of Open Internet Services for users and developers on the Internet Computer. In t

Yi Token by Crate Protocol: the primitive for auto-compounding single token staking pools.

yi Yi Token by Crate Protocol: the primitive for auto-compounding single token staking pools. About Yi is a Solana primitive for building single-sided

Crate Protocol 12 Apr 7, 2022
Uniswap V2 / constant-product AMM implemented in Solana's Anchor -- add and remove liquidity, swap tokens, earn fees

Uniswap V2 AMM implemented in Anchor programs/ammv2/src/draft.rs: outline of program with comments -- drafted before implementation Supported Instruct

Something-Something 8 Aug 10, 2024
Marinde Anchor-Based, first on mainnet, liquid-staking-program and mSOL->SOL swap pool

marinade-anchor Marinade-finance liquid staking program for the Solana blockchain Audits & Code Review Kudelski Security: https://marinade.finance/Kud

Marinade.Finance 42 Dec 11, 2022
Transparency for Mining Pool Transaction Selection

miningpool-observer Transparency for Mining Pool Transaction Selection The miningpool-observer project compares block templates produced by a Bitcoin

0xB10C 36 Nov 25, 2022
⛏ An open protocol for launching liquidity mining programs on Solana.

⛏ Quarry An open protocol for launching liquidity mining programs on Solana. Background Quarry was built with the intention of helping more Solana pro

Quarry Protocol 207 Dec 19, 2022
Making Token Exchange program with Solana(Rust), Web3, and Vue

Escrow program for Solana blockchain Tech stack Program (Smart Contract) Rust crates: solana-program, spl-token Solana CLI for test validator UI Types

Hoon Wee 3 May 10, 2022
The Voting example based on MoonZoon and Solana + Anchor framework.

The Voting example based on MoonZoon and Solana + Anchor framework.

Martin Kavík 6 Aug 13, 2022
Battery-included Solana/Anchor project skeleton.

Anchor Skeleton Battery-included Solana/Anchor project skeleton. Features Rust test only: All tests (integration, unit) are written in Rust, so the co

Weiyuan Wu 5 Feb 23, 2022
Solana NFT marketplace boilerplate with anchor & react & candy-machine-cli

The Heros NFT Marketplace Boilerplate project is designed to let users fork, customize, and deploy their own nft marketplace app to a custom domain, ultra fast.

null 30 Dec 15, 2022
Solana NFT marketplace boilerplate with anchor & react & candy-machine-cli

Solana_Marketplace_HerosNFT The Heros NFT Marketplace Boilerplate project is designed to let users fork, customize, and deploy their own nft marketpla

null 30 Dec 15, 2022