Skip to content

Commit

Permalink
Add schedule to release vesting #38 (#39)
Browse files Browse the repository at this point in the history
* Add schedule to release vesting #38

* Simplify output for schedule in vesting-contract-cli #38

Co-authored-by: Semen Medvedev <sm@neonlabs.org>
  • Loading branch information
s-medvedev and Semen Medvedev authored May 18, 2022
1 parent 7bc097e commit 1fdefeb
Show file tree
Hide file tree
Showing 4 changed files with 178 additions and 13 deletions.
13 changes: 9 additions & 4 deletions addin-vesting/cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// use std::str::FromStr;
use chrono::{DateTime, Duration};
use chrono::{NaiveDateTime, DateTime, Duration};
use clap::{
crate_description, crate_name, crate_version, value_t, App, AppSettings, Arg, SubCommand,
};
Expand Down Expand Up @@ -425,11 +425,16 @@ fn report_vesting_record_info(vesting_record: &VestingRecord) {

let schedules = &vesting_record.schedule;

msg!("Schedule:");
for i in 0..schedules.len() {
msg!("\nSCHEDULE {:?}", i);
msg!("Release Height: {:?}", &schedules[i].release_time);
msg!("Amount: {:?}", &schedules[i].amount);
msg!(" {:2}: amount {}, timestamp {} ({})",
i,
&schedules[i].amount,
&schedules[i].release_time,
NaiveDateTime::from_timestamp(schedules[i].release_time.try_into().unwrap(), 0u32),
);
}
msg!("Total amount: {}", schedules.iter().map(|v| v.amount).sum::<u64>());
}

fn main() {
Expand Down
2 changes: 2 additions & 0 deletions launch-script/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ borsh = "0.9.1"
log = "0.4.11"
clap = "2.33.3"
thiserror = "1.0"
chrono = "0.4.0"
chronoutil = "0.2.3"
spl-token = { version = "3.3", path = "../solana-program-library/token/program", features = [ "no-entrypoint" ] }
spl-associated-token-account = { path = "../solana-program-library/associated-token-account/program", features = [ "no-entrypoint" ] }
spl-governance = { version = "2.2", path = "../solana-program-library/governance/program" }
Expand Down
36 changes: 27 additions & 9 deletions launch-script/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ mod wallet;
mod helpers;
mod msig;
mod token_distribution;
mod schedule_creator;

use crate::{
tokens::{
Expand All @@ -23,6 +24,7 @@ use crate::{
token_distribution::{
TokenDistribution,
},
schedule_creator::ScheduleCreator,
};
use solana_sdk::{
pubkey::Pubkey,
Expand Down Expand Up @@ -75,15 +77,25 @@ pub enum AccountOwner {
Key(Pubkey),
}

#[derive(Debug,PartialEq)]
#[derive(Debug,PartialEq,Copy,Clone)]
pub enum Lockup {
NoLockup,
For4Years,
For1Year_1YearLinear,
}

impl Lockup {
pub fn default() -> Self {Lockup::For1Year_1YearLinear}

pub fn is_locked(&self) -> bool {*self != Lockup::NoLockup}

pub fn get_schedule_size(&self) -> u32 {
match *self {
Lockup::NoLockup => 1,
Lockup::For4Years => 1,
Lockup::For1Year_1YearLinear => 12,
}
}
}

pub struct ExtraTokenAccount {
Expand Down Expand Up @@ -333,7 +345,7 @@ fn process_environment(wallet: &Wallet, client: &Client, setup: bool, verbose: b
system_instruction::transfer( // Charge VestingRecord
&wallet.payer_keypair.pubkey(),
&vesting_addin.find_vesting_account(&vesting_token_account),
Rent::default().minimum_balance(vesting_addin.get_vesting_account_size(1, true)),
Rent::default().minimum_balance(vesting_addin.get_vesting_account_size(Lockup::default().get_schedule_size(), true)),
),
]);
let transaction = client.create_transaction(
Expand Down Expand Up @@ -391,7 +403,7 @@ fn process_environment(wallet: &Wallet, client: &Client, setup: bool, verbose: b
system_instruction::transfer( // Charge VestingRecord
&wallet.payer_keypair.pubkey(),
&vesting_addin.find_vesting_account(&token_account_address),
Rent::default().minimum_balance(vesting_addin.get_vesting_account_size(1, true)),
Rent::default().minimum_balance(vesting_addin.get_vesting_account_size(token_account.lockup.get_schedule_size(), true)),
),
]);
}
Expand Down Expand Up @@ -660,8 +672,9 @@ fn setup_proposal_ido(wallet: &Wallet, client: &Client, proposal_index: Option<u
// =========================================================================
// Create TGE proposal (Token Genesis Event)
// =========================================================================
fn setup_proposal_tge(wallet: &Wallet, client: &Client, proposal_index: Option<u32>, setup: bool, verbose: bool) -> Result<(), ScriptError> {
fn setup_proposal_tge(wallet: &Wallet, client: &Client, proposal_index: Option<u32>, setup: bool, verbose: bool, testing: bool) -> Result<(), ScriptError> {
let executor = TransactionExecutor {client, setup, verbose};
let schedule_creator = ScheduleCreator::new(testing);

let realm = Realm::new(&client, &wallet.governance_program_id, REALM_NAME, &wallet.community_pubkey);
realm.update_max_voter_weight_record_address()?;
Expand Down Expand Up @@ -740,8 +753,7 @@ fn setup_proposal_tge(wallet: &Wallet, client: &Client, proposal_index: Option<u

let seed: String = format!("{}_vesting_{}", REALM_NAME, i);
let vesting_token_account = Pubkey::create_with_seed(&wallet.creator_keypair.pubkey(), &seed, &spl_token::id()).unwrap();
// TODO Calculate schedule
let schedule = vec!(VestingSchedule { release_time: 0, amount: voter.weight });
let schedule = schedule_creator.get_schedule(voter.weight, Lockup::default());

transaction_inserter.insert_transaction_checked(
&format!("Deposit {} to {} on token account {}",
Expand All @@ -766,8 +778,7 @@ fn setup_proposal_tge(wallet: &Wallet, client: &Client, proposal_index: Option<u

if token_account.lockup.is_locked() {
let token_account_owner = account_owner_resolver.get_owner_pubkey(&token_account.owner)?;
// TODO Calculate schedule
let schedule = vec!(VestingSchedule { release_time: 0, amount: token_account.amount });
let schedule = schedule_creator.get_schedule(token_account.amount, token_account.lockup);

transaction_inserter.insert_transaction_checked(
&format!("Deposit {} to {} on token account {}",
Expand Down Expand Up @@ -966,6 +977,12 @@ fn main() {
.takes_value(false)
.help("Send transactions to blockchain")
)
.arg(
Arg::with_name("testing")
.long("testing")
.takes_value(false)
.help("Configure testing environment")
)
.subcommand(SubCommand::with_name("environment")
.about("Prepare environment for launching")
)
Expand Down Expand Up @@ -1006,6 +1023,7 @@ fn main() {

let send_trx: bool = matches.is_present("send_trx");
let verbose: bool = matches.is_present("verbose");
let testing: bool = matches.is_present("testing");
match matches.subcommand() {
("environment", Some(arg_matches)) => {
process_environment(&wallet, &client, send_trx, verbose).unwrap()
Expand All @@ -1014,7 +1032,7 @@ fn main() {
let proposal_index = arg_matches.value_of("index").map(|v| v.parse::<u32>().unwrap());
match arg_matches.subcommand() {
("create-tge", Some(arg_matches)) => {
setup_proposal_tge(&wallet, &client, proposal_index, send_trx, verbose).unwrap()
setup_proposal_tge(&wallet, &client, proposal_index, send_trx, verbose, testing).unwrap()
},
("create-ido", Some(arg_matches)) => {
setup_proposal_ido(&wallet, &client, proposal_index, send_trx, verbose).unwrap()
Expand Down
140 changes: 140 additions & 0 deletions launch-script/src/schedule_creator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
use chrono::prelude::*;
use chronoutil::delta::{shift_months, shift_years};
use chrono::Duration;
use crate::Lockup;
use spl_governance_addin_vesting::state::VestingSchedule;

pub struct ScheduleCreator {
pub current: NaiveDateTime,
pub testing: bool,
}

impl ScheduleCreator {
pub fn new(testing: bool) -> Self {
let current = if testing {
Utc::now().naive_utc()
} else {
Utc::today().naive_utc().and_hms(0, 0, 0)
};
Self {
current,
testing,
}
}

pub fn get_schedule(&self, amount: u64, lockup: Lockup) -> Vec<VestingSchedule> {
if self.testing {
self._get_schedule_testing(amount, &lockup)
} else {
self._get_schedule_real(amount, lockup)
}
}

fn _get_schedule_real(&self, amount: u64, lockup: Lockup) -> Vec<VestingSchedule> {
match lockup {
Lockup::NoLockup => {
vec![
VestingSchedule {release_time: 0, amount}
]
},
Lockup::For4Years => {
vec![
VestingSchedule {
release_time: shift_years(self.current, 4).timestamp() as u64,
amount
}
]
},
Lockup::For1Year_1YearLinear => {
let mut schedules = vec!();
let start = shift_years(self.current, 1);
for i in 1i32..=12 {
let prev = (amount as u128)
.checked_mul((i-1) as u128).unwrap()
.checked_div(12).unwrap() as u64;
let curr = (amount as u128)
.checked_mul(i as u128).unwrap()
.checked_div(12).unwrap() as u64;
let schedule = VestingSchedule {
release_time: shift_months(start, i).timestamp() as u64,
amount: curr-prev
};
schedules.push(schedule)
};
schedules
},
}
}

fn _get_schedule_testing(&self, amount: u64, lockup: &Lockup) -> Vec<VestingSchedule> {
match lockup {
Lockup::NoLockup => {
vec![
VestingSchedule {release_time: 0, amount}
]
},
Lockup::For4Years => {
vec![
VestingSchedule {
release_time: (self.current + Duration::minutes(12)).timestamp() as u64,
amount
}
]
},
Lockup::For1Year_1YearLinear => {
let mut schedules = vec!();
let start = self.current + Duration::minutes(3);
for i in 1i32..=12 {
let prev = (amount as u128)
.checked_mul((i-1) as u128).unwrap()
.checked_div(12).unwrap() as u64;
let curr = (amount as u128)
.checked_mul(i as u128).unwrap()
.checked_div(12).unwrap() as u64;
let schedule = VestingSchedule {
release_time: (start + Duration::seconds((i*180/12).into())).timestamp() as u64,
amount: curr-prev
};
schedules.push(schedule)
};
schedules
},
}
}
}

#[cfg(test)]
mod test {
use super::*;

#[test]
fn test_schedule_creator_testing() {
let schedule_creator = ScheduleCreator::new(true);
println!("{:?}", schedule_creator.get_schedule(11, Lockup::NoLockup));
println!("{:?}", schedule_creator.get_schedule(11, Lockup::For4Years));
println!("{:?}", schedule_creator.get_schedule(11, Lockup::For1Year_1YearLinear));
}

#[test]
fn test_schedule_creator_real() {
let schedule_creator = ScheduleCreator::new(false);
println!("{:?}", schedule_creator.get_schedule(1_000_000, Lockup::NoLockup));
println!("{:?}", schedule_creator.get_schedule(1_000_000, Lockup::For4Years));
println!("{:?}", schedule_creator.get_schedule(1_000_000, Lockup::For1Year_1YearLinear));
}

#[test]
fn test_date() {
let today = Utc::today();
let curr = today.naive_utc().and_hms(0, 0, 0);
let curr = Utc.ymd(2022, 1, 31).and_hms(0, 0, 0);

println!("Today: {}", today);
println!("Current: {} {}", curr, curr.timestamp());

for i in 1..=12 {
let curr2 = shift_months(curr, i);
println!("Current {:2}: {} {}", i, curr2, curr2.timestamp());
}
}
}

0 comments on commit 1fdefeb

Please sign in to comment.