2024-12-08 21:57:35 +03:00

109 lines
2.8 KiB
Plaintext

#pragma version ^0.4.1;
#include "../imports/stdlib.fc";
#include "../utils/Constants.fc";
#include "../utils/Math.fc";
#include "../utils/Security.fc";
;; Operation codes
const int op_stake = 1;
const int op_unstake = 2;
const int op_claim_rewards = 3;
const int op_update_rewards = 4;
const int op_emergency_withdraw = 5;
;; Error codes
const int error_insufficient_balance = 101;
const int error_no_stake_found = 102;
const int error_invalid_amount = 103;
const int error_lock_period_active = 104;
const int error_unauthorized = 105;
;; Constants
const int REWARD_PRECISION = 1000000000; ;; 9 decimals
const int MIN_STAKE_PERIOD = 86400; ;; 1 day in seconds
;; Storage variables
global slice owner;
global slice tfix_token;
global int total_staked;
global int reward_rate;
global int last_update_time;
global int rewards_per_token;
() load_data() impure {
slice ds = get_data().begin_parse();
owner = ds~load_msg_addr();
tfix_token = ds~load_msg_addr();
total_staked = ds~load_coins();
reward_rate = ds~load_uint(32);
last_update_time = ds~load_uint(64);
rewards_per_token = ds~load_uint(128);
}
() save_data() impure {
set_data(begin_cell()
.store_slice(owner)
.store_slice(tfix_token)
.store_coins(total_staked)
.store_uint(reward_rate, 32)
.store_uint(last_update_time, 64)
.store_uint(rewards_per_token, 128)
.end_cell());
}
() recv_internal(int msg_value, cell in_msg_full, slice in_msg_body) impure {
if (in_msg_body.slice_empty?()) { return (); }
slice cs = in_msg_full.begin_parse();
int flags = cs~load_uint(4);
if (flags & 1) { return (); }
slice sender = cs~load_msg_addr();
int op = in_msg_body~load_uint(32);
load_data();
if (op == op_stake) {
handle_stake(sender, msg_value);
} elseif (op == op_unstake) {
handle_unstake(sender, in_msg_body);
} elseif (op == op_claim_rewards) {
handle_claim_rewards(sender);
}
save_data();
}
() handle_stake(slice sender, int amount) impure {
throw_unless(error_invalid_amount, amount > 0);
total_staked += amount;
last_update_time = now();
}
() handle_unstake(slice sender, slice msg) impure {
int amount = msg~load_coins();
throw_unless(error_invalid_amount, amount > 0);
throw_unless(error_insufficient_balance, amount <= total_staked);
total_staked -= amount;
;; Send unstaked tokens using mode 3 (ignore errors, pay fees separately)
cell msg_body = begin_cell()
.store_uint(0x18, 6)
.store_slice(sender)
.store_coins(amount)
.store_uint(0, 107) ;; 1 + 4 + 4 + 64 + 32 + 1 + 1
.end_cell();
send_raw_message(msg_body, 3);
}
;; Get methods
int get_total_staked() method_id {
return total_staked;
}
int get_reward_rate() method_id {
return reward_rate;
}