mirror of
https://github.com/d0zingcat/ore.git
synced 2026-05-14 15:10:13 +00:00
refactor
This commit is contained in:
34
core/program/Cargo.toml
Normal file
34
core/program/Cargo.toml
Normal 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
41
core/program/src/lib.rs
Normal 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
424
core/program/src/loaders.rs
Normal 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(())
|
||||
}
|
||||
75
core/program/src/processor/claim.rs
Normal file
75
core/program/src/processor/claim.rs
Normal 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(())
|
||||
}
|
||||
46
core/program/src/processor/close.rs
Normal file
46
core/program/src/processor/close.rs
Normal 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(())
|
||||
}
|
||||
57
core/program/src/processor/crown.rs
Normal file
57
core/program/src/processor/crown.rs
Normal 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(())
|
||||
}
|
||||
233
core/program/src/processor/initialize.rs
Normal file
233
core/program/src/processor/initialize.rs
Normal 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(())
|
||||
}
|
||||
220
core/program/src/processor/mine.rs
Normal file
220
core/program/src/processor/mine.rs
Normal 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");
|
||||
21
core/program/src/processor/mod.rs
Normal file
21
core/program/src/processor/mod.rs
Normal 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::*;
|
||||
83
core/program/src/processor/open.rs
Normal file
83
core/program/src/processor/open.rs
Normal 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(())
|
||||
}
|
||||
254
core/program/src/processor/reset.rs
Normal file
254
core/program/src/processor/reset.rs
Normal 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(¤t_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(¤t_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(¤t_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(¤t_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(¤t_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(¤t_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(¤t_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(¤t_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)));
|
||||
}
|
||||
}
|
||||
69
core/program/src/processor/stake.rs
Normal file
69
core/program/src/processor/stake.rs
Normal 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(())
|
||||
}
|
||||
29
core/program/src/processor/update.rs
Normal file
29
core/program/src/processor/update.rs
Normal 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(())
|
||||
}
|
||||
89
core/program/src/processor/upgrade.rs
Normal file
89
core/program/src/processor/upgrade.rs
Normal 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(())
|
||||
}
|
||||
Reference in New Issue
Block a user