Skip to content

Commit

Permalink
fixed conflicts
Browse files Browse the repository at this point in the history
  • Loading branch information
VladasZ committed Oct 26, 2023
1 parent 28d7dab commit 15a2503
Show file tree
Hide file tree
Showing 14 changed files with 101 additions and 422 deletions.
13 changes: 3 additions & 10 deletions contract/src/auth/api.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,7 @@
use near_sdk::near_bindgen;
use model::AuthApi;
use near_sdk::{env::log_str, near_bindgen, require, AccountId};

use crate::*;

trait AuthApi {
fn add_oracle(&mut self, account_id: AccountId);

fn remove_oracle(&mut self, account_id: AccountId);

fn get_oracles(&self) -> Vec<AccountId>;
}
use crate::{Contract, ContractExt};

#[near_bindgen]
impl AuthApi for Contract {
Expand Down
10 changes: 6 additions & 4 deletions contract/src/burn/api.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use crate::{common::unix_timestamp, *};
use model::{BurnApi, TokensAmount, UnixTimestamp};
use near_sdk::{
env, ext_contract, is_promise_success, json_types::U128, near_bindgen, serde_json::json, Gas, Promise,
PromiseOrValue,
};

trait BurnApi {
fn burn(&mut self) -> PromiseOrValue<U128>;
}
use crate::{common::unix_timestamp, Contract, ContractExt};

#[near_bindgen]
impl BurnApi for Contract {
Expand Down
21 changes: 9 additions & 12 deletions contract/src/claim/api.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
use crate::{common::unix_timestamp, *};
use model::{ClaimApi, ClaimAvailabilityView, TokensAmount, UnixTimestamp};
use near_sdk::{
env, json_types::U128, near_bindgen, require, serde_json::json, AccountId, Gas, Promise, PromiseOrValue,
};

pub trait ClaimApi {
fn get_claimable_balance_for_account(&self, account_id: AccountId) -> U128;

fn is_claim_available(&self, account_id: AccountId) -> ClaimAvailabilityView;

fn claim(&mut self) -> PromiseOrValue<U128>;
}
use crate::{common::unix_timestamp, Contract, ContractExt};

#[near_bindgen]
impl ClaimApi for Contract {
Expand All @@ -17,7 +14,7 @@ impl ClaimApi for Contract {
let mut total_accrual: TokensAmount = 0;
let now: UnixTimestamp = unix_timestamp(env::block_timestamp_ms());

for (datetime, index) in account_data.accruals.iter() {
for (datetime, index) in &account_data.accruals {
if now - datetime > self.burn_period {
continue;
}
Expand All @@ -40,7 +37,7 @@ impl ClaimApi for Contract {
return ClaimAvailabilityView::Available;
};

let now_seconds = (env::block_timestamp_ms() / 1_000) as u32;
let now_seconds = unix_timestamp(env::block_timestamp_ms());

if now_seconds - last_claim_at > self.claim_period {
ClaimAvailabilityView::Available
Expand All @@ -49,7 +46,7 @@ impl ClaimApi for Contract {
}
}

fn claim(&mut self) -> PromiseOrValue<U128> {
fn claim(&mut self) -> PromiseOrValue<()> {
let account_id = env::predecessor_account_id();

require!(
Expand All @@ -59,7 +56,7 @@ impl ClaimApi for Contract {

let account_data = self.accounts.get_mut(&account_id).expect("Account data is not found");

let now: UnixTimestamp = (env::block_timestamp_ms() / 1000) as u32;
let now = unix_timestamp(env::block_timestamp_ms());
let mut total_accrual: TokensAmount = 0;

for (datetime, index) in &account_data.accruals {
Expand Down
2 changes: 1 addition & 1 deletion contract/src/clean/api.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use near_sdk::{near_bindgen, AccountId};

use crate::*;
use crate::{Contract, ContractExt};

pub trait CleanApi {
fn clean(&mut self, account_ids: Vec<AccountId>);
Expand Down
4 changes: 3 additions & 1 deletion contract/src/common/asserts.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use crate::*;
use near_sdk::{env, require};

use crate::Contract;

impl Contract {
pub(crate) fn assert_oracle(&self) {
Expand Down
6 changes: 4 additions & 2 deletions contract/src/common/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use crate::*;
use model::UnixTimestamp;
use near_sdk::env::panic_str;

mod asserts;

pub(crate) fn unix_timestamp(ms: u64) -> UnixTimestamp {
(ms / 1000) as u32
u32::try_from(ms / 1000)
.unwrap_or_else(|err| panic_str(&format!("Failed to get convert milliseconds to Unix timestamp: {err}")))
}
210 changes: 4 additions & 206 deletions contract/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,11 @@
use model::{AccountRecord, ClaimAvailabilityView, Duration, SweatClaimInterface, TokensAmount, UnixTimestamp};
use model::{AccountRecord, Duration, InitApi, TokensAmount, UnixTimestamp};
use near_sdk::{
borsh::{self, BorshDeserialize, BorshSerialize},
env,
env::{log_str, panic_str},
ext_contract, is_promise_success,
json_types::U128,
near_bindgen, require,
serde_json::json,
near_bindgen,
store::{LookupMap, UnorderedMap, UnorderedSet, Vector},
AccountId, BorshStorageKey, Gas, PanicOnDefault, Promise, PromiseOrValue,
AccountId, BorshStorageKey, PanicOnDefault,
};

use crate::StorageKey::AccrualsEntry;

mod auth;
mod burn;
mod claim;
Expand Down Expand Up @@ -45,7 +38,7 @@ enum StorageKey {
}

#[near_bindgen]
impl SweatClaimInterface for Contract {
impl InitApi for Contract {
#[init]
#[private]
fn init(token_account_id: AccountId) -> Self {
Expand All @@ -62,209 +55,14 @@ impl SweatClaimInterface for Contract {
}

fn set_claim_period(&mut self, period: Duration) {
pub fn set_claim_period(&mut self, period: Duration) {
self.assert_oracle();

self.claim_period = period;
}

fn set_burn_period(&mut self, period: Duration) {
pub fn set_burn_period(&mut self, period: Duration) {
self.assert_oracle();

self.burn_period = period;
}

#[private]
fn add_oracle(&mut self, account_id: AccountId) {
require!(self.oracles.insert(account_id.clone()), "Already exists");
log_str(&format!("Oracle {account_id} was added"));
}

#[private]
fn remove_oracle(&mut self, account_id: AccountId) {
require!(self.oracles.remove(&account_id), "No such oracle");
log_str(&format!("Oracle {account_id} was removed"));
}

fn get_oracles(&self) -> Vec<AccountId> {
self.oracles.iter().cloned().collect()
}

fn record_batch_for_hold(&mut self, amounts: Vec<(AccountId, U128)>) {
log_str(&format!("Record batch: {amounts:?}"));

require!(
self.oracles.contains(&env::predecessor_account_id()),
"Unauthorized access! Only oracle can do this!"
);

let now_seconds = unix_timestamp(env::block_timestamp_ms());
let mut balances: Vector<TokensAmount> = Vector::new(AccrualsEntry(now_seconds));
let mut total_balance: TokensAmount = 0;

for (account_id, amount) in amounts {
log_str(&format!("Record {amount:?} for {account_id}"));

let amount = amount.0;

total_balance += amount;
balances.push(amount);
let index = balances.len() - 1;

if let Some(record) = self.accounts.get_mut(&account_id) {
record.accruals.push((now_seconds, index));
} else {
let record = AccountRecord {
last_claim_at: Some(now_seconds),
accruals: vec![(now_seconds, index)],
..Default::default()
};

self.accounts.insert(account_id, record);
}
}

self.accruals.insert(now_seconds, (balances, total_balance));
}

fn get_balance_for_account(&self, account_id: AccountId) -> U128 {
let account_data = self.accounts.get(&account_id).expect("Account data is not found");

let mut total_accrual: TokensAmount = 0;
let now = unix_timestamp(env::block_timestamp_ms());

for (datetime, index) in &account_data.accruals {
if now - datetime > self.burn_period {
continue;
}

if let Some((accruals, _)) = self.accruals.get(datetime) {
if let Some(amount) = accruals.get(*index) {
total_accrual += *amount;
}
}
}

U128(total_accrual)
}

fn is_claim_available(&self, account_id: AccountId) -> ClaimAvailabilityView {
let account_data = self.accounts.get(&account_id).expect("Account data is not found");

let Some(last_claim_at) = account_data.last_claim_at else {
return ClaimAvailabilityView::Available;
};

let now_seconds = unix_timestamp(env::block_timestamp_ms());

if now_seconds - last_claim_at > self.claim_period {
ClaimAvailabilityView::Available
} else {
ClaimAvailabilityView::Unavailable((last_claim_at, self.claim_period))
}
}

fn claim(&mut self) -> PromiseOrValue<()> {
let account_id = env::predecessor_account_id();

require!(
self.is_claim_available(account_id.clone()) == ClaimAvailabilityView::Available,
"Claim is not available at the moment"
);

let account_data = self.accounts.get_mut(&account_id).expect("Account data is not found");

let now = unix_timestamp(env::block_timestamp_ms());
let mut total_accrual: TokensAmount = 0;

for (datetime, index) in &account_data.accruals {
if now - datetime > self.burn_period {
continue;
}

if let Some((accruals, total)) = self.accruals.get_mut(datetime) {
if let Some(amount) = accruals.get_mut(*index) {
total_accrual += *amount;
*total -= *amount;
*amount = 0;
}
}
}

account_data.accruals.clear();
account_data.last_claim_at = Some(now);

let args = json!({
"receiver_id": account_id,
"amount": total_accrual.to_string(),
"memo": "",
})
.to_string()
.as_bytes()
.to_vec();

Promise::new(self.token_account_id.clone())
.function_call("ft_transfer".to_string(), args, 1, Gas(5 * Gas::ONE_TERA.0))
.into()
}

fn burn(&mut self) -> PromiseOrValue<U128> {
require!(
self.oracles.contains(&env::predecessor_account_id()),
"Unauthorized access"
);

let mut total_to_burn = 0;
let mut keys_to_remove: Vec<UnixTimestamp> = vec![];
let now = unix_timestamp(env::block_timestamp_ms());

for (datetime, (_, total)) in self.accruals.iter() {
if now - datetime >= self.burn_period {
keys_to_remove.push(*datetime);
total_to_burn += total;
}
}

let args = json!({
"amount": U128(total_to_burn),
})
.to_string()
.as_bytes()
.to_vec();

Promise::new(self.token_account_id.clone())
.function_call("burn".to_string(), args, 0, Gas(5 * Gas::ONE_TERA.0))
.then(
ext_self::ext(env::current_account_id())
.with_static_gas(Gas(5 * Gas::ONE_TERA.0))
.on_burn(total_to_burn, keys_to_remove),
)
.into()
}
}

#[ext_contract(ext_self)]
pub trait SelfCallback {
fn on_burn(&mut self, total_to_burn: TokensAmount, keys_to_remove: Vec<UnixTimestamp>) -> U128;
}

#[near_bindgen]
impl SelfCallback for Contract {
fn on_burn(&mut self, total_to_burn: TokensAmount, keys_to_remove: Vec<UnixTimestamp>) -> U128 {
if is_promise_success() {
for datetime in keys_to_remove {
self.accruals.remove(&datetime);
}

U128(total_to_burn)
} else {
U128(0)
}
}
}

fn unix_timestamp(ms: u64) -> UnixTimestamp {
u32::try_from(ms / 1000)
.unwrap_or_else(|err| panic_str(&format!("Failed to get convert milliseconds to Unix timestamp: {err}")))
}
9 changes: 4 additions & 5 deletions contract/src/record/api.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use crate::*;
use model::{AccountRecord, RecordApi, TokensAmount};
use near_sdk::{env, env::log_str, json_types::U128, near_bindgen, require, store::Vector, AccountId};

trait RecordApi {
fn record_batch_for_hold(&mut self, amounts: Vec<(AccountId, U128)>);
}
use crate::{common::unix_timestamp, Contract, ContractExt, StorageKey::AccrualsEntry};

#[near_bindgen]
impl RecordApi for Contract {
Expand All @@ -14,7 +13,7 @@ impl RecordApi for Contract {
"Unauthorized access! Only oracle can do this!"
);

let now_seconds: UnixTimestamp = (env::block_timestamp_ms() / 1_000) as u32;
let now_seconds = unix_timestamp(env::block_timestamp_ms());
let mut balances: Vector<TokensAmount> = Vector::new(AccrualsEntry(now_seconds));
let mut total_balance: TokensAmount = 0;

Expand Down
Loading

0 comments on commit 15a2503

Please sign in to comment.