This commit is contained in:
Hardhat Chad
2024-06-29 00:59:55 +00:00
parent edc1439712
commit 462a7021e1
29 changed files with 245 additions and 194 deletions

25
core/api/Cargo.toml Normal file
View File

@@ -0,0 +1,25 @@
[package]
name = "ore-api"
description = "API for interacting with the ORE program"
version.workspace = true
edition.workspace = true
license.workspace = true
homepage.workspace = true
documentation.workspace = true
repository.workspace = true
keywords.workspace = true
[dependencies]
array-const-fn-init = "0.1.1"
bs58 = "0.5.0"
bytemuck = "1.14.3"
const-crypto = "0.1.0"
drillx.workspace = true
mpl-token-metadata.workspace = true
num_enum = "0.7.2"
shank = "0.3.0"
solana-program.workspace = true
spl-token.workspace = true
spl-associated-token-account.workspace = true
static_assertions = "1.1.0"
thiserror = "1.0.57"

133
core/api/src/consts.rs Normal file
View File

@@ -0,0 +1,133 @@
use array_const_fn_init::array_const_fn_init;
use const_crypto::ed25519;
use solana_program::{pubkey, pubkey::Pubkey};
/// The reward rate to intialize the program with.
pub const INITIAL_BASE_REWARD_RATE: u64 = 10u64.pow(3u32);
/// The admin allowed to initialize the program.
pub const INITIAL_ADMIN: Pubkey = pubkey!("HBUh9g46wk2X89CvaNN15UmsznP59rh6od1h8JwYAopk");
/// The spam/liveness tolerance in seconds.
pub const TOLERANCE: i64 = 5;
/// The minimum difficulty required of all submitted hashes.
pub const MIN_DIFFICULTY: u32 = 8;
/// The decimal precision of the ORE token.
/// There are 100 billion indivisible units per ORE (called "grains").
pub const TOKEN_DECIMALS: u8 = 11;
/// The decimal precision of the ORE v1 token.
pub const TOKEN_DECIMALS_V1: u8 = 9;
/// One ORE token, denominated in indivisible units.
pub const ONE_ORE: u64 = 10u64.pow(TOKEN_DECIMALS as u32);
/// The duration of one minute, in seconds.
pub const ONE_MINUTE: i64 = 60;
/// The number of minutes in a program epoch.
pub const EPOCH_MINUTES: i64 = 1;
/// The duration of a program epoch, in seconds.
pub const EPOCH_DURATION: i64 = ONE_MINUTE.saturating_mul(EPOCH_MINUTES);
/// The maximum token supply (21 million).
pub const MAX_SUPPLY: u64 = ONE_ORE.saturating_mul(21_000_000);
/// The target quantity of ORE to be mined per epoch.
pub const TARGET_EPOCH_REWARDS: u64 = ONE_ORE.saturating_mul(EPOCH_MINUTES as u64);
/// The maximum quantity of ORE that can be mined per epoch.
/// Inflation rate ≈ 1 ORE / min (min 0, max 8)
pub const MAX_EPOCH_REWARDS: u64 = TARGET_EPOCH_REWARDS.saturating_mul(BUS_COUNT as u64);
/// The quantity of ORE each bus is allowed to issue per epoch.
pub const BUS_EPOCH_REWARDS: u64 = MAX_EPOCH_REWARDS.saturating_div(BUS_COUNT as u64);
/// The number of bus accounts, for parallelizing mine operations.
pub const BUS_COUNT: usize = 8;
/// The smoothing factor for reward rate changes. The reward rate cannot change by more or less
/// than a factor of this constant from one epoch to the next.
pub const SMOOTHING_FACTOR: u64 = 2;
// Assert MAX_EPOCH_REWARDS is evenly divisible by BUS_COUNT.
static_assertions::const_assert!(
(MAX_EPOCH_REWARDS / BUS_COUNT as u64) * BUS_COUNT as u64 == MAX_EPOCH_REWARDS
);
/// The seed of the bus account PDA.
pub const BUS: &[u8] = b"bus";
/// The seed of the config account PDA.
pub const CONFIG: &[u8] = b"config";
/// The seed of the metadata account PDA.
pub const METADATA: &[u8] = b"metadata";
/// The seed of the mint account PDA.
pub const MINT: &[u8] = b"mint";
/// The seed of proof account PDAs.
pub const PROOF: &[u8] = b"proof";
/// The seed of the treasury account PDA.
pub const TREASURY: &[u8] = b"treasury";
/// Noise for deriving the mint pda
pub const MINT_NOISE: [u8; 16] = [
166, 199, 85, 221, 225, 119, 21, 185, 160, 82, 242, 237, 194, 84, 250, 252,
];
/// The name for token metadata.
pub const METADATA_NAME: &str = "ORE";
/// The ticker symbol for token metadata.
pub const METADATA_SYMBOL: &str = "ORE";
/// The uri for token metdata.
pub const METADATA_URI: &str = "https://ore.supply/metadata.json";
/// Program id for const pda derivations
const PROGRAM_ID: [u8; 32] = unsafe { *(&crate::id() as *const Pubkey as *const [u8; 32]) };
/// The addresses of the bus accounts.
pub const BUS_ADDRESSES: [Pubkey; BUS_COUNT] = array_const_fn_init![const_bus_address; 8];
/// Function to derive const bus addresses.
const fn const_bus_address(i: usize) -> Pubkey {
Pubkey::new_from_array(ed25519::derive_program_address(&[BUS, &[i as u8]], &PROGRAM_ID).0)
}
/// The address of the config account.
pub const CONFIG_ADDRESS: Pubkey =
Pubkey::new_from_array(ed25519::derive_program_address(&[CONFIG], &PROGRAM_ID).0);
/// The address of the mint metadata account.
pub const METADATA_ADDRESS: Pubkey = Pubkey::new_from_array(
ed25519::derive_program_address(
&[
METADATA,
unsafe { &*(&mpl_token_metadata::ID as *const Pubkey as *const [u8; 32]) },
unsafe { &*(&MINT_ADDRESS as *const Pubkey as *const [u8; 32]) },
],
unsafe { &*(&mpl_token_metadata::ID as *const Pubkey as *const [u8; 32]) },
)
.0,
);
/// The address of the mint account.
pub const MINT_ADDRESS: Pubkey =
Pubkey::new_from_array(ed25519::derive_program_address(&[MINT, &MINT_NOISE], &PROGRAM_ID).0);
/// The address of the v1 mint account.
pub const MINT_V1_ADDRESS: Pubkey = pubkey!("oreoN2tQbHXVaZsr3pf66A48miqcBXCDJozganhEJgz");
/// The address of the treasury account.
pub const TREASURY_ADDRESS: Pubkey =
Pubkey::new_from_array(ed25519::derive_program_address(&[TREASURY], &PROGRAM_ID).0);
/// The bump of the treasury account, for cpis.
pub const TREASURY_BUMP: u8 = ed25519::derive_program_address(&[TREASURY], &PROGRAM_ID).1;

32
core/api/src/error.rs Normal file
View File

@@ -0,0 +1,32 @@
use num_enum::IntoPrimitive;
use solana_program::program_error::ProgramError;
use thiserror::Error;
#[derive(Debug, Error, Clone, Copy, PartialEq, Eq, IntoPrimitive)]
#[repr(u32)]
pub enum OreError {
#[error("The epoch has ended and needs reset")]
NeedsReset = 0,
#[error("The provided hash is invalid")]
HashInvalid = 1,
#[error("The provided hash did not satisfy the minimum required difficulty")]
HashTooEasy = 2,
#[error("The claim amount cannot be greater than the claimable rewards")]
ClaimTooLarge = 3,
#[error("The clock time is invalid")]
ClockInvalid = 4,
#[error("You are trying to submit too soon")]
Spam = 5,
#[error("Only one hash may be validated per transaction")]
TransactionInvalid = 6,
#[error("The tolerance cannot exceed i64 max value")]
ToleranceOverflow = 7,
#[error("The maximum supply has been reached")]
MaxSupply = 8,
}
impl From<OreError> for ProgramError {
fn from(e: OreError) -> Self {
ProgramError::Custom(e as u32)
}
}

439
core/api/src/instruction.rs Normal file
View File

@@ -0,0 +1,439 @@
use bytemuck::{Pod, Zeroable};
use drillx::Solution;
use num_enum::TryFromPrimitive;
use shank::ShankInstruction;
use solana_program::{
instruction::{AccountMeta, Instruction},
pubkey::Pubkey,
system_program, sysvar,
};
use crate::{consts::*, impl_instruction_from_bytes, impl_to_bytes};
#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, ShankInstruction, TryFromPrimitive)]
#[rustfmt::skip]
pub enum OreInstruction {
#[account(0, name = "ore_program", desc = "Ore program")]
#[account(1, name = "signer", desc = "Signer", signer)]
#[account(2, name = "beneficiary", desc = "Beneficiary token account", writable)]
#[account(3, name = "proof", desc = "Ore proof account", writable)]
#[account(4, name = "treasury", desc = "Ore treasury account", writable)]
#[account(5, name = "treasury_tokens", desc = "Ore treasury token account", writable)]
#[account(6, name = "token_program", desc = "SPL token program")]
Claim = 0,
#[account(0, name = "ore_program", desc = "Ore program")]
#[account(1, name = "signer", desc = "Signer", signer)]
#[account(2, name = "proof", desc = "Ore proof account", writable)]
#[account(3, name = "system_program", desc = "Solana system program")]
Close = 1,
#[account(0, name = "ore_program", desc = "Ore program")]
#[account(1, name = "signer", desc = "Signer", signer)]
#[account(2, name = "config", desc = "Ore config account", writable)]
#[account(3, name = "proof", desc = "Ore proof account current top staker")]
#[account(4, name = "proof_new", desc = "Ore proof account new top staker")]
Crown = 2,
#[account(0, name = "ore_program", desc = "Ore program")]
#[account(1, name = "signer", desc = "Signer", signer)]
#[account(2, name = "bus", desc = "Ore bus account", writable)]
#[account(3, name = "config", desc = "Ore config account")]
#[account(4, name = "noise", desc = "Ore noise account")]
#[account(5, name = "proof", desc = "Ore proof account", writable)]
#[account(6, name = "slot_hashes", desc = "Solana slot hashes sysvar")]
Mine = 3,
#[account(0, name = "ore_program", desc = "Ore program")]
#[account(1, name = "signer", desc = "Signer", signer)]
#[account(2, name = "proof", desc = "Ore proof account", writable)]
#[account(3, name = "system_program", desc = "Solana system program")]
Open = 4,
#[account(0, name = "ore_program", desc = "Ore program")]
#[account(1, name = "signer", desc = "Signer", signer)]
#[account(2, name = "bus_0", desc = "Ore bus account 0", writable)]
#[account(3, name = "bus_1", desc = "Ore bus account 1", writable)]
#[account(4, name = "bus_2", desc = "Ore bus account 2", writable)]
#[account(5, name = "bus_3", desc = "Ore bus account 3", writable)]
#[account(6, name = "bus_4", desc = "Ore bus account 4", writable)]
#[account(7, name = "bus_5", desc = "Ore bus account 5", writable)]
#[account(8, name = "bus_6", desc = "Ore bus account 6", writable)]
#[account(9, name = "bus_7", desc = "Ore bus account 7", writable)]
#[account(10, name = "config", desc = "Ore config account")]
#[account(11, name = "mint", desc = "Ore token mint account", writable)]
#[account(12, name = "treasury", desc = "Ore treasury account", writable)]
#[account(13, name = "treasury_tokens", desc = "Ore treasury token account", writable)]
#[account(14, name = "token_program", desc = "SPL token program")]
Reset = 5,
#[account(0, name = "ore_program", desc = "Ore program")]
#[account(1, name = "signer", desc = "Signer", signer)]
#[account(2, name = "proof", desc = "Ore proof account", writable)]
#[account(3, name = "sender", desc = "Signer token account", writable)]
#[account(4, name = "treasury_tokens", desc = "Ore treasury token account", writable)]
#[account(5, name = "token_program", desc = "SPL token program")]
Stake = 6,
#[account(0, name = "ore_program", desc = "Ore program")]
#[account(1, name = "signer", desc = "Signer", signer)]
#[account(2, name = "proof", desc = "Ore proof account", writable)]
Update = 7,
#[account(0, name = "ore_program", desc = "Ore program")]
#[account(1, name = "signer", desc = "Signer", signer)]
#[account(2, name = "beneficiary", desc = "Beneficiary token account", writable)]
#[account(3, name = "sender", desc = "Signer token account", writable)]
#[account(4, name = "treasury", desc = "Ore treasury account", writable)]
#[account(5, name = "mint", desc = "Ore token mint account", writable)]
#[account(6, name = "mint_v1", desc = "Ore v1 token mint account", writable)]
#[account(7, name = "token_program", desc = "SPL token program")]
Upgrade = 8,
#[account(0, name = "ore_program", desc = "Ore program")]
#[account(1, name = "signer", desc = "Admin signer", signer)]
#[account(2, name = "bus_0", desc = "Ore bus account 0", writable)]
#[account(3, name = "bus_1", desc = "Ore bus account 1", writable)]
#[account(4, name = "bus_2", desc = "Ore bus account 2", writable)]
#[account(5, name = "bus_3", desc = "Ore bus account 3", writable)]
#[account(6, name = "bus_4", desc = "Ore bus account 4", writable)]
#[account(7, name = "bus_5", desc = "Ore bus account 5", writable)]
#[account(8, name = "bus_6", desc = "Ore bus account 6", writable)]
#[account(9, name = "bus_7", desc = "Ore bus account 7", writable)]
#[account(10, name = "metadata", desc = "Ore mint metadata account", writable)]
#[account(11, name = "mint", desc = "Ore mint account", writable)]
#[account(12, name = "noise", desc = "Ore noise account", writable)]
#[account(13, name = "treasury", desc = "Ore treasury account", writable)]
#[account(14, name = "treasury_tokens", desc = "Ore treasury token account", writable)]
#[account(15, name = "system_program", desc = "Solana system program")]
#[account(16, name = "token_program", desc = "SPL token program")]
#[account(17, name = "associated_token_program", desc = "SPL associated token program")]
#[account(18, name = "mpl_metadata_program", desc = "Metaplex metadata program")]
#[account(19, name = "rent", desc = "Solana rent sysvar")]
Initialize = 100,
}
impl OreInstruction {
pub fn to_vec(&self) -> Vec<u8> {
vec![*self as u8]
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct InitializeArgs {
pub bus_0_bump: u8,
pub bus_1_bump: u8,
pub bus_2_bump: u8,
pub bus_3_bump: u8,
pub bus_4_bump: u8,
pub bus_5_bump: u8,
pub bus_6_bump: u8,
pub bus_7_bump: u8,
pub config_bump: u8,
pub metadata_bump: u8,
pub mint_bump: u8,
pub treasury_bump: u8,
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct OpenArgs {
pub bump: u8,
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct MineArgs {
pub digest: [u8; 16],
pub nonce: [u8; 8],
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct ClaimArgs {
pub amount: [u8; 8],
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct StakeArgs {
pub amount: [u8; 8],
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct UpgradeArgs {
pub amount: [u8; 8],
}
impl_to_bytes!(InitializeArgs);
impl_to_bytes!(OpenArgs);
impl_to_bytes!(MineArgs);
impl_to_bytes!(ClaimArgs);
impl_to_bytes!(StakeArgs);
impl_to_bytes!(UpgradeArgs);
impl_instruction_from_bytes!(InitializeArgs);
impl_instruction_from_bytes!(OpenArgs);
impl_instruction_from_bytes!(MineArgs);
impl_instruction_from_bytes!(ClaimArgs);
impl_instruction_from_bytes!(StakeArgs);
impl_instruction_from_bytes!(UpgradeArgs);
/// Builds a claim instruction.
pub fn claim(signer: Pubkey, beneficiary: Pubkey, amount: u64) -> Instruction {
let proof = Pubkey::find_program_address(&[PROOF, signer.as_ref()], &crate::id()).0;
let treasury_tokens = spl_associated_token_account::get_associated_token_address(
&TREASURY_ADDRESS,
&MINT_ADDRESS,
);
Instruction {
program_id: crate::id(),
accounts: vec![
AccountMeta::new(signer, true),
AccountMeta::new(beneficiary, false),
AccountMeta::new(MINT_ADDRESS, false),
AccountMeta::new(proof, false),
AccountMeta::new_readonly(TREASURY_ADDRESS, false),
AccountMeta::new(treasury_tokens, false),
AccountMeta::new_readonly(spl_token::id(), false),
],
data: [
OreInstruction::Claim.to_vec(),
ClaimArgs {
amount: amount.to_le_bytes(),
}
.to_bytes()
.to_vec(),
]
.concat(),
}
}
/// Builds a close instruction.
pub fn close(signer: Pubkey) -> Instruction {
let proof_pda = Pubkey::find_program_address(&[PROOF, signer.as_ref()], &crate::id());
Instruction {
program_id: crate::id(),
accounts: vec![
AccountMeta::new(signer, true),
AccountMeta::new(proof_pda.0, false),
AccountMeta::new_readonly(solana_program::system_program::id(), false),
],
data: OreInstruction::Close.to_vec(),
}
}
/// Builds a mine instruction.
pub fn mine(signer: Pubkey, bus: Pubkey, solution: Solution) -> Instruction {
let proof = Pubkey::find_program_address(&[PROOF, signer.as_ref()], &crate::id()).0;
Instruction {
program_id: crate::id(),
accounts: vec![
AccountMeta::new(signer, true),
AccountMeta::new(bus, false),
AccountMeta::new_readonly(CONFIG_ADDRESS, false),
AccountMeta::new(proof, false),
AccountMeta::new_readonly(sysvar::instructions::id(), false),
AccountMeta::new_readonly(sysvar::slot_hashes::id(), false),
],
data: [
OreInstruction::Mine.to_vec(),
MineArgs {
digest: solution.d,
nonce: solution.n,
}
.to_bytes()
.to_vec(),
]
.concat(),
}
}
/// Builds an open instruction.
pub fn open(signer: Pubkey, miner: Pubkey) -> Instruction {
let proof_pda = Pubkey::find_program_address(&[PROOF, signer.as_ref()], &crate::id());
Instruction {
program_id: crate::id(),
accounts: vec![
AccountMeta::new(signer, true),
AccountMeta::new_readonly(miner, false),
AccountMeta::new(proof_pda.0, false),
AccountMeta::new_readonly(solana_program::system_program::id(), false),
AccountMeta::new_readonly(sysvar::slot_hashes::id(), false),
],
data: [
OreInstruction::Open.to_vec(),
OpenArgs { bump: proof_pda.1 }.to_bytes().to_vec(),
]
.concat(),
}
}
/// Builds a reset instruction.
pub fn reset(signer: Pubkey) -> Instruction {
let treasury_tokens = spl_associated_token_account::get_associated_token_address(
&TREASURY_ADDRESS,
&MINT_ADDRESS,
);
Instruction {
program_id: crate::id(),
accounts: vec![
AccountMeta::new(signer, true),
AccountMeta::new(BUS_ADDRESSES[0], false),
AccountMeta::new(BUS_ADDRESSES[1], false),
AccountMeta::new(BUS_ADDRESSES[2], false),
AccountMeta::new(BUS_ADDRESSES[3], false),
AccountMeta::new(BUS_ADDRESSES[4], false),
AccountMeta::new(BUS_ADDRESSES[5], false),
AccountMeta::new(BUS_ADDRESSES[6], false),
AccountMeta::new(BUS_ADDRESSES[7], false),
AccountMeta::new(CONFIG_ADDRESS, false),
AccountMeta::new(MINT_ADDRESS, false),
AccountMeta::new(TREASURY_ADDRESS, false),
AccountMeta::new(treasury_tokens, false),
AccountMeta::new_readonly(spl_token::id(), false),
],
data: OreInstruction::Reset.to_vec(),
}
}
/// Build a stake instruction.
pub fn stake(signer: Pubkey, sender: Pubkey, amount: u64) -> Instruction {
let proof = Pubkey::find_program_address(&[PROOF, signer.as_ref()], &crate::id()).0;
let treasury_tokens = spl_associated_token_account::get_associated_token_address(
&TREASURY_ADDRESS,
&MINT_ADDRESS,
);
Instruction {
program_id: crate::id(),
accounts: vec![
AccountMeta::new(signer, true),
AccountMeta::new(proof, false),
AccountMeta::new(sender, false),
AccountMeta::new(treasury_tokens, false),
AccountMeta::new_readonly(spl_token::id(), false),
],
data: [
OreInstruction::Stake.to_vec(),
StakeArgs {
amount: amount.to_le_bytes(),
}
.to_bytes()
.to_vec(),
]
.concat(),
}
}
// Build an update instruction.
pub fn update(signer: Pubkey, miner: Pubkey) -> Instruction {
let proof = Pubkey::find_program_address(&[PROOF, signer.as_ref()], &crate::id()).0;
Instruction {
program_id: crate::id(),
accounts: vec![
AccountMeta::new(signer, true),
AccountMeta::new_readonly(miner, false),
AccountMeta::new(proof, false),
],
data: OreInstruction::Update.to_vec(),
}
}
// Build an upgrade instruction.
pub fn upgrade(signer: Pubkey, beneficiary: Pubkey, sender: Pubkey, amount: u64) -> Instruction {
Instruction {
program_id: crate::id(),
accounts: vec![
AccountMeta::new(signer, true),
AccountMeta::new(beneficiary, false),
AccountMeta::new(MINT_ADDRESS, false),
AccountMeta::new(MINT_V1_ADDRESS, false),
AccountMeta::new(sender, false),
AccountMeta::new(TREASURY_ADDRESS, false),
AccountMeta::new_readonly(spl_token::id(), false),
],
data: [
OreInstruction::Upgrade.to_vec(),
UpgradeArgs {
amount: amount.to_le_bytes(),
}
.to_bytes()
.to_vec(),
]
.concat(),
}
}
/// Builds an initialize instruction.
pub fn initialize(signer: Pubkey) -> Instruction {
let bus_pdas = [
Pubkey::find_program_address(&[BUS, &[0]], &crate::id()),
Pubkey::find_program_address(&[BUS, &[1]], &crate::id()),
Pubkey::find_program_address(&[BUS, &[2]], &crate::id()),
Pubkey::find_program_address(&[BUS, &[3]], &crate::id()),
Pubkey::find_program_address(&[BUS, &[4]], &crate::id()),
Pubkey::find_program_address(&[BUS, &[5]], &crate::id()),
Pubkey::find_program_address(&[BUS, &[6]], &crate::id()),
Pubkey::find_program_address(&[BUS, &[7]], &crate::id()),
];
let config_pda = Pubkey::find_program_address(&[CONFIG], &crate::id());
let mint_pda = Pubkey::find_program_address(&[MINT, MINT_NOISE.as_slice()], &crate::id());
let treasury_pda = Pubkey::find_program_address(&[TREASURY], &crate::id());
let treasury_tokens =
spl_associated_token_account::get_associated_token_address(&treasury_pda.0, &mint_pda.0);
let metadata_pda = Pubkey::find_program_address(
&[
METADATA,
mpl_token_metadata::ID.as_ref(),
mint_pda.0.as_ref(),
],
&mpl_token_metadata::ID,
);
Instruction {
program_id: crate::id(),
accounts: vec![
AccountMeta::new(signer, true),
AccountMeta::new(bus_pdas[0].0, false),
AccountMeta::new(bus_pdas[1].0, false),
AccountMeta::new(bus_pdas[2].0, false),
AccountMeta::new(bus_pdas[3].0, false),
AccountMeta::new(bus_pdas[4].0, false),
AccountMeta::new(bus_pdas[5].0, false),
AccountMeta::new(bus_pdas[6].0, false),
AccountMeta::new(bus_pdas[7].0, false),
AccountMeta::new(config_pda.0, false),
AccountMeta::new(metadata_pda.0, false),
AccountMeta::new(mint_pda.0, false),
AccountMeta::new(treasury_pda.0, false),
AccountMeta::new(treasury_tokens, false),
AccountMeta::new_readonly(system_program::id(), false),
AccountMeta::new_readonly(spl_token::id(), false),
AccountMeta::new_readonly(spl_associated_token_account::id(), false),
AccountMeta::new_readonly(mpl_token_metadata::ID, false),
AccountMeta::new_readonly(sysvar::rent::id(), false),
],
data: [
OreInstruction::Initialize.to_vec(),
InitializeArgs {
bus_0_bump: bus_pdas[0].1,
bus_1_bump: bus_pdas[1].1,
bus_2_bump: bus_pdas[2].1,
bus_3_bump: bus_pdas[3].1,
bus_4_bump: bus_pdas[4].1,
bus_5_bump: bus_pdas[5].1,
bus_6_bump: bus_pdas[6].1,
bus_7_bump: bus_pdas[7].1,
config_bump: config_pda.1,
metadata_bump: metadata_pda.1,
mint_bump: mint_pda.1,
treasury_bump: treasury_pda.1,
}
.to_bytes()
.to_vec(),
]
.concat(),
}
}

9
core/api/src/lib.rs Normal file
View File

@@ -0,0 +1,9 @@
pub mod consts;
pub mod error;
pub mod instruction;
pub mod state;
pub mod utils;
use solana_program::declare_id;
declare_id!("mineRHF5r6S7HyD9SppBfVMXMavDkJsxwGesEvxZr2A");

32
core/api/src/state/bus.rs Normal file
View File

@@ -0,0 +1,32 @@
use bytemuck::{Pod, Zeroable};
use shank::ShankAccount;
use crate::{
impl_account_from_bytes, impl_to_bytes,
utils::{AccountDiscriminator, Discriminator},
};
/// Bus accounts are responsible for distributing mining rewards.
/// There are 8 busses total to minimize write-lock contention and allow for parallel mine operations.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, ShankAccount, Zeroable)]
pub struct Bus {
/// The ID of the bus account.
pub id: u64,
/// The remaining rewards this bus has left to payout in the current epoch.
pub rewards: u64,
/// The rewards this bus would have paid out in the current epoch if there no limit.
/// Used to calculate the updated reward rate.
pub theoretical_rewards: u64,
}
impl Discriminator for Bus {
fn discriminator() -> AccountDiscriminator {
AccountDiscriminator::Bus
}
}
impl_to_bytes!(Bus);
impl_account_from_bytes!(Bus);

View File

@@ -0,0 +1,37 @@
use bytemuck::{Pod, Zeroable};
use shank::ShankAccount;
use solana_program::pubkey::Pubkey;
use crate::{
impl_account_from_bytes, impl_to_bytes,
utils::{AccountDiscriminator, Discriminator},
};
/// Config is a singleton account which manages admin configurable variables.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, ShankAccount, Zeroable)]
pub struct Config {
/// The admin authority with permission to update the difficulty.
pub admin: Pubkey,
/// The base reward rate paid out for a hash of minimum difficulty.
pub base_reward_rate: u64,
/// The timestamp of the last reset.
pub last_reset_at: i64,
/// The largest known stake balance on the network.
pub max_stake: u64,
/// The address of the proof account with the highest stake balance.
pub top_staker: Pubkey,
}
impl Discriminator for Config {
fn discriminator() -> AccountDiscriminator {
AccountDiscriminator::Config
}
}
impl_to_bytes!(Config);
impl_account_from_bytes!(Config);

View File

@@ -0,0 +1,9 @@
mod bus;
mod config;
mod proof;
mod treasury;
pub use bus::*;
pub use config::*;
pub use proof::*;
pub use treasury::*;

View File

@@ -0,0 +1,50 @@
use bytemuck::{Pod, Zeroable};
use shank::ShankAccount;
use solana_program::pubkey::Pubkey;
use crate::{
impl_account_from_bytes, impl_to_bytes,
utils::{AccountDiscriminator, Discriminator},
};
/// Proof accounts track a miner's current hash, claimable rewards, and lifetime stats.
/// Every miner is allowed one proof account which is required by the program to mine or claim rewards.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, ShankAccount, Zeroable)]
pub struct Proof {
/// The signer authorized to use this proof.
pub authority: Pubkey,
/// The quantity of tokens this miner has staked or earned.
pub balance: u64,
/// The current mining challenge.
pub challenge: [u8; 32],
/// The last hash the miner provided.
pub last_hash: [u8; 32],
/// The last time this account provided a hash.
pub last_hash_at: i64,
/// The last time stake was deposited into this account.
pub last_stake_at: i64,
/// The keypair which has permission to submit hashes for mining.
pub miner: Pubkey,
/// The total lifetime hashes provided by this miner.
pub total_hashes: u64,
/// The total lifetime rewards distributed to this miner.
pub total_rewards: u64,
}
impl Discriminator for Proof {
fn discriminator() -> AccountDiscriminator {
AccountDiscriminator::Proof
}
}
impl_to_bytes!(Proof);
impl_account_from_bytes!(Proof);

View File

@@ -0,0 +1,22 @@
use bytemuck::{Pod, Zeroable};
use shank::ShankAccount;
use crate::{
impl_account_from_bytes, impl_to_bytes,
utils::{AccountDiscriminator, Discriminator},
};
/// Treasury is a singleton account which manages all program wide variables.
/// It is the mint authority for the Ore token and also the authority of the program-owned token account.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, ShankAccount, Zeroable)]
pub struct Treasury {}
impl Discriminator for Treasury {
fn discriminator() -> AccountDiscriminator {
AccountDiscriminator::Treasury
}
}
impl_to_bytes!(Treasury);
impl_account_from_bytes!(Treasury);

156
core/api/src/utils.rs Normal file
View File

@@ -0,0 +1,156 @@
use bytemuck::{Pod, Zeroable};
use num_enum::{IntoPrimitive, TryFromPrimitive};
use solana_program::{
account_info::AccountInfo, entrypoint::ProgramResult, program_error::ProgramError,
pubkey::Pubkey, rent::Rent, sysvar::Sysvar,
};
/// Creates a new pda
#[inline(always)]
pub fn create_pda<'a, 'info>(
target_account: &'a AccountInfo<'info>,
owner: &Pubkey,
space: usize,
pda_seeds: &[&[u8]],
system_program: &'a AccountInfo<'info>,
payer: &'a AccountInfo<'info>,
) -> ProgramResult {
let rent = Rent::get()?;
if target_account.lamports().eq(&0) {
// If balance is zero, create account
solana_program::program::invoke_signed(
&solana_program::system_instruction::create_account(
payer.key,
target_account.key,
rent.minimum_balance(space),
space as u64,
owner,
),
&[
payer.clone(),
target_account.clone(),
system_program.clone(),
],
&[pda_seeds],
)?;
} else {
// Otherwise, if balance is nonzero:
// 1) transfer sufficient lamports for rent exemption
let rent_exempt_balance = rent
.minimum_balance(space)
.saturating_sub(target_account.lamports());
if rent_exempt_balance.gt(&0) {
solana_program::program::invoke(
&solana_program::system_instruction::transfer(
payer.key,
target_account.key,
rent_exempt_balance,
),
&[
payer.clone(),
target_account.clone(),
system_program.clone(),
],
)?;
}
// 2) allocate space for the account
solana_program::program::invoke_signed(
&solana_program::system_instruction::allocate(target_account.key, space as u64),
&[target_account.clone(), system_program.clone()],
&[pda_seeds],
)?;
// 3) assign our program as the owner
solana_program::program::invoke_signed(
&solana_program::system_instruction::assign(target_account.key, owner),
&[target_account.clone(), system_program.clone()],
&[pda_seeds],
)?;
}
Ok(())
}
#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)]
pub enum AccountDiscriminator {
Bus = 100,
Config = 101,
Proof = 102,
Treasury = 103,
}
pub trait Discriminator {
fn discriminator() -> AccountDiscriminator;
}
pub trait AccountDeserialize {
fn try_from_bytes(data: &[u8]) -> Result<&Self, ProgramError>;
fn try_from_bytes_mut(data: &mut [u8]) -> Result<&mut Self, ProgramError>;
}
#[macro_export]
macro_rules! impl_to_bytes {
($struct_name:ident) => {
impl $struct_name {
pub fn to_bytes(&self) -> &[u8] {
bytemuck::bytes_of(self)
}
}
};
}
#[macro_export]
macro_rules! impl_account_from_bytes {
($struct_name:ident) => {
impl crate::utils::AccountDeserialize for $struct_name {
fn try_from_bytes(
data: &[u8],
) -> Result<&Self, solana_program::program_error::ProgramError> {
if (Self::discriminator() as u8).ne(&data[0]) {
return Err(solana_program::program_error::ProgramError::InvalidAccountData);
}
bytemuck::try_from_bytes::<Self>(&data[8..]).or(Err(
solana_program::program_error::ProgramError::InvalidAccountData,
))
}
fn try_from_bytes_mut(
data: &mut [u8],
) -> Result<&mut Self, solana_program::program_error::ProgramError> {
if (Self::discriminator() as u8).ne(&data[0]) {
return Err(solana_program::program_error::ProgramError::InvalidAccountData);
}
bytemuck::try_from_bytes_mut::<Self>(&mut data[8..]).or(Err(
solana_program::program_error::ProgramError::InvalidAccountData,
))
}
}
};
}
#[macro_export]
macro_rules! impl_instruction_from_bytes {
($struct_name:ident) => {
impl $struct_name {
pub fn try_from_bytes(
data: &[u8],
) -> Result<&Self, solana_program::program_error::ProgramError> {
bytemuck::try_from_bytes::<Self>(data).or(Err(
solana_program::program_error::ProgramError::InvalidInstructionData,
))
}
}
};
}
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, Zeroable)]
pub struct MineEvent {
pub difficulty: u64,
pub reward: u64,
pub timing: i64,
}
impl_to_bytes!(MineEvent);

34
core/program/Cargo.toml Normal file
View File

@@ -0,0 +1,34 @@
[package]
name = "ore-program"
description = "ORE is a fair-launch, proof-of-work, digital currency everyone can mine"
version.workspace = true
edition.workspace = true
license.workspace = true
homepage.workspace = true
documentation.workspace = true
repository.workspace = true
readme.workspace = true
keywords.workspace = true
[lib]
crate-type = ["cdylib", "lib"]
name = "ore"
[features]
no-entrypoint = []
default = []
[dependencies]
drillx.workspace = true
mpl-token-metadata.workspace = true
ore-api = { path = "../api" }
solana-program.workspace = true
spl-token.workspace = true
spl-associated-token-account.workspace = true
[dev-dependencies]
bs64 = "0.1.2"
rand = "0.8.5"
solana-program-test = "^1.18"
solana-sdk = "^1.18"
tokio = { version = "1.35", features = ["full"] }

41
core/program/src/lib.rs Normal file
View File

@@ -0,0 +1,41 @@
mod loaders;
mod processor;
use ore_api::instruction::*;
use processor::*;
use solana_program::{
self, account_info::AccountInfo, entrypoint::ProgramResult, program_error::ProgramError,
pubkey::Pubkey,
};
#[cfg(not(feature = "no-entrypoint"))]
solana_program::entrypoint!(process_instruction);
pub fn process_instruction(
program_id: &Pubkey,
accounts: &[AccountInfo],
data: &[u8],
) -> ProgramResult {
if program_id.ne(&ore_api::id()) {
return Err(ProgramError::IncorrectProgramId);
}
let (tag, data) = data
.split_first()
.ok_or(ProgramError::InvalidInstructionData)?;
match OreInstruction::try_from(*tag).or(Err(ProgramError::InvalidInstructionData))? {
OreInstruction::Claim => process_claim(program_id, accounts, data)?,
OreInstruction::Close => process_close(program_id, accounts, data)?,
OreInstruction::Crown => process_crown(program_id, accounts, data)?,
OreInstruction::Mine => process_mine(program_id, accounts, data)?,
OreInstruction::Open => process_open(program_id, accounts, data)?,
OreInstruction::Reset => process_reset(program_id, accounts, data)?,
OreInstruction::Stake => process_stake(program_id, accounts, data)?,
OreInstruction::Update => process_update(program_id, accounts, data)?,
OreInstruction::Upgrade => process_upgrade(program_id, accounts, data)?,
OreInstruction::Initialize => process_initialize(program_id, accounts, data)?,
}
Ok(())
}

424
core/program/src/loaders.rs Normal file
View File

@@ -0,0 +1,424 @@
use ore_api::{
consts::*,
state::{Bus, Config, Proof, Treasury},
utils::{AccountDeserialize, Discriminator},
};
use solana_program::{
account_info::AccountInfo, program_error::ProgramError, program_pack::Pack, pubkey::Pubkey,
system_program, sysvar,
};
use spl_token::state::Mint;
/// Errors if:
/// - Account is not a signer.
pub fn load_signer<'a, 'info>(info: &'a AccountInfo<'info>) -> Result<(), ProgramError> {
if !info.is_signer {
return Err(ProgramError::MissingRequiredSignature);
}
Ok(())
}
/// Errors if:
/// - Owner is not Ore program.
/// - Address does not match the expected bus address.
/// - Data is empty.
/// - Data cannot deserialize into a bus account.
/// - Bus ID does not match the expected ID.
/// - Expected to be writable, but is not.
pub fn load_bus<'a, 'info>(
info: &'a AccountInfo<'info>,
id: u64,
is_writable: bool,
) -> Result<(), ProgramError> {
if info.owner.ne(&ore_api::id()) {
return Err(ProgramError::InvalidAccountOwner);
}
if info.key.ne(&BUS_ADDRESSES[id as usize]) {
return Err(ProgramError::InvalidSeeds);
}
if info.data_is_empty() {
return Err(ProgramError::UninitializedAccount);
}
let bus_data = info.data.borrow();
let bus = Bus::try_from_bytes(&bus_data)?;
if bus.id.ne(&id) {
return Err(ProgramError::InvalidAccountData);
}
if is_writable && !info.is_writable {
return Err(ProgramError::InvalidAccountData);
}
Ok(())
}
/// Errors if:
/// - Owner is not Ore program.
/// - Data is empty.
/// - Data cannot deserialize into a bus account.
/// - Bus ID is not in the expected range.
/// - Address is not in set of valid bus address.
/// - Expected to be writable, but is not.
pub fn load_any_bus<'a, 'info>(
info: &'a AccountInfo<'info>,
is_writable: bool,
) -> Result<(), ProgramError> {
if info.owner.ne(&ore_api::id()) {
return Err(ProgramError::InvalidAccountOwner);
}
if info.data_is_empty() {
return Err(ProgramError::UninitializedAccount);
}
if info.data.borrow()[0].ne(&(Bus::discriminator() as u8)) {
return Err(solana_program::program_error::ProgramError::InvalidAccountData);
}
if !BUS_ADDRESSES.contains(info.key) {
return Err(ProgramError::InvalidSeeds);
}
if is_writable && !info.is_writable {
return Err(ProgramError::InvalidAccountData);
}
Ok(())
}
/// Errors if:
/// - Owner is not Ore program.
/// - Address does not match the expected address.
/// - Data is empty.
/// - Data cannot deserialize into a config account.
/// - Expected to be writable, but is not.
pub fn load_config<'a, 'info>(
info: &'a AccountInfo<'info>,
is_writable: bool,
) -> Result<(), ProgramError> {
if info.owner.ne(&ore_api::id()) {
return Err(ProgramError::InvalidAccountOwner);
}
if info.key.ne(&CONFIG_ADDRESS) {
return Err(ProgramError::InvalidSeeds);
}
if info.data_is_empty() {
return Err(ProgramError::UninitializedAccount);
}
if info.data.borrow()[0].ne(&(Config::discriminator() as u8)) {
return Err(solana_program::program_error::ProgramError::InvalidAccountData);
}
if is_writable && !info.is_writable {
return Err(ProgramError::InvalidAccountData);
}
Ok(())
}
/// Errors if:
/// - Owner is not Ore program.
/// - Data is empty.
/// - Data cannot deserialize into a proof account.
/// - Proof authority does not match the expected address.
/// - Expected to be writable, but is not.
pub fn load_proof<'a, 'info>(
info: &'a AccountInfo<'info>,
authority: &Pubkey,
is_writable: bool,
) -> Result<(), ProgramError> {
if info.owner.ne(&ore_api::id()) {
return Err(ProgramError::InvalidAccountOwner);
}
if info.data_is_empty() {
return Err(ProgramError::UninitializedAccount);
}
let proof_data = info.data.borrow();
let proof = Proof::try_from_bytes(&proof_data)?;
if proof.authority.ne(&authority) {
return Err(ProgramError::InvalidAccountData);
}
if is_writable && !info.is_writable {
return Err(ProgramError::InvalidAccountData);
}
Ok(())
}
/// Errors if:
/// - Owner is not Ore program.
/// - Data is empty.
/// - Data cannot deserialize into a proof account.
/// - Proof miner does not match the expected address.
/// - Expected to be writable, but is not.
pub fn load_proof_with_miner<'a, 'info>(
info: &'a AccountInfo<'info>,
miner: &Pubkey,
is_writable: bool,
) -> Result<(), ProgramError> {
if info.owner.ne(&ore_api::id()) {
return Err(ProgramError::InvalidAccountOwner);
}
if info.data_is_empty() {
return Err(ProgramError::UninitializedAccount);
}
let proof_data = info.data.borrow();
let proof = Proof::try_from_bytes(&proof_data)?;
if proof.miner.ne(&miner) {
return Err(ProgramError::InvalidAccountData);
}
if is_writable && !info.is_writable {
return Err(ProgramError::InvalidAccountData);
}
Ok(())
}
/// Errors if:
/// - Owner is not Ore program.
/// - Data is empty.
/// - Data cannot deserialize into a proof account.
/// - Expected to be writable, but is not.
pub fn load_any_proof<'a, 'info>(
info: &'a AccountInfo<'info>,
is_writable: bool,
) -> Result<(), ProgramError> {
if info.owner.ne(&ore_api::id()) {
return Err(ProgramError::InvalidAccountOwner);
}
if info.data_is_empty() {
return Err(ProgramError::UninitializedAccount);
}
if info.data.borrow()[0].ne(&(Proof::discriminator() as u8)) {
return Err(solana_program::program_error::ProgramError::InvalidAccountData);
}
if is_writable && !info.is_writable {
return Err(ProgramError::InvalidAccountData);
}
Ok(())
}
/// Errors if:
/// - Owner is not Ore program.
/// - Address does not match the expected address.
/// - Data is empty.
/// - Data cannot deserialize into a treasury account.
/// - Expected to be writable, but is not.
pub fn load_treasury<'a, 'info>(
info: &'a AccountInfo<'info>,
is_writable: bool,
) -> Result<(), ProgramError> {
if info.owner.ne(&ore_api::id()) {
return Err(ProgramError::InvalidAccountOwner);
}
if info.key.ne(&TREASURY_ADDRESS) {
return Err(ProgramError::InvalidSeeds);
}
if info.data_is_empty() {
return Err(ProgramError::UninitializedAccount);
}
if info.data.borrow()[0].ne(&(Treasury::discriminator() as u8)) {
return Err(solana_program::program_error::ProgramError::InvalidAccountData);
}
if is_writable && !info.is_writable {
return Err(ProgramError::InvalidAccountData);
}
Ok(())
}
/// Errors if:
/// - Owner is not SPL token program.
/// - Address does not match the expected mint address.
/// - Data is empty.
/// - Data cannot deserialize into a mint account.
/// - Expected to be writable, but is not.
pub fn load_mint<'a, 'info>(
info: &'a AccountInfo<'info>,
address: Pubkey,
is_writable: bool,
) -> Result<(), ProgramError> {
if info.owner.ne(&spl_token::id()) {
return Err(ProgramError::InvalidAccountOwner);
}
if info.key.ne(&address) {
return Err(ProgramError::InvalidSeeds);
}
if info.data_is_empty() {
return Err(ProgramError::UninitializedAccount);
}
if Mint::unpack_unchecked(&info.data.borrow()).is_err() {
return Err(ProgramError::InvalidAccountData);
}
if is_writable && !info.is_writable {
return Err(ProgramError::InvalidAccountData);
}
Ok(())
}
/// Errors if:
/// - Owner is not SPL token program.
/// - Data is empty.
/// - Data cannot deserialize into a token account.
/// - Token account owner does not match the expected owner address.
/// - Token account mint does not match the expected mint address.
/// - Expected to be writable, but is not.
pub fn load_token_account<'a, 'info>(
info: &'a AccountInfo<'info>,
owner: Option<&Pubkey>,
mint: &Pubkey,
is_writable: bool,
) -> Result<(), ProgramError> {
if info.owner.ne(&spl_token::id()) {
return Err(ProgramError::InvalidAccountOwner);
}
if info.data_is_empty() {
return Err(ProgramError::UninitializedAccount);
}
let account_data = info.data.borrow();
let account = spl_token::state::Account::unpack_unchecked(&account_data)
.or(Err(ProgramError::InvalidAccountData))?;
if account.mint.ne(&mint) {
return Err(ProgramError::InvalidAccountData);
}
if let Some(owner) = owner {
if account.owner.ne(owner) {
return Err(ProgramError::InvalidAccountData);
}
}
if is_writable && !info.is_writable {
return Err(ProgramError::InvalidAccountData);
}
Ok(())
}
/// Errors if:
/// - Address does not match PDA derived from provided seeds.
/// - Cannot load as an uninitialized account.
pub fn load_uninitialized_pda<'a, 'info>(
info: &'a AccountInfo<'info>,
seeds: &[&[u8]],
bump: u8,
program_id: &Pubkey,
) -> Result<(), ProgramError> {
let pda = Pubkey::find_program_address(seeds, program_id);
if info.key.ne(&pda.0) {
return Err(ProgramError::InvalidSeeds);
}
if bump.ne(&pda.1) {
return Err(ProgramError::InvalidSeeds);
}
load_system_account(info, true)
}
/// Errors if:
/// - Owner is not the system program.
/// - Data is not empty.
/// - Account is not writable.
pub fn load_system_account<'a, 'info>(
info: &'a AccountInfo<'info>,
is_writable: bool,
) -> Result<(), ProgramError> {
if info.owner.ne(&system_program::id()) {
return Err(ProgramError::InvalidAccountOwner);
}
if !info.data_is_empty() {
return Err(ProgramError::AccountAlreadyInitialized);
}
if is_writable && !info.is_writable {
return Err(ProgramError::InvalidAccountData);
}
Ok(())
}
/// Errors if:
/// - Owner is not the sysvar address.
/// - Account cannot load with the expected address.
pub fn load_sysvar<'a, 'info>(
info: &'a AccountInfo<'info>,
key: Pubkey,
) -> Result<(), ProgramError> {
if info.owner.ne(&sysvar::id()) {
return Err(ProgramError::InvalidAccountOwner);
}
load_account(info, key, false)
}
/// Errors if:
/// - Address does not match the expected value.
/// - Expected to be writable, but is not.
pub fn load_account<'a, 'info>(
info: &'a AccountInfo<'info>,
key: Pubkey,
is_writable: bool,
) -> Result<(), ProgramError> {
if info.key.ne(&key) {
return Err(ProgramError::InvalidAccountData);
}
if is_writable && !info.is_writable {
return Err(ProgramError::InvalidAccountData);
}
Ok(())
}
/// Errors if:
/// - Address does not match the expected value.
/// - Account is not executable.
pub fn load_program<'a, 'info>(
info: &'a AccountInfo<'info>,
key: Pubkey,
) -> Result<(), ProgramError> {
if info.key.ne(&key) {
return Err(ProgramError::IncorrectProgramId);
}
if !info.executable {
return Err(ProgramError::InvalidAccountData);
}
Ok(())
}

View File

@@ -0,0 +1,75 @@
use ore_api::{
consts::*, error::OreError, instruction::ClaimArgs, state::Proof, utils::AccountDeserialize,
};
use solana_program::{
account_info::AccountInfo, entrypoint::ProgramResult, program_error::ProgramError,
pubkey::Pubkey,
};
use crate::loaders::*;
/// Claim distributes Ore from the treasury to a miner. Its responsibilies include:
/// 1. Decrement the miner's claimable balance.
/// 2. Transfer tokens from the treasury to the miner.
///
/// Safety requirements:
/// - Claim is a permissionless instruction and can be called by any user.
/// - Can only succeed if the claimed amount is less than or equal to the miner's claimable rewards.
/// - The provided beneficiary, token account, treasury, treasury token account, and token program must be valid.
pub fn process_claim<'a, 'info>(
_program_id: &Pubkey,
accounts: &'a [AccountInfo<'info>],
data: &[u8],
) -> ProgramResult {
// Parse args
let args = ClaimArgs::try_from_bytes(data)?;
let amount = u64::from_le_bytes(args.amount);
// Load accounts
let [signer, beneficiary_info, mint_info, proof_info, treasury_info, treasury_tokens_info, token_program] =
accounts
else {
return Err(ProgramError::NotEnoughAccountKeys);
};
load_signer(signer)?;
load_token_account(beneficiary_info, None, &MINT_ADDRESS, true)?;
load_mint(mint_info, MINT_ADDRESS, true)?;
load_proof(proof_info, signer.key, true)?;
load_treasury(treasury_info, false)?;
load_token_account(
treasury_tokens_info,
Some(treasury_info.key),
&MINT_ADDRESS,
true,
)?;
load_program(token_program, spl_token::id())?;
// Update miner balance
let mut proof_data = proof_info.data.borrow_mut();
let proof = Proof::try_from_bytes_mut(&mut proof_data)?;
proof.balance = proof
.balance
.checked_sub(amount)
.ok_or(OreError::ClaimTooLarge)?;
// Distribute tokens from treasury to beneficiary
solana_program::program::invoke_signed(
&spl_token::instruction::transfer(
&spl_token::id(),
treasury_tokens_info.key,
beneficiary_info.key,
treasury_info.key,
&[treasury_info.key],
amount,
)?,
&[
token_program.clone(),
treasury_tokens_info.clone(),
beneficiary_info.clone(),
treasury_info.clone(),
],
&[&[TREASURY, &[TREASURY_BUMP]]],
)?;
Ok(())
}

View File

@@ -0,0 +1,46 @@
use ore_api::{state::Proof, utils::AccountDeserialize};
use solana_program::{
account_info::AccountInfo, entrypoint::ProgramResult, program_error::ProgramError,
pubkey::Pubkey, system_program,
};
use crate::loaders::*;
/// Close closes a proof account and returns the rent to the owner. Its responsibilities include:
/// 1. Realloc proof account size to 0.
/// 2. Transfer lamports to the owner.
///
/// Safety requirements:
/// - Deregister is a permissionless instruction and can be invoked by any singer.
/// - Can only succeed if the provided proof acount PDA is valid (associated with the signer).
/// - The provided system program must be valid.
pub fn process_close<'a, 'info>(
_program_id: &Pubkey,
accounts: &'a [AccountInfo<'info>],
_data: &[u8],
) -> ProgramResult {
// Load accounts
let [signer, proof_info, system_program] = accounts else {
return Err(ProgramError::NotEnoughAccountKeys);
};
load_signer(signer)?;
load_proof(proof_info, signer.key, true)?;
load_program(system_program, system_program::id())?;
// Validate balance is zero
let proof_data = proof_info.data.borrow();
let proof = Proof::try_from_bytes(&proof_data)?;
if proof.balance.gt(&0) {
return Err(ProgramError::InvalidAccountData);
}
drop(proof_data);
// Realloc data to zero
proof_info.realloc(0, true)?;
// Send lamports to signer
**signer.lamports.borrow_mut() += proof_info.lamports();
**proof_info.lamports.borrow_mut() = 0;
Ok(())
}

View File

@@ -0,0 +1,57 @@
use ore_api::{
state::{Config, Proof},
utils::AccountDeserialize,
};
use solana_program::{
account_info::AccountInfo, entrypoint::ProgramResult, program_error::ProgramError,
pubkey::Pubkey,
};
use crate::loaders::*;
/// Crown marks an account as the top staker if their balance is greater than the last known top staker.
pub fn process_crown<'a, 'info>(
_program_id: &Pubkey,
accounts: &'a [AccountInfo<'info>],
_data: &[u8],
) -> ProgramResult {
// Load accounts
let [signer, config_info, proof_info, proof_new_info] = accounts else {
return Err(ProgramError::NotEnoughAccountKeys);
};
load_signer(signer)?;
load_config(config_info, true)?;
load_any_proof(proof_new_info, false)?;
// Load config
let mut config_data = config_info.data.borrow_mut();
let config = Config::try_from_bytes_mut(&mut config_data)?;
// Load proposed new top staker
let proof_new_data = proof_new_info.data.borrow();
let proof_new = Proof::try_from_bytes(&proof_new_data)?;
// If top staker is not the default null address, then compare balances
if config.top_staker.ne(&Pubkey::new_from_array([0; 32])) {
// Load current top staker
load_any_proof(proof_info, false)?;
let proof_data = proof_info.data.borrow();
let proof = Proof::try_from_bytes(&proof_data)?;
// Require the provided proof account is the current top staker
if config.top_staker.ne(&proof_info.key) {
return Ok(());
}
// Compare balances
if proof_new.balance.lt(&proof.balance) {
return Ok(());
}
}
// Crown the new top staker
config.max_stake = proof_new.balance;
config.top_staker = *proof_new_info.key;
Ok(())
}

View File

@@ -0,0 +1,233 @@
use std::mem::size_of;
use ore_api::{
consts::*,
instruction::*,
state::{Bus, Config, Treasury},
utils::create_pda,
utils::AccountDeserialize,
utils::Discriminator,
};
use solana_program::{
account_info::AccountInfo,
entrypoint::ProgramResult,
program_error::ProgramError,
program_pack::Pack,
pubkey::Pubkey,
system_program, {self, sysvar},
};
use spl_token::state::Mint;
use crate::loaders::*;
/// Initialize sets up the Ore program. Its responsibilities include:
/// 1. Initialize the 8 bus accounts.
/// 2. Initialize the treasury account.
/// 3. Initialize the Ore mint account.
/// 4. Initialize the mint metadata account.
/// 5. Initialize the treasury token account.
/// 6. Set the signer as the program admin.
///
/// Safety requirements:
/// - Initialize is a permissionless instruction and can be called by anyone.
/// - Can only succeed once for the entire lifetime of the program.
/// - Can only succeed if all provided PDAs match their expected values.
/// - Can only succeed if provided system program, token program,
/// associated token program, metadata program, and rent sysvar are valid.
///
/// Discussion
/// - The signer of this instruction is set as the program admin and the
/// upgrade authority of the mint metadata account.
pub fn process_initialize<'a, 'info>(
_program_id: &Pubkey,
accounts: &'a [AccountInfo<'info>],
data: &[u8],
) -> ProgramResult {
// Parse args
let args = InitializeArgs::try_from_bytes(data)?;
// Load accounts
let [signer, bus_0_info, bus_1_info, bus_2_info, bus_3_info, bus_4_info, bus_5_info, bus_6_info, bus_7_info, config_info, metadata_info, mint_info, treasury_info, treasury_tokens_info, system_program, token_program, associated_token_program, metadata_program, rent_sysvar] =
accounts
else {
return Err(ProgramError::NotEnoughAccountKeys);
};
load_signer(signer)?;
load_uninitialized_pda(bus_0_info, &[BUS, &[0]], args.bus_0_bump, &ore_api::id())?;
load_uninitialized_pda(bus_1_info, &[BUS, &[1]], args.bus_1_bump, &ore_api::id())?;
load_uninitialized_pda(bus_2_info, &[BUS, &[2]], args.bus_2_bump, &ore_api::id())?;
load_uninitialized_pda(bus_3_info, &[BUS, &[3]], args.bus_3_bump, &ore_api::id())?;
load_uninitialized_pda(bus_4_info, &[BUS, &[4]], args.bus_4_bump, &ore_api::id())?;
load_uninitialized_pda(bus_5_info, &[BUS, &[5]], args.bus_5_bump, &ore_api::id())?;
load_uninitialized_pda(bus_6_info, &[BUS, &[6]], args.bus_6_bump, &ore_api::id())?;
load_uninitialized_pda(bus_7_info, &[BUS, &[7]], args.bus_7_bump, &ore_api::id())?;
load_uninitialized_pda(config_info, &[CONFIG], args.config_bump, &ore_api::id())?;
load_uninitialized_pda(
metadata_info,
&[
METADATA,
mpl_token_metadata::ID.as_ref(),
MINT_ADDRESS.as_ref(),
],
args.metadata_bump,
&mpl_token_metadata::ID,
)?;
load_uninitialized_pda(
mint_info,
&[MINT, MINT_NOISE.as_slice()],
args.mint_bump,
&ore_api::id(),
)?;
load_uninitialized_pda(
treasury_info,
&[TREASURY],
args.treasury_bump,
&ore_api::id(),
)?;
load_system_account(treasury_tokens_info, true)?;
load_program(system_program, system_program::id())?;
load_program(token_program, spl_token::id())?;
load_program(associated_token_program, spl_associated_token_account::id())?;
load_program(metadata_program, mpl_token_metadata::ID)?;
load_sysvar(rent_sysvar, sysvar::rent::id())?;
// Check signer
if signer.key.ne(&INITIAL_ADMIN) {
return Err(ProgramError::MissingRequiredSignature);
}
// Initialize bus accounts
let bus_infos = [
bus_0_info, bus_1_info, bus_2_info, bus_3_info, bus_4_info, bus_5_info, bus_6_info,
bus_7_info,
];
let bus_bumps = [
args.bus_0_bump,
args.bus_1_bump,
args.bus_2_bump,
args.bus_3_bump,
args.bus_4_bump,
args.bus_5_bump,
args.bus_6_bump,
args.bus_7_bump,
];
for i in 0..BUS_COUNT {
create_pda(
bus_infos[i],
&ore_api::id(),
8 + size_of::<Bus>(),
&[BUS, &[i as u8], &[bus_bumps[i]]],
system_program,
signer,
)?;
let mut bus_data = bus_infos[i].try_borrow_mut_data()?;
bus_data[0] = Bus::discriminator() as u8;
let bus = Bus::try_from_bytes_mut(&mut bus_data)?;
bus.id = i as u64;
bus.rewards = 0;
}
// Initialize config
create_pda(
config_info,
&ore_api::id(),
8 + size_of::<Config>(),
&[CONFIG, &[args.config_bump]],
system_program,
signer,
)?;
let mut config_data = config_info.data.borrow_mut();
config_data[0] = Config::discriminator() as u8;
let config = Config::try_from_bytes_mut(&mut config_data)?;
config.admin = *signer.key;
config.base_reward_rate = INITIAL_BASE_REWARD_RATE;
config.last_reset_at = 0;
config.max_stake = 0;
config.top_staker = Pubkey::new_from_array([0; 32]);
// Initialize treasury
create_pda(
treasury_info,
&ore_api::id(),
8 + size_of::<Treasury>(),
&[TREASURY, &[args.treasury_bump]],
system_program,
signer,
)?;
let mut treasury_data = treasury_info.data.borrow_mut();
treasury_data[0] = Treasury::discriminator() as u8;
drop(treasury_data);
// Initialize mint
create_pda(
mint_info,
&spl_token::id(),
Mint::LEN,
&[MINT, MINT_NOISE.as_slice(), &[args.mint_bump]],
system_program,
signer,
)?;
solana_program::program::invoke_signed(
&spl_token::instruction::initialize_mint(
&spl_token::id(),
mint_info.key,
treasury_info.key,
None,
TOKEN_DECIMALS,
)?,
&[
token_program.clone(),
mint_info.clone(),
treasury_info.clone(),
rent_sysvar.clone(),
],
&[&[MINT, MINT_NOISE.as_slice(), &[args.mint_bump]]],
)?;
// Initialize mint metadata
mpl_token_metadata::instructions::CreateMetadataAccountV3Cpi {
__program: metadata_program,
metadata: metadata_info,
mint: mint_info,
mint_authority: treasury_info,
payer: signer,
update_authority: (signer, true),
system_program,
rent: Some(rent_sysvar),
__args: mpl_token_metadata::instructions::CreateMetadataAccountV3InstructionArgs {
data: mpl_token_metadata::types::DataV2 {
name: METADATA_NAME.to_string(),
symbol: METADATA_SYMBOL.to_string(),
uri: METADATA_URI.to_string(),
seller_fee_basis_points: 0,
creators: None,
collection: None,
uses: None,
},
is_mutable: true,
collection_details: None,
},
}
.invoke_signed(&[&[TREASURY, &[args.treasury_bump]]])?;
// Initialize treasury token account
solana_program::program::invoke(
&spl_associated_token_account::instruction::create_associated_token_account(
signer.key,
treasury_info.key,
mint_info.key,
&spl_token::id(),
),
&[
associated_token_program.clone(),
signer.clone(),
treasury_tokens_info.clone(),
treasury_info.clone(),
mint_info.clone(),
system_program.clone(),
token_program.clone(),
],
)?;
Ok(())
}

View File

@@ -0,0 +1,220 @@
use std::mem::size_of;
use drillx::Solution;
use ore_api::{
consts::*,
error::OreError,
instruction::{MineArgs, OreInstruction},
state::{Bus, Config, Proof},
utils::{AccountDeserialize, MineEvent},
};
use solana_program::program::set_return_data;
#[allow(deprecated)]
use solana_program::{
account_info::AccountInfo,
blake3::hashv,
clock::Clock,
entrypoint::ProgramResult,
log::sol_log,
program_error::ProgramError,
pubkey,
pubkey::Pubkey,
sanitize::SanitizeError,
serialize_utils::{read_pubkey, read_u16, read_u8},
slot_hashes::SlotHash,
sysvar::{self, instructions::load_current_index, Sysvar},
};
use crate::loaders::*;
/// Mine is the primary workhorse instruction of the Ore program. Its responsibilities include:
/// 1. Calculate the hash from the provided nonce.
/// 2. Payout rewards based on difficulty, staking multiplier, and liveness penalty.
/// 3. Generate a new challenge for the miner.
/// 4. Update the miner's lifetime stats.
///
/// Safety requirements:
/// - Mine is a permissionless instruction and can be called by any signer.
/// - Can only succeed if mining is not paused.
/// - Can only succeed if the last reset was less than 60 seconds ago.
/// - Can only succeed if the provided hash satisfies the minimum difficulty requirement.
/// - The the provided proof account must be associated with the signer.
/// - The provided bus, config, noise, stake, and slot hash sysvar must be valid.
pub fn process_mine<'a, 'info>(
_program_id: &Pubkey,
accounts: &'a [AccountInfo<'info>],
data: &[u8],
) -> ProgramResult {
// Parse args
let args = MineArgs::try_from_bytes(data)?;
// Load accounts
let [signer, bus_info, config_info, proof_info, instructions_sysvar, slot_hashes_sysvar] =
accounts
else {
return Err(ProgramError::NotEnoughAccountKeys);
};
load_signer(signer)?;
load_any_bus(bus_info, true)?;
load_config(config_info, false)?;
load_proof_with_miner(proof_info, signer.key, true)?;
load_sysvar(instructions_sysvar, sysvar::instructions::id())?;
load_sysvar(slot_hashes_sysvar, sysvar::slot_hashes::id())?;
// Validate this is the only mine ix in the transaction.
if !validate_transaction(&instructions_sysvar.data.borrow()).unwrap_or(false) {
return Err(OreError::TransactionInvalid.into());
}
// Validate epoch is active.
let config_data = config_info.data.borrow();
let config = Config::try_from_bytes(&config_data)?;
let clock = Clock::get().or(Err(ProgramError::InvalidAccountData))?;
if config
.last_reset_at
.saturating_add(EPOCH_DURATION)
.le(&clock.unix_timestamp)
{
return Err(OreError::NeedsReset.into());
}
// Validate the hash digest.
let mut proof_data = proof_info.data.borrow_mut();
let proof = Proof::try_from_bytes_mut(&mut proof_data)?;
let solution = Solution::new(args.digest, args.nonce);
if !solution.is_valid(&proof.challenge) {
return Err(OreError::HashInvalid.into());
}
// Validate hash satisfies the minimnum difficulty.
let hash = solution.to_hash();
let difficulty = hash.difficulty();
sol_log(&format!("Diff {}", difficulty));
if difficulty.lt(&MIN_DIFFICULTY) {
return Err(OreError::HashTooEasy.into());
}
// Calculate base reward rate.
let difficulty = difficulty.saturating_sub(MIN_DIFFICULTY);
let mut reward = config
.base_reward_rate
.saturating_mul(2u64.saturating_pow(difficulty));
// Apply staking multiplier.
// If user has greater than or equal to the max stake on the network, they receive 2x multiplier.
// Any stake less than this will receives between 1x and 2x multipler. The multipler is only active
// if the miner's last stake deposit was more than one minute ago.
if config.max_stake.gt(&0)
&& proof
.last_stake_at
.saturating_add(ONE_MINUTE)
.le(&clock.unix_timestamp)
{
let staking_reward = proof
.balance
.min(config.max_stake)
.saturating_mul(reward)
.saturating_div(config.max_stake);
reward = reward.saturating_add(staking_reward);
}
// Reject spam transactions.
let t = clock.unix_timestamp;
let t_target = proof.last_hash_at.saturating_add(ONE_MINUTE);
let t_spam = t_target.saturating_sub(TOLERANCE);
if t.lt(&t_spam) {
return Err(OreError::Spam.into());
}
// Apply liveness penalty.
let t_liveness = t_target.saturating_add(TOLERANCE);
if t.gt(&t_liveness) {
reward = reward.saturating_sub(
reward
.saturating_mul(t.saturating_sub(t_liveness) as u64)
.saturating_div(ONE_MINUTE as u64),
);
}
// Limit payout amount to whatever is left in the bus
let mut bus_data = bus_info.data.borrow_mut();
let bus = Bus::try_from_bytes_mut(&mut bus_data)?;
let reward_actual = reward.min(bus.rewards);
// Update balances
bus.theoretical_rewards = bus.theoretical_rewards.saturating_add(reward);
bus.rewards = bus.rewards.saturating_sub(reward_actual);
proof.balance = proof.balance.saturating_add(reward_actual);
// Hash recent slot hash into the next challenge to prevent pre-mining attacks
proof.last_hash = hash.h;
proof.challenge = hashv(&[
hash.h.as_slice(),
&slot_hashes_sysvar.data.borrow()[0..size_of::<SlotHash>()],
])
.0;
// Update time trackers
proof.last_hash_at = clock.unix_timestamp;
// Update lifetime stats
proof.total_hashes = proof.total_hashes.saturating_add(1);
proof.total_rewards = proof.total_rewards.saturating_add(reward);
// Log the mined rewards
set_return_data(
MineEvent {
difficulty: difficulty as u64,
reward: reward_actual,
timing: t.saturating_sub(t_liveness),
}
.to_bytes(),
);
Ok(())
}
/// Require that there is only one `mine` instruction per transaction and it is called from the
/// top level of the transaction.
///
/// The intent here is to disincentivize sybil. As long as a user can fit multiple hashes in a single
/// transaction, there is a financial incentive to sybil multiple keypairs and pack as many hashes
/// as possible into each transaction to minimize fee / hash.
///
/// If each transaction is limited to one hash only, then a user will minimize their fee / hash
/// by allocating all their hashpower to finding the single most difficult hash they can.
fn validate_transaction(msg: &[u8]) -> Result<bool, SanitizeError> {
#[allow(deprecated)]
let idx = load_current_index(msg);
let mut c = 0;
let num_instructions = read_u16(&mut c, msg)?;
let pc = c;
for i in 0..num_instructions as usize {
c = pc + i * 2;
c = read_u16(&mut c, msg)? as usize;
let num_accounts = read_u16(&mut c, msg)? as usize;
c += num_accounts * 33;
// Only allow instructions to call ore and the compute budget program.
match read_pubkey(&mut c, msg)? {
ore_api::ID => {
c += 2;
if let Ok(ix) = OreInstruction::try_from(read_u8(&mut c, msg)?) {
if let OreInstruction::Mine = ix {
if i.ne(&(idx as usize)) {
return Ok(false);
}
}
} else {
return Ok(false);
}
}
COMPUTE_BUDGET_PROGRAM_ID => {} // Noop
_ => return Ok(false),
}
}
Ok(true)
}
/// Program id of the compute budge program.
const COMPUTE_BUDGET_PROGRAM_ID: Pubkey = pubkey!("ComputeBudget111111111111111111111111111111");

View File

@@ -0,0 +1,21 @@
mod claim;
mod close;
mod crown;
mod initialize;
mod mine;
mod open;
mod reset;
mod stake;
mod update;
mod upgrade;
pub use claim::*;
pub use close::*;
pub use crown::*;
pub use initialize::*;
pub use mine::*;
pub use open::*;
pub use reset::*;
pub use stake::*;
pub use update::*;
pub use upgrade::*;

View File

@@ -0,0 +1,83 @@
use std::mem::size_of;
use ore_api::{
consts::*,
instruction::OpenArgs,
state::Proof,
utils::{create_pda, AccountDeserialize, Discriminator},
};
use solana_program::{
account_info::AccountInfo,
blake3::hashv,
clock::Clock,
entrypoint::ProgramResult,
program_error::ProgramError,
pubkey::Pubkey,
slot_hashes::SlotHash,
system_program,
sysvar::{self, Sysvar},
};
use crate::loaders::*;
/// Register generates a new hash chain for a prospective miner. Its responsibilities include:
/// 1. Initialize a new proof account.
/// 2. Generate an initial hash from the signer's key.
///
/// Safety requirements:
/// - Register is a permissionless instruction and can be invoked by any singer.
/// - Can only succeed if the provided proof acount PDA is valid (associated with the signer).
/// - Can only succeed if the user does not already have a proof account.
/// - The provided system program must be valid.
pub fn process_open<'a, 'info>(
_program_id: &Pubkey,
accounts: &'a [AccountInfo<'info>],
data: &[u8],
) -> ProgramResult {
// Parse args
let args = OpenArgs::try_from_bytes(data)?;
// Load accounts
let [signer, miner_info, proof_info, system_program, slot_hashes_info] = accounts else {
return Err(ProgramError::NotEnoughAccountKeys);
};
load_signer(signer)?;
load_system_account(miner_info, false)?;
load_uninitialized_pda(
proof_info,
&[PROOF, signer.key.as_ref()],
args.bump,
&ore_api::id(),
)?;
load_program(system_program, system_program::id())?;
load_sysvar(slot_hashes_info, sysvar::slot_hashes::id())?;
// Initialize proof
create_pda(
proof_info,
&ore_api::id(),
8 + size_of::<Proof>(),
&[PROOF, signer.key.as_ref(), &[args.bump]],
system_program,
signer,
)?;
let clock = Clock::get().or(Err(ProgramError::InvalidAccountData))?;
let mut proof_data = proof_info.data.borrow_mut();
proof_data[0] = Proof::discriminator() as u8;
let proof = Proof::try_from_bytes_mut(&mut proof_data)?;
proof.authority = *signer.key;
proof.balance = 0;
proof.challenge = hashv(&[
signer.key.as_ref(),
&slot_hashes_info.data.borrow()[0..size_of::<SlotHash>()],
])
.0;
proof.last_hash = [0; 32];
proof.last_hash_at = clock.unix_timestamp;
proof.last_stake_at = clock.unix_timestamp;
proof.miner = *miner_info.key;
proof.total_hashes = 0;
proof.total_rewards = 0;
Ok(())
}

View File

@@ -0,0 +1,254 @@
use ore_api::{
consts::*,
error::OreError,
state::{Bus, Config},
utils::AccountDeserialize,
};
use solana_program::{
account_info::AccountInfo, clock::Clock, entrypoint::ProgramResult,
program_error::ProgramError, program_pack::Pack, pubkey::Pubkey, sysvar::Sysvar,
};
use spl_token::state::Mint;
use crate::loaders::{
load_bus, load_config, load_mint, load_program, load_signer, load_token_account, load_treasury,
};
/// Reset sets up the Ore program for the next epoch. Its responsibilities include:
/// 1. Reset bus account rewards counters.
/// 2. Adjust the reward rate to stabilize inflation.
/// 3. Top up the treasury token account to fund claims.
///
/// Safety requirements:
/// - Reset is a permissionless instruction and can be invoked by any signer.
/// - Can only succeed if START_AT has passed.
/// - Can only succeed if more tha 60 seconds or more have passed since the last successful reset.
/// - The busses, mint, treasury, treasury token account, and token program must all be valid.
///
/// Discussion:
/// - It is important that `reset` can only be invoked once per 60 second period to ensure the supply growth rate
/// stays within the guaranteed bounds of 0 ≤ R ≤ 2 ORE/min.
/// - The reward rate is dynamically adjusted based on last epoch's theoretical reward rate to target an average
/// supply growth rate of 1 ORE/min.
/// - The "theoretical" reward rate refers to the amount that would have been paid out if rewards were not capped by
/// the bus limits. It's necessary to use this value to ensure the reward rate update calculation accurately
/// accounts for the difficulty of submitted hashes.
pub fn process_reset<'a, 'info>(
_program_id: &Pubkey,
accounts: &'a [AccountInfo<'info>],
_data: &[u8],
) -> ProgramResult {
// Load accounts
let [signer, bus_0_info, bus_1_info, bus_2_info, bus_3_info, bus_4_info, bus_5_info, bus_6_info, bus_7_info, config_info, mint_info, treasury_info, treasury_tokens_info, token_program] =
accounts
else {
return Err(ProgramError::NotEnoughAccountKeys);
};
load_signer(signer)?;
load_bus(bus_0_info, 0, true)?;
load_bus(bus_1_info, 1, true)?;
load_bus(bus_2_info, 2, true)?;
load_bus(bus_3_info, 3, true)?;
load_bus(bus_4_info, 4, true)?;
load_bus(bus_5_info, 5, true)?;
load_bus(bus_6_info, 6, true)?;
load_bus(bus_7_info, 7, true)?;
load_config(config_info, true)?;
load_mint(mint_info, MINT_ADDRESS, true)?;
load_treasury(treasury_info, true)?;
load_token_account(
treasury_tokens_info,
Some(treasury_info.key),
mint_info.key,
true,
)?;
load_program(token_program, spl_token::id())?;
let busses: [&AccountInfo; BUS_COUNT] = [
bus_0_info, bus_1_info, bus_2_info, bus_3_info, bus_4_info, bus_5_info, bus_6_info,
bus_7_info,
];
// Validate enough time has passed since last reset
let mut config_data = config_info.data.borrow_mut();
let config = Config::try_from_bytes_mut(&mut config_data)?;
let clock = Clock::get().or(Err(ProgramError::InvalidAccountData))?;
if config
.last_reset_at
.saturating_add(EPOCH_DURATION)
.gt(&clock.unix_timestamp)
{
return Ok(());
}
// Update reset timestamp
config.last_reset_at = clock.unix_timestamp;
// Reset bus accounts and calculate actual rewards mined since last reset
let mut total_remaining_rewards = 0u64;
let mut total_theoretical_rewards = 0u64;
for i in 0..BUS_COUNT {
let mut bus_data = busses[i].data.borrow_mut();
let bus = Bus::try_from_bytes_mut(&mut bus_data)?;
total_remaining_rewards = total_remaining_rewards.saturating_add(bus.rewards);
total_theoretical_rewards =
total_theoretical_rewards.saturating_add(bus.theoretical_rewards);
bus.rewards = BUS_EPOCH_REWARDS;
bus.theoretical_rewards = 0;
}
let total_epoch_rewards = MAX_EPOCH_REWARDS.saturating_sub(total_remaining_rewards);
// Update base reward rate for next epoch
config.base_reward_rate =
calculate_new_reward_rate(config.base_reward_rate, total_theoretical_rewards);
// Max supply check
let mint = Mint::unpack(&mint_info.data.borrow()).expect("Failed to parse mint");
if mint.supply.ge(&MAX_SUPPLY) {
return Err(OreError::MaxSupply.into());
}
// Fund treasury token account
let amount = MAX_SUPPLY
.saturating_sub(mint.supply)
.min(total_epoch_rewards);
solana_program::program::invoke_signed(
&spl_token::instruction::mint_to(
&spl_token::id(),
mint_info.key,
treasury_tokens_info.key,
treasury_info.key,
&[treasury_info.key],
amount,
)?,
&[
token_program.clone(),
mint_info.clone(),
treasury_tokens_info.clone(),
treasury_info.clone(),
],
&[&[TREASURY, &[TREASURY_BUMP]]],
)?;
Ok(())
}
/// This function calculates what the new reward rate should be based on how many total rewards
/// were mined in the prior epoch. The math is largely identitical to function used by the Bitcoin
/// network to update the difficulty between each epoch.
///
/// new_rate = current_rate * (target_rewards / actual_rewards)
///
/// The new rate is then smoothed by a constant factor to avoid large fluctuations. In Ore's case,
/// the epochs are short (60 seconds) so a smoothing factor of 2 has been chosen. That is, the reward rate
/// can at most double or halve from one epoch to the next.
pub(crate) fn calculate_new_reward_rate(current_rate: u64, epoch_rewards: u64) -> u64 {
// Avoid division by zero. Leave the reward rate unchanged, if detected.
if epoch_rewards.eq(&0) {
return current_rate;
}
// Calculate new reward rate.
let new_rate = (current_rate as u128)
.saturating_mul(TARGET_EPOCH_REWARDS as u128)
.saturating_div(epoch_rewards as u128) as u64;
// Smooth reward rate so it cannot change by more than a constant factor from one epoch to the next.
let new_rate_min = current_rate.saturating_div(SMOOTHING_FACTOR);
let new_rate_max = current_rate.saturating_mul(SMOOTHING_FACTOR);
let new_rate_smoothed = new_rate_min.max(new_rate_max.min(new_rate));
// Prevent reward rate from dropping below 1 or exceeding BUS_EPOCH_REWARDS and return.
new_rate_smoothed.max(1).min(BUS_EPOCH_REWARDS)
}
#[cfg(test)]
mod tests {
use rand::{distributions::Uniform, Rng};
use crate::{
calculate_new_reward_rate, BUS_EPOCH_REWARDS, MAX_EPOCH_REWARDS, SMOOTHING_FACTOR,
TARGET_EPOCH_REWARDS,
};
const FUZZ_SIZE: u64 = 10_000;
#[test]
fn test_calculate_new_reward_rate_target() {
let current_rate = 1000;
let new_rate = calculate_new_reward_rate(current_rate, TARGET_EPOCH_REWARDS);
assert!(new_rate.eq(&current_rate));
}
#[test]
fn test_calculate_new_reward_rate_div_by_zero() {
let current_rate = 1000;
let new_rate = calculate_new_reward_rate(current_rate, 0);
assert!(new_rate.eq(&current_rate));
}
#[test]
fn test_calculate_new_reward_rate_lower() {
let current_rate = 1000;
let new_rate =
calculate_new_reward_rate(current_rate, TARGET_EPOCH_REWARDS.saturating_add(1_000_000));
assert!(new_rate.lt(&current_rate));
}
#[test]
fn test_calculate_new_reward_rate_lower_fuzz() {
let mut rng = rand::thread_rng();
for _ in 0..FUZZ_SIZE {
let current_rate: u64 = rng.sample(Uniform::new(1, BUS_EPOCH_REWARDS));
let actual_rewards: u64 =
rng.sample(Uniform::new(TARGET_EPOCH_REWARDS, MAX_EPOCH_REWARDS));
let new_rate = calculate_new_reward_rate(current_rate, actual_rewards);
assert!(new_rate.lt(&current_rate));
}
}
#[test]
fn test_calculate_new_reward_rate_higher() {
let current_rate = 1000;
let new_rate =
calculate_new_reward_rate(current_rate, TARGET_EPOCH_REWARDS.saturating_sub(1_000_000));
println!("{:?} {:?}", new_rate, current_rate);
assert!(new_rate.gt(&current_rate));
}
#[test]
fn test_calculate_new_reward_rate_higher_fuzz() {
let mut rng = rand::thread_rng();
for _ in 0..FUZZ_SIZE {
let current_rate: u64 = rng.sample(Uniform::new(1, BUS_EPOCH_REWARDS));
let actual_rewards: u64 = rng.sample(Uniform::new(1, TARGET_EPOCH_REWARDS));
let new_rate = calculate_new_reward_rate(current_rate, actual_rewards);
assert!(new_rate.gt(&current_rate));
}
}
#[test]
fn test_calculate_new_reward_rate_max_smooth() {
let current_rate = 1000;
let new_rate = calculate_new_reward_rate(current_rate, 1);
assert!(new_rate.eq(&current_rate.saturating_mul(SMOOTHING_FACTOR)));
}
#[test]
fn test_calculate_new_reward_rate_min_smooth() {
let current_rate = 1000;
let new_rate = calculate_new_reward_rate(current_rate, u64::MAX);
assert!(new_rate.eq(&current_rate.saturating_div(SMOOTHING_FACTOR)));
}
#[test]
fn test_calculate_new_reward_rate_max_inputs() {
let new_rate = calculate_new_reward_rate(BUS_EPOCH_REWARDS, MAX_EPOCH_REWARDS);
assert!(new_rate.eq(&BUS_EPOCH_REWARDS.saturating_div(SMOOTHING_FACTOR)));
}
#[test]
fn test_calculate_new_reward_rate_min_inputs() {
let new_rate = calculate_new_reward_rate(1, 1);
assert!(new_rate.eq(&1u64.saturating_mul(SMOOTHING_FACTOR)));
}
}

View File

@@ -0,0 +1,69 @@
use ore_api::{consts::*, instruction::StakeArgs, state::Proof, utils::AccountDeserialize};
use solana_program::{
account_info::AccountInfo, clock::Clock, entrypoint::ProgramResult,
program_error::ProgramError, pubkey::Pubkey, sysvar::Sysvar,
};
use crate::loaders::*;
/// Stake deposits Ore into a miner's proof account to earn multiplier. Its responsibilies include:
/// 1. Transfer tokens from the miner to the treasury account.
/// 2. Increment the miner's claimable balance.
///
/// Safety requirements:
/// - Stake is a permissionless instruction and can be called by any user.
/// - Can only succeed if the amount is less than or equal to the miner's transferable tokens.
/// - The provided beneficiary, proof, sender, treasury token account, and token program must be valid.
pub fn process_stake<'a, 'info>(
_program_id: &Pubkey,
accounts: &'a [AccountInfo<'info>],
data: &[u8],
) -> ProgramResult {
// Parse args
let args = StakeArgs::try_from_bytes(data)?;
let amount = u64::from_le_bytes(args.amount);
// Load accounts
let [signer, proof_info, sender_info, treasury_tokens_info, token_program] = accounts else {
return Err(ProgramError::NotEnoughAccountKeys);
};
load_signer(signer)?;
load_proof(proof_info, signer.key, true)?;
load_token_account(sender_info, Some(signer.key), &MINT_ADDRESS, true)?;
load_token_account(
treasury_tokens_info,
Some(&TREASURY_ADDRESS),
&MINT_ADDRESS,
true,
)?;
load_program(token_program, spl_token::id())?;
// Update proof balance
let mut proof_data = proof_info.data.borrow_mut();
let proof = Proof::try_from_bytes_mut(&mut proof_data)?;
proof.balance = proof.balance.saturating_add(amount);
// Update deposit timestamp
let clock = Clock::get().or(Err(ProgramError::InvalidAccountData))?;
proof.last_stake_at = clock.unix_timestamp;
// Distribute tokens from signer to treasury
solana_program::program::invoke(
&spl_token::instruction::transfer(
&spl_token::id(),
sender_info.key,
treasury_tokens_info.key,
signer.key,
&[signer.key],
amount,
)?,
&[
token_program.clone(),
sender_info.clone(),
treasury_tokens_info.clone(),
signer.clone(),
],
)?;
Ok(())
}

View File

@@ -0,0 +1,29 @@
use ore_api::{state::Proof, utils::AccountDeserialize};
use solana_program::{
account_info::AccountInfo, entrypoint::ProgramResult, program_error::ProgramError,
pubkey::Pubkey,
};
use crate::loaders::*;
/// Update changes the miner authority on a proof account.
pub fn process_update<'a, 'info>(
_program_id: &Pubkey,
accounts: &'a [AccountInfo<'info>],
_data: &[u8],
) -> ProgramResult {
// Load accounts
let [signer, miner_info, proof_info] = accounts else {
return Err(ProgramError::NotEnoughAccountKeys);
};
load_signer(signer)?;
load_system_account(miner_info, false)?;
load_proof(proof_info, signer.key, true)?;
// Update the proof
let mut proof_data = proof_info.data.borrow_mut();
let proof = Proof::try_from_bytes_mut(&mut proof_data)?;
proof.miner = *miner_info.key;
Ok(())
}

View File

@@ -0,0 +1,89 @@
use ore_api::{consts::*, error::OreError, instruction::StakeArgs};
use solana_program::{
account_info::AccountInfo, entrypoint::ProgramResult, program_error::ProgramError,
program_pack::Pack, pubkey::Pubkey,
};
use spl_token::state::Mint;
use crate::loaders::*;
/// Upgrade allows a user to migrate a v1 token to a v2 token one-for-one. Its responsibilies include:
/// 1. Burns the v1 tokens.
/// 2. Mints an equivalent number of v2 tokens to the user.
///
/// Safety requirements:
/// - Upgrade is a permissionless instruction and can be called by any user.
/// - The provided beneficiary, mint, mint v1, sender, and token program must be valid.
pub fn process_upgrade<'a, 'info>(
_program_id: &Pubkey,
accounts: &'a [AccountInfo<'info>],
data: &[u8],
) -> ProgramResult {
// Parse args
let args = StakeArgs::try_from_bytes(data)?;
let amount = u64::from_le_bytes(args.amount);
// Load accounts
let [signer, beneficiary_info, mint_info, mint_v1_info, sender_info, treasury_info, token_program] =
accounts
else {
return Err(ProgramError::NotEnoughAccountKeys);
};
load_signer(signer)?;
load_token_account(beneficiary_info, Some(&signer.key), &MINT_ADDRESS, true)?;
load_mint(mint_info, MINT_ADDRESS, true)?;
load_mint(mint_v1_info, MINT_V1_ADDRESS, true)?;
load_token_account(sender_info, Some(signer.key), &MINT_V1_ADDRESS, true)?;
load_program(token_program, spl_token::id())?;
// Burn v1 tokens
solana_program::program::invoke(
&spl_token::instruction::burn(
&spl_token::id(),
sender_info.key,
mint_v1_info.key,
signer.key,
&[signer.key],
amount,
)?,
&[
token_program.clone(),
sender_info.clone(),
mint_v1_info.clone(),
signer.clone(),
],
)?;
// Account for decimals change.
// v1 token has 9 decimals. v2 token has 11.
let amount_to_mint = amount.saturating_mul(100);
// Cap at max supply.
let mint_data = mint_info.data.borrow();
let mint = Mint::unpack(&mint_data)?;
if mint.supply.saturating_add(amount_to_mint).gt(&MAX_SUPPLY) {
return Err(OreError::MaxSupply.into());
}
drop(mint_data);
// Mint to the beneficiary account
solana_program::program::invoke_signed(
&spl_token::instruction::mint_to(
&spl_token::id(),
mint_info.key,
beneficiary_info.key,
treasury_info.key,
&[treasury_info.key],
amount_to_mint,
)?,
&[
token_program.clone(),
mint_info.clone(),
beneficiary_info.clone(),
treasury_info.clone(),
],
&[&[TREASURY, &[TREASURY_BUMP]]],
)?;
Ok(())
}