mirror of
https://github.com/serai-dex/serai.git
synced 2025-12-12 14:09:25 +00:00
Compare commits
8 Commits
rocksdb-sn
...
1cd9868433
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1cd9868433 | ||
|
|
8be0538eba | ||
|
|
c32040240c | ||
|
|
207f2bd28a | ||
|
|
2b32fe90ca | ||
|
|
b9df73e418 | ||
|
|
da51543588 | ||
|
|
c1bcb0f6c7 |
49
Cargo.lock
generated
49
Cargo.lock
generated
@@ -7487,6 +7487,30 @@ dependencies = [
|
||||
"chrono",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serai-emissions-pallet"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"frame-support",
|
||||
"frame-system",
|
||||
"pallet-babe",
|
||||
"parity-scale-codec",
|
||||
"scale-info",
|
||||
"serai-coins-pallet",
|
||||
"serai-dex-pallet",
|
||||
"serai-emissions-primitives",
|
||||
"serai-primitives",
|
||||
"serai-validator-sets-pallet",
|
||||
"serai-validator-sets-primitives",
|
||||
"sp-runtime",
|
||||
"sp-session",
|
||||
"sp-std",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serai-emissions-primitives"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "serai-env"
|
||||
version = "0.1.0"
|
||||
@@ -7515,6 +7539,28 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serai-genesis-liquidity-pallet"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"frame-support",
|
||||
"frame-system",
|
||||
"parity-scale-codec",
|
||||
"scale-info",
|
||||
"serai-coins-pallet",
|
||||
"serai-dex-pallet",
|
||||
"serai-genesis-liquidity-primitives",
|
||||
"serai-primitives",
|
||||
"sp-std",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serai-genesis-liquidity-primitives"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serai-primitives",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serai-in-instructions-pallet"
|
||||
version = "0.1.0"
|
||||
@@ -7525,6 +7571,7 @@ dependencies = [
|
||||
"scale-info",
|
||||
"serai-coins-pallet",
|
||||
"serai-dex-pallet",
|
||||
"serai-genesis-liquidity-pallet",
|
||||
"serai-in-instructions-primitives",
|
||||
"serai-primitives",
|
||||
"serai-validator-sets-pallet",
|
||||
@@ -7786,6 +7833,8 @@ dependencies = [
|
||||
"scale-info",
|
||||
"serai-coins-pallet",
|
||||
"serai-dex-pallet",
|
||||
"serai-emissions-pallet",
|
||||
"serai-genesis-liquidity-pallet",
|
||||
"serai-in-instructions-pallet",
|
||||
"serai-primitives",
|
||||
"serai-signals-pallet",
|
||||
|
||||
@@ -1,40 +1,33 @@
|
||||
use std::{sync::Arc, collections::HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use rocksdb::{
|
||||
DBCompressionType, ThreadMode, SingleThreaded, LogLevel, WriteOptions,
|
||||
Transaction as RocksTransaction, Options, OptimisticTransactionDB, SnapshotWithThreadMode,
|
||||
Transaction as RocksTransaction, Options, OptimisticTransactionDB,
|
||||
};
|
||||
|
||||
use crate::*;
|
||||
|
||||
pub struct Transaction<'a, T: ThreadMode> {
|
||||
dirtied_keys: HashSet<Vec<u8>>,
|
||||
txn: RocksTransaction<'a, OptimisticTransactionDB<T>>,
|
||||
snapshot: SnapshotWithThreadMode<'a, OptimisticTransactionDB<T>>,
|
||||
db: &'a OptimisticTransactionDB<T>,
|
||||
}
|
||||
pub struct Transaction<'a, T: ThreadMode>(
|
||||
RocksTransaction<'a, OptimisticTransactionDB<T>>,
|
||||
&'a OptimisticTransactionDB<T>,
|
||||
);
|
||||
|
||||
impl<T: ThreadMode> Get for Transaction<'_, T> {
|
||||
fn get(&self, key: impl AsRef<[u8]>) -> Option<Vec<u8>> {
|
||||
if self.dirtied_keys.contains(key.as_ref()) {
|
||||
return self.txn.get(key).expect("couldn't read from RocksDB via transaction");
|
||||
}
|
||||
self.snapshot.get(key).expect("couldn't read from RocksDB via snapshot")
|
||||
self.0.get(key).expect("couldn't read from RocksDB via transaction")
|
||||
}
|
||||
}
|
||||
impl<T: ThreadMode> DbTxn for Transaction<'_, T> {
|
||||
fn put(&mut self, key: impl AsRef<[u8]>, value: impl AsRef<[u8]>) {
|
||||
self.dirtied_keys.insert(key.as_ref().to_vec());
|
||||
self.txn.put(key, value).expect("couldn't write to RocksDB via transaction")
|
||||
self.0.put(key, value).expect("couldn't write to RocksDB via transaction")
|
||||
}
|
||||
fn del(&mut self, key: impl AsRef<[u8]>) {
|
||||
self.dirtied_keys.insert(key.as_ref().to_vec());
|
||||
self.txn.delete(key).expect("couldn't delete from RocksDB via transaction")
|
||||
self.0.delete(key).expect("couldn't delete from RocksDB via transaction")
|
||||
}
|
||||
fn commit(self) {
|
||||
self.txn.commit().expect("couldn't commit to RocksDB via transaction");
|
||||
self.db.flush_wal(true).expect("couldn't flush RocksDB WAL");
|
||||
self.db.flush().expect("couldn't flush RocksDB");
|
||||
self.0.commit().expect("couldn't commit to RocksDB via transaction");
|
||||
self.1.flush_wal(true).expect("couldn't flush RocksDB WAL");
|
||||
self.1.flush().expect("couldn't flush RocksDB");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,12 +41,7 @@ impl<T: Send + ThreadMode + 'static> Db for Arc<OptimisticTransactionDB<T>> {
|
||||
fn txn(&mut self) -> Self::Transaction<'_> {
|
||||
let mut opts = WriteOptions::default();
|
||||
opts.set_sync(true);
|
||||
Transaction {
|
||||
dirtied_keys: HashSet::new(),
|
||||
txn: self.transaction_opt(&opts, &Default::default()),
|
||||
snapshot: self.snapshot(),
|
||||
db: &**self,
|
||||
}
|
||||
Transaction(self.transaction_opt(&opts, &Default::default()), &**self)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -55,6 +55,8 @@ exceptions = [
|
||||
|
||||
{ allow = ["AGPL-3.0"], name = "serai-coins-pallet" },
|
||||
{ allow = ["AGPL-3.0"], name = "serai-dex-pallet" },
|
||||
|
||||
{ allow = ["AGPL-3.0"], name = "serai-genesis-liquidity-pallet" },
|
||||
|
||||
{ allow = ["AGPL-3.0"], name = "serai-in-instructions-pallet" },
|
||||
|
||||
|
||||
14
substrate/abi/src/emissions.rs
Normal file
14
substrate/abi/src/emissions.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
#[derive(Clone, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum Call {
|
||||
// This call is just a place holder so that abi works as expected.
|
||||
empty_call,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum Event {
|
||||
empty_event,
|
||||
}
|
||||
19
substrate/abi/src/genesis_liquidity.rs
Normal file
19
substrate/abi/src/genesis_liquidity.rs
Normal file
@@ -0,0 +1,19 @@
|
||||
use serai_primitives::*;
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum Call {
|
||||
// This call is just a place holder so that abi works as expected.
|
||||
empty_call,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, scale::Encode, scale::Decode, scale_info::TypeInfo)]
|
||||
#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum Event {
|
||||
GenesisLiquidityAdded { by: SeraiAddress, balance: Balance },
|
||||
GenesisLiquidityRemoved { by: SeraiAddress, balance: Balance },
|
||||
GenesisLiquidityAddedToPool { coin1: Balance, coin2: Balance },
|
||||
EconomicSecurityReached { network: NetworkId },
|
||||
}
|
||||
@@ -11,6 +11,9 @@ pub mod validator_sets;
|
||||
pub mod in_instructions;
|
||||
pub mod signals;
|
||||
|
||||
pub mod genesis_liquidity;
|
||||
pub mod emissions;
|
||||
|
||||
pub mod babe;
|
||||
pub mod grandpa;
|
||||
|
||||
@@ -25,6 +28,8 @@ pub enum Call {
|
||||
LiquidityTokens(coins::Call),
|
||||
Dex(dex::Call),
|
||||
ValidatorSets(validator_sets::Call),
|
||||
GenesisLiquidity(genesis_liquidity::Call),
|
||||
Emissions(emissions::Call),
|
||||
InInstructions(in_instructions::Call),
|
||||
Signals(signals::Call),
|
||||
Babe(babe::Call),
|
||||
@@ -46,6 +51,8 @@ pub enum Event {
|
||||
LiquidityTokens(coins::Event),
|
||||
Dex(dex::Event),
|
||||
ValidatorSets(validator_sets::Event),
|
||||
GenesisLiquidity(genesis_liquidity::Event),
|
||||
Emissions(emissions::Event),
|
||||
InInstructions(in_instructions::Event),
|
||||
Signals(signals::Event),
|
||||
Babe,
|
||||
|
||||
@@ -194,6 +194,11 @@ pub mod pallet {
|
||||
#[pallet::getter(fn security_oracle_value)]
|
||||
pub type SecurityOracleValue<T: Config> = StorageMap<_, Identity, Coin, Amount, OptionQuery>;
|
||||
|
||||
/// Current length of the `SpotPrices` map.
|
||||
#[pallet::storage]
|
||||
#[pallet::getter(fn swap_volume)]
|
||||
pub type SwapVolume<T: Config> = StorageMap<_, Identity, Coin, u64, OptionQuery>;
|
||||
|
||||
impl<T: Config> Pallet<T> {
|
||||
fn restore_median(
|
||||
coin: Coin,
|
||||
@@ -890,6 +895,20 @@ pub mod pallet {
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
|
||||
// update the volume, SRI amount is always at index 1 if the path len is 2 or 3.
|
||||
// path len 1 is not allowed and 3 is already the maximum.
|
||||
let swap_volume = amounts.get(1).ok_or(Error::<T>::CorrespondenceError)?;
|
||||
let existing = SwapVolume::<T>::get(coin1).unwrap_or(0);
|
||||
let new_volume = existing.saturating_add(*swap_volume);
|
||||
SwapVolume::<T>::set(coin1, Some(new_volume));
|
||||
|
||||
// if we did 2 pools, update the volume for second coin as well.
|
||||
if u32::try_from(path.len()).unwrap() == T::MaxSwapPathLength::get() {
|
||||
let existing = SwapVolume::<T>::get(path.last().unwrap()).unwrap_or(0);
|
||||
let new_volume = existing.saturating_add(*swap_volume);
|
||||
SwapVolume::<T>::set(path.last().unwrap(), Some(new_volume));
|
||||
}
|
||||
Self::deposit_event(Event::SwapExecuted {
|
||||
who: sender,
|
||||
send_to,
|
||||
|
||||
65
substrate/emissions/pallet/Cargo.toml
Normal file
65
substrate/emissions/pallet/Cargo.toml
Normal file
@@ -0,0 +1,65 @@
|
||||
[package]
|
||||
name = "serai-emissions-pallet"
|
||||
version = "0.1.0"
|
||||
description = "Emissions pallet for Serai"
|
||||
license = "AGPL-3.0-only"
|
||||
repository = "https://github.com/serai-dex/serai/tree/develop/substrate/emissions/pallet"
|
||||
authors = ["Akil Demir <aeg_asd@hotmail.com>"]
|
||||
edition = "2021"
|
||||
rust-version = "1.77"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[package.metadata.cargo-machete]
|
||||
ignored = ["scale", "scale-info"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
|
||||
[dependencies]
|
||||
scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] }
|
||||
scale-info = { version = "2", default-features = false, features = ["derive"] }
|
||||
|
||||
frame-system = { git = "https://github.com/serai-dex/substrate", default-features = false }
|
||||
frame-support = { git = "https://github.com/serai-dex/substrate", default-features = false }
|
||||
|
||||
sp-std = { git = "https://github.com/serai-dex/substrate", default-features = false }
|
||||
sp-session = { git = "https://github.com/serai-dex/substrate", default-features = false }
|
||||
sp-runtime = { git = "https://github.com/serai-dex/substrate", default-features = false }
|
||||
|
||||
pallet-babe = { git = "https://github.com/serai-dex/substrate", default-features = false }
|
||||
|
||||
coins-pallet = { package = "serai-coins-pallet", path = "../../coins/pallet", default-features = false }
|
||||
validator-sets-pallet = { package = "serai-validator-sets-pallet", path = "../../validator-sets/pallet", default-features = false }
|
||||
dex-pallet = { package = "serai-dex-pallet", path = "../../dex/pallet", default-features = false }
|
||||
|
||||
serai-primitives = { path = "../../primitives", default-features = false }
|
||||
serai-validator-sets-primitives = { path = "../../validator-sets/primitives", default-features = false }
|
||||
emissions-primitives = { package = "serai-emissions-primitives", path = "../primitives", default-features = false }
|
||||
|
||||
[features]
|
||||
std = [
|
||||
"scale/std",
|
||||
"scale-info/std",
|
||||
|
||||
"frame-system/std",
|
||||
"frame-support/std",
|
||||
|
||||
"sp-std/std",
|
||||
"sp-session/std",
|
||||
"sp-runtime/std",
|
||||
|
||||
"pallet-babe/std",
|
||||
|
||||
"coins-pallet/std",
|
||||
"validator-sets-pallet/std",
|
||||
"dex-pallet/std",
|
||||
|
||||
"serai-primitives/std",
|
||||
"emissions-primitives/std",
|
||||
]
|
||||
|
||||
default = ["std"]
|
||||
15
substrate/emissions/pallet/LICENSE
Normal file
15
substrate/emissions/pallet/LICENSE
Normal file
@@ -0,0 +1,15 @@
|
||||
AGPL-3.0-only license
|
||||
|
||||
Copyright (c) 2024 Luke Parker
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License Version 3 as
|
||||
published by the Free Software Foundation.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
306
substrate/emissions/pallet/src/lib.rs
Normal file
306
substrate/emissions/pallet/src/lib.rs
Normal file
@@ -0,0 +1,306 @@
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
#[allow(clippy::cast_possible_truncation, clippy::no_effect_underscore_binding)]
|
||||
#[frame_support::pallet]
|
||||
pub mod pallet {
|
||||
use super::*;
|
||||
use frame_system::pallet_prelude::*;
|
||||
use frame_support::{pallet_prelude::*, sp_runtime::SaturatedConversion};
|
||||
|
||||
use sp_std::{vec, vec::Vec, collections::btree_map::BTreeMap};
|
||||
use sp_session::ShouldEndSession;
|
||||
use sp_runtime;
|
||||
|
||||
use coins_pallet::{Config as CoinsConfig, Pallet as Coins, AllowMint};
|
||||
use dex_pallet::{Config as DexConfig, Pallet as Dex};
|
||||
|
||||
use validator_sets_pallet::{Pallet as ValidatorSets, Config as ValidatorSetsConfig};
|
||||
use pallet_babe::{Pallet as Babe, Config as BabeConfig};
|
||||
|
||||
use serai_primitives::{NetworkId, NETWORKS, *};
|
||||
use serai_validator_sets_primitives::MAX_KEY_SHARES_PER_SET;
|
||||
use emissions_primitives::*;
|
||||
|
||||
#[pallet::config]
|
||||
pub trait Config:
|
||||
frame_system::Config<AccountId = PublicKey>
|
||||
+ ValidatorSetsConfig
|
||||
+ BabeConfig
|
||||
+ CoinsConfig
|
||||
+ DexConfig
|
||||
{
|
||||
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
|
||||
}
|
||||
|
||||
#[pallet::genesis_config]
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode)]
|
||||
pub struct GenesisConfig<T: Config> {
|
||||
/// Networks to spawn Serai with.
|
||||
pub networks: Vec<NetworkId>,
|
||||
/// List of participants to place in the initial validator sets.
|
||||
pub participants: Vec<T::AccountId>,
|
||||
}
|
||||
|
||||
impl<T: Config> Default for GenesisConfig<T> {
|
||||
fn default() -> Self {
|
||||
GenesisConfig { networks: Default::default(), participants: Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
#[pallet::error]
|
||||
pub enum Error<T> {
|
||||
GenesisPeriodEnded,
|
||||
AmountOverflowed,
|
||||
NotEnoughLiquidity,
|
||||
CanOnlyRemoveFullAmount,
|
||||
}
|
||||
|
||||
#[pallet::event]
|
||||
pub enum Event<T: Config> {}
|
||||
|
||||
#[pallet::pallet]
|
||||
pub struct Pallet<T>(PhantomData<T>);
|
||||
|
||||
#[pallet::storage]
|
||||
#[pallet::getter(fn participants)]
|
||||
pub(crate) type Participants<T: Config> = StorageMap<
|
||||
_,
|
||||
Identity,
|
||||
NetworkId,
|
||||
BoundedVec<(PublicKey, u64), ConstU32<{ MAX_KEY_SHARES_PER_SET }>>,
|
||||
OptionQuery,
|
||||
>;
|
||||
|
||||
#[pallet::storage]
|
||||
#[pallet::getter(fn epoch_begin_block)]
|
||||
pub(crate) type EpochBeginBlock<T: Config> = StorageMap<_, Identity, u64, u64, ValueQuery>;
|
||||
|
||||
#[pallet::storage]
|
||||
#[pallet::getter(fn economic_security_reached)]
|
||||
pub(crate) type EconomicSecurityReached<T: Config> =
|
||||
StorageMap<_, Identity, NetworkId, BlockNumberFor<T>, ValueQuery>;
|
||||
|
||||
#[pallet::storage]
|
||||
#[pallet::getter(fn last_swap_volume)]
|
||||
pub(crate) type LastSwapVolume<T: Config> = StorageMap<_, Identity, NetworkId, u64, OptionQuery>;
|
||||
|
||||
#[pallet::genesis_build]
|
||||
impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
|
||||
fn build(&self) {
|
||||
for id in self.networks.clone() {
|
||||
let mut participants = vec![];
|
||||
for p in self.participants.clone() {
|
||||
participants.push((p, 0u64));
|
||||
}
|
||||
Participants::<T>::set(id, Some(participants.try_into().unwrap()));
|
||||
}
|
||||
|
||||
EpochBeginBlock::<T>::set(0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[pallet::hooks]
|
||||
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
|
||||
/// Since we are on `on_finalize`, session should have already rotated.
|
||||
/// We can distribute the rewards for the last set.
|
||||
fn on_finalize(n: BlockNumberFor<T>) {
|
||||
// we accept we reached economic security once we can mint smallest amount of a network's coin
|
||||
for coin in COINS {
|
||||
let existing = EconomicSecurityReached::<T>::get(coin.network());
|
||||
if existing == 0u32.into() &&
|
||||
<T as CoinsConfig>::AllowMint::is_allowed(&Balance { coin, amount: Amount(1) })
|
||||
{
|
||||
EconomicSecurityReached::<T>::set(coin.network(), n);
|
||||
}
|
||||
}
|
||||
|
||||
// emissions start only after genesis period and happens once per epoch
|
||||
// so we don't do anything before that time.
|
||||
if !(n >= BLOCKS_PER_MONTH.into() && T::ShouldEndSession::should_end_session(n)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// figure out the amount of blocks in the last epoch
|
||||
// TODO: we use epoch index here but should we use SessionIndex since this is how we decide
|
||||
// whether time to distribute the rewards or not? Because apparently epochs != Sessions
|
||||
// since we can skip some epochs if the chain is offline more than epoch duration??
|
||||
let epoch = Babe::<T>::current_epoch().epoch_index - 1;
|
||||
let block_count = n.saturated_into::<u64>() - Self::epoch_begin_block(epoch);
|
||||
|
||||
// get total reward for this epoch
|
||||
let pre_ec_security = Self::pre_ec_security();
|
||||
let mut distances = BTreeMap::new();
|
||||
let mut total_distance: u64 = 0;
|
||||
let reward_this_epoch = if Self::initial_period(n) {
|
||||
// rewards are fixed for initial period
|
||||
block_count * INITIAL_REWARD_PER_BLOCK
|
||||
} else if pre_ec_security {
|
||||
// calculate distance to economic security per network
|
||||
let mut total_required: u64 = 0;
|
||||
let mut total_current: u64 = 0;
|
||||
for n in NETWORKS {
|
||||
if n == NetworkId::Serai {
|
||||
continue;
|
||||
}
|
||||
|
||||
let required = ValidatorSets::<T>::required_stake_for_network(n);
|
||||
let mut current = ValidatorSets::<T>::total_allocated_stake(n).unwrap_or(Amount(0)).0;
|
||||
if current > required {
|
||||
current = required;
|
||||
}
|
||||
|
||||
distances.insert(n, required - current);
|
||||
total_required = total_required.saturating_add(required);
|
||||
total_current = total_current.saturating_add(current);
|
||||
}
|
||||
total_distance = total_required.saturating_sub(total_current);
|
||||
|
||||
// add serai network portion(20%)
|
||||
let new_total_distance =
|
||||
total_distance.saturating_mul(10) / (10 - SERAI_VALIDATORS_DESIRED_PERCENTAGE);
|
||||
distances.insert(NetworkId::Serai, new_total_distance - total_distance);
|
||||
total_distance = new_total_distance;
|
||||
|
||||
// rewards for pre-economic security is
|
||||
// (STAKE_REQUIRED - CURRENT_STAKE) / blocks_until(SECURE_BY).
|
||||
let block_reward = total_distance / Self::blocks_until(SECURE_BY);
|
||||
block_count * block_reward
|
||||
} else {
|
||||
// post ec security
|
||||
block_count * REWARD_PER_BLOCK
|
||||
};
|
||||
|
||||
// get swap volumes
|
||||
let mut volume_per_network: BTreeMap<NetworkId, u64> = BTreeMap::new();
|
||||
for c in COINS {
|
||||
// this should return 0 for SRI and so it shouldn't affect the total volume.
|
||||
let current_volume = Dex::<T>::swap_volume(c).unwrap_or(0);
|
||||
volume_per_network.insert(
|
||||
c.network(),
|
||||
(*volume_per_network.get(&c.network()).unwrap_or(&0)).saturating_add(current_volume),
|
||||
);
|
||||
}
|
||||
|
||||
// map current volumes to epoch volumes
|
||||
let mut total_volume = 0u64;
|
||||
for (n, vol) in &mut volume_per_network {
|
||||
let last_volume = Self::last_swap_volume(n).unwrap_or(0);
|
||||
let vol_this_epoch = vol.saturating_sub(last_volume);
|
||||
|
||||
// update the current volume
|
||||
LastSwapVolume::<T>::set(n, Some(*vol));
|
||||
|
||||
total_volume = total_volume.saturating_add(vol_this_epoch);
|
||||
*vol = vol_this_epoch;
|
||||
}
|
||||
|
||||
// map epoch ec-security-distance/volume to rewards
|
||||
let rewards_per_network = distances
|
||||
.into_iter()
|
||||
.map(|(n, distance)| {
|
||||
let reward = if pre_ec_security {
|
||||
// calculate how much each network gets based on distance to ec-security
|
||||
reward_this_epoch.saturating_mul(distance) / total_distance
|
||||
} else {
|
||||
// 20% of the reward goes to the Serai network and rest is distributed among others
|
||||
// based on swap-volume.
|
||||
if n == NetworkId::Serai {
|
||||
reward_this_epoch / 5
|
||||
} else {
|
||||
let reward = reward_this_epoch - (reward_this_epoch / 5);
|
||||
reward.saturating_mul(*volume_per_network.get(&n).unwrap_or(&0)) / total_volume
|
||||
}
|
||||
};
|
||||
(n, reward)
|
||||
})
|
||||
.collect::<BTreeMap<NetworkId, u64>>();
|
||||
|
||||
// distribute the rewards within the network
|
||||
for (n, reward) in rewards_per_network {
|
||||
// calculate pool vs validator share
|
||||
let capacity = ValidatorSets::<T>::total_allocated_stake(n).unwrap_or(Amount(0)).0;
|
||||
let required = ValidatorSets::<T>::required_stake_for_network(n);
|
||||
let unused_capacity = capacity.saturating_sub(required);
|
||||
|
||||
let distribution = unused_capacity.saturating_mul(ACCURACY_MULTIPLIER) / capacity;
|
||||
let total = DESIRED_DISTRIBUTION.saturating_add(distribution);
|
||||
|
||||
let validators_reward = DESIRED_DISTRIBUTION.saturating_mul(reward) / total;
|
||||
let pool_reward = total - validators_reward;
|
||||
|
||||
// distribute validators rewards
|
||||
Self::distribute_to_validators(n, validators_reward);
|
||||
|
||||
// send the rest to the pool
|
||||
let coin_count = u64::try_from(n.coins().len()).unwrap();
|
||||
for c in n.coins() {
|
||||
// TODO: we just print a warning here instead of unwrap?
|
||||
// assumes reward is equally distributed between network coins.
|
||||
Coins::<T>::mint(
|
||||
Dex::<T>::get_pool_account(*c),
|
||||
Balance { coin: Coin::Serai, amount: Amount(pool_reward / coin_count) },
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
// set the begin block and participants
|
||||
EpochBeginBlock::<T>::set(epoch, n.saturated_into::<u64>());
|
||||
for n in NETWORKS {
|
||||
// TODO: `participants_for_latest_decided_set` returns keys with key shares but we
|
||||
// store keys with actual stake amounts. Pr https://github.com/serai-dex/serai/pull/518
|
||||
// supposed to change that and so this pr relies and that pr.
|
||||
Participants::<T>::set(n, ValidatorSets::<T>::participants_for_latest_decided_set(n));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Config> Pallet<T> {
|
||||
fn blocks_until(block: u64) -> u64 {
|
||||
let current = <frame_system::Pallet<T>>::block_number().saturated_into::<u64>();
|
||||
block.saturating_sub(current)
|
||||
}
|
||||
|
||||
fn initial_period(n: BlockNumberFor<T>) -> bool {
|
||||
n >= BLOCKS_PER_MONTH.into() && n < (3 * BLOCKS_PER_MONTH).into()
|
||||
}
|
||||
|
||||
/// Returns true if any of the external networks haven't reached economic security yet.
|
||||
fn pre_ec_security() -> bool {
|
||||
for n in NETWORKS {
|
||||
if n == NetworkId::Serai {
|
||||
continue;
|
||||
}
|
||||
|
||||
if Self::economic_security_reached(n) == 0u32.into() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn distribute_to_validators(n: NetworkId, reward: u64) {
|
||||
// distribute among network's set based on
|
||||
// -> (key shares * stake per share) + ((stake % stake per share) / 2)
|
||||
let stake_per_share = ValidatorSets::<T>::allocation_per_key_share(n).unwrap().0;
|
||||
let mut scores = vec![];
|
||||
let mut total_score = 0u64;
|
||||
for (p, amount) in Self::participants(n).unwrap() {
|
||||
let remainder = amount % stake_per_share;
|
||||
let score = (amount - remainder) + (remainder / 2);
|
||||
|
||||
total_score = total_score.saturating_add(score);
|
||||
scores.push((p, score));
|
||||
}
|
||||
|
||||
// stake the rewards
|
||||
for (p, score) in scores {
|
||||
let p_reward = reward.saturating_mul(score) / total_score;
|
||||
// TODO: print a warning here?
|
||||
let _ = ValidatorSets::<T>::deposit_stake(n, p, Amount(p_reward));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub use pallet::*;
|
||||
22
substrate/emissions/primitives/Cargo.toml
Normal file
22
substrate/emissions/primitives/Cargo.toml
Normal file
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "serai-emissions-primitives"
|
||||
version = "0.1.0"
|
||||
description = "Serai emissions primitives"
|
||||
license = "MIT"
|
||||
repository = "https://github.com/serai-dex/serai/tree/develop/substrate/emissions/primitives"
|
||||
authors = ["Akil Demir <aeg_asd@hotmail.com>"]
|
||||
edition = "2021"
|
||||
rust-version = "1.77"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
|
||||
[features]
|
||||
std = []
|
||||
default = ["std"]
|
||||
21
substrate/emissions/primitives/LICENSE
Normal file
21
substrate/emissions/primitives/LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Luke Parker
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
24
substrate/emissions/primitives/src/lib.rs
Normal file
24
substrate/emissions/primitives/src/lib.rs
Normal file
@@ -0,0 +1,24 @@
|
||||
#![cfg_attr(docsrs, feature(doc_cfg))]
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
/// Amount of blocks in 30 days for 6s per block.
|
||||
pub const BLOCKS_PER_MONTH: u32 = 10 * 60 * 24 * 30;
|
||||
|
||||
/// INITIAL_REWARD = 100,000 SRI / BLOCKS_PER_DAY for 60 days
|
||||
pub const INITIAL_REWARD_PER_BLOCK: u64 = 100_000 * 10u64.pow(8) / ((BLOCKS_PER_MONTH as u64) / 30);
|
||||
|
||||
/// REWARD = 20M SRI / BLOCKS_PER_YEAR
|
||||
pub const REWARD_PER_BLOCK: u64 = 20_000_000 * 10u64.pow(8) / ((BLOCKS_PER_MONTH as u64) * 12);
|
||||
|
||||
/// 20% of all stake desired to be for Serai network(2/10)
|
||||
pub const SERAI_VALIDATORS_DESIRED_PERCENTAGE: u64 = 2;
|
||||
|
||||
/// Desired unused capacity ratio for a network assuming capacity is 10,000.
|
||||
pub const DESIRED_DISTRIBUTION: u64 = 1_000;
|
||||
|
||||
/// Percentage scale for the validator vs. pool reward distribution.
|
||||
pub const ACCURACY_MULTIPLIER: u64 = 10_000;
|
||||
|
||||
/// The block to target for economic security
|
||||
pub const SECURE_BY: u64 = (BLOCKS_PER_MONTH as u64) * 12;
|
||||
54
substrate/genesis-liquidity/pallet/Cargo.toml
Normal file
54
substrate/genesis-liquidity/pallet/Cargo.toml
Normal file
@@ -0,0 +1,54 @@
|
||||
[package]
|
||||
name = "serai-genesis-liquidity-pallet"
|
||||
version = "0.1.0"
|
||||
description = "Genesis liquidity pallet for Serai"
|
||||
license = "AGPL-3.0-only"
|
||||
repository = "https://github.com/serai-dex/serai/tree/develop/substrate/genesis-liquidity/pallet"
|
||||
authors = ["Akil Demir <aeg_asd@hotmail.com>"]
|
||||
edition = "2021"
|
||||
rust-version = "1.77"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[package.metadata.cargo-machete]
|
||||
ignored = ["scale", "scale-info"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
|
||||
[dependencies]
|
||||
scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] }
|
||||
scale-info = { version = "2", default-features = false, features = ["derive"] }
|
||||
|
||||
frame-system = { git = "https://github.com/serai-dex/substrate", default-features = false }
|
||||
frame-support = { git = "https://github.com/serai-dex/substrate", default-features = false }
|
||||
|
||||
sp-std = { git = "https://github.com/serai-dex/substrate", default-features = false }
|
||||
|
||||
dex-pallet = { package = "serai-dex-pallet", path = "../../dex/pallet", default-features = false }
|
||||
coins-pallet = { package = "serai-coins-pallet", path = "../../coins/pallet", default-features = false }
|
||||
|
||||
serai-primitives = { path = "../../primitives", default-features = false }
|
||||
genesis-liquidity-primitives = { package = "serai-genesis-liquidity-primitives", path = "../primitives", default-features = false }
|
||||
|
||||
[features]
|
||||
std = [
|
||||
"scale/std",
|
||||
"scale-info/std",
|
||||
|
||||
"frame-system/std",
|
||||
"frame-support/std",
|
||||
|
||||
"sp-std/std",
|
||||
|
||||
"coins-pallet/std",
|
||||
"dex-pallet/std",
|
||||
|
||||
"serai-primitives/std",
|
||||
"genesis-liquidity-primitives/std",
|
||||
]
|
||||
|
||||
default = ["std"]
|
||||
15
substrate/genesis-liquidity/pallet/LICENSE
Normal file
15
substrate/genesis-liquidity/pallet/LICENSE
Normal file
@@ -0,0 +1,15 @@
|
||||
AGPL-3.0-only license
|
||||
|
||||
Copyright (c) 2024 Luke Parker
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License Version 3 as
|
||||
published by the Free Software Foundation.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
276
substrate/genesis-liquidity/pallet/src/lib.rs
Normal file
276
substrate/genesis-liquidity/pallet/src/lib.rs
Normal file
@@ -0,0 +1,276 @@
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
#[allow(clippy::cast_possible_truncation, clippy::no_effect_underscore_binding)]
|
||||
#[frame_support::pallet]
|
||||
pub mod pallet {
|
||||
use super::*;
|
||||
use frame_system::{pallet_prelude::*, RawOrigin};
|
||||
use frame_support::{pallet_prelude::*, sp_runtime::SaturatedConversion};
|
||||
|
||||
use sp_std::{vec, collections::btree_map::BTreeMap};
|
||||
|
||||
use dex_pallet::{Pallet as Dex, Config as DexConfig};
|
||||
use coins_pallet::{
|
||||
primitives::{OutInstructionWithBalance, OutInstruction},
|
||||
Config as CoinsConfig, Pallet as Coins, AllowMint,
|
||||
};
|
||||
|
||||
use serai_primitives::*;
|
||||
pub use genesis_liquidity_primitives as primitives;
|
||||
use primitives::*;
|
||||
|
||||
/// LiquidityTokens Pallet as an instance of coins pallet.
|
||||
pub type LiquidityTokens<T> = coins_pallet::Pallet<T, coins_pallet::Instance1>;
|
||||
|
||||
#[pallet::config]
|
||||
pub trait Config:
|
||||
frame_system::Config + DexConfig + CoinsConfig + coins_pallet::Config<coins_pallet::Instance1>
|
||||
{
|
||||
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
|
||||
}
|
||||
|
||||
#[pallet::error]
|
||||
pub enum Error<T> {
|
||||
GenesisPeriodEnded,
|
||||
AmountOverflowed,
|
||||
NotEnoughLiquidity,
|
||||
CanOnlyRemoveFullAmount,
|
||||
}
|
||||
|
||||
#[pallet::event]
|
||||
#[pallet::generate_deposit(fn deposit_event)]
|
||||
pub enum Event<T: Config> {
|
||||
GenesisLiquidityAdded { by: SeraiAddress, balance: Balance },
|
||||
GenesisLiquidityRemoved { by: SeraiAddress, balance: Balance },
|
||||
GenesisLiquidityAddedToPool { coin1: Balance, coin2: Balance },
|
||||
EconomicSecurityReached { network: NetworkId },
|
||||
}
|
||||
|
||||
#[pallet::pallet]
|
||||
pub struct Pallet<T>(PhantomData<T>);
|
||||
|
||||
#[pallet::storage]
|
||||
pub(crate) type Liquidity<T: Config> =
|
||||
StorageDoubleMap<_, Identity, Coin, Blake2_128Concat, PublicKey, SubstrateAmount, OptionQuery>;
|
||||
|
||||
#[pallet::storage]
|
||||
pub(crate) type LiquidityTokensPerAddress<T: Config> =
|
||||
StorageDoubleMap<_, Identity, Coin, Blake2_128Concat, PublicKey, SubstrateAmount, OptionQuery>;
|
||||
|
||||
#[pallet::storage]
|
||||
pub(crate) type EconomicSecurityReached<T: Config> =
|
||||
StorageMap<_, Identity, NetworkId, BlockNumberFor<T>, ValueQuery>;
|
||||
|
||||
#[pallet::hooks]
|
||||
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
|
||||
fn on_finalize(n: BlockNumberFor<T>) {
|
||||
// Distribute the genesis sri to pools after a month
|
||||
if n == BLOCKS_PER_MONTH.into() {
|
||||
// mint the SRI
|
||||
Coins::<T>::mint(
|
||||
GENESIS_LIQUIDITY_ACCOUNT.into(),
|
||||
Balance { coin: Coin::Serai, amount: Amount(GENESIS_SRI) },
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// get coin values & total
|
||||
let mut account_values = BTreeMap::new();
|
||||
let mut pool_values = BTreeMap::new();
|
||||
let mut total_value: u64 = 0;
|
||||
for coin in COINS {
|
||||
// TODO: following line is just a place holder till we get the actual coin value
|
||||
// in terms of btc.
|
||||
let value = Dex::<T>::security_oracle_value(coin).unwrap_or(Amount(0)).0;
|
||||
account_values.insert(coin, vec![]);
|
||||
let mut pool_amount: u64 = 0;
|
||||
for (account, amount) in Liquidity::<T>::iter_prefix(coin) {
|
||||
pool_amount = pool_amount.saturating_add(amount);
|
||||
let value_this_addr = amount.saturating_mul(value);
|
||||
account_values.get_mut(&coin).unwrap().push((account, value_this_addr))
|
||||
}
|
||||
|
||||
let pool_value = pool_amount.saturating_mul(value);
|
||||
total_value = total_value.saturating_add(pool_value);
|
||||
pool_values.insert(coin, (pool_amount, pool_value));
|
||||
}
|
||||
|
||||
// add the liquidity per pool
|
||||
for (coin, (amount, value)) in &pool_values {
|
||||
let sri_amount = GENESIS_SRI.saturating_mul(*value) / total_value;
|
||||
let origin = RawOrigin::Signed(GENESIS_LIQUIDITY_ACCOUNT.into());
|
||||
Dex::<T>::add_liquidity(
|
||||
origin.into(),
|
||||
*coin,
|
||||
*amount,
|
||||
sri_amount,
|
||||
*amount,
|
||||
sri_amount,
|
||||
GENESIS_LIQUIDITY_ACCOUNT.into(),
|
||||
)
|
||||
.unwrap();
|
||||
Self::deposit_event(Event::GenesisLiquidityAddedToPool {
|
||||
coin1: Balance { coin: *coin, amount: Amount(*amount) },
|
||||
coin2: Balance { coin: Coin::Serai, amount: Amount(sri_amount) },
|
||||
});
|
||||
|
||||
// set liquidity tokens per account
|
||||
let tokens = LiquidityTokens::<T>::balance(GENESIS_LIQUIDITY_ACCOUNT.into(), *coin).0;
|
||||
let mut total_tokens_this_coin: u64 = 0;
|
||||
for (acc, value) in account_values.get(coin).unwrap() {
|
||||
let liq_tokens_this_acc =
|
||||
tokens.saturating_mul(*value) / pool_values.get(coin).unwrap().1;
|
||||
total_tokens_this_coin = total_tokens_this_coin.saturating_add(liq_tokens_this_acc);
|
||||
LiquidityTokensPerAddress::<T>::set(coin, acc, Some(liq_tokens_this_acc));
|
||||
}
|
||||
assert_eq!(tokens, total_tokens_this_coin);
|
||||
}
|
||||
|
||||
// we shouldn't have any coin left in our account at this moment, including SRI.
|
||||
for coin in COINS {
|
||||
assert_eq!(Coins::<T>::balance(GENESIS_LIQUIDITY_ACCOUNT.into(), coin), Amount(0));
|
||||
}
|
||||
}
|
||||
|
||||
// we accept we reached economic security once we can mint smallest amount of a network's coin
|
||||
for coin in COINS {
|
||||
let existing = EconomicSecurityReached::<T>::get(coin.network());
|
||||
if existing == 0u32.into() &&
|
||||
<T as CoinsConfig>::AllowMint::is_allowed(&Balance { coin, amount: Amount(1) })
|
||||
{
|
||||
EconomicSecurityReached::<T>::set(coin.network(), n);
|
||||
Self::deposit_event(Event::EconomicSecurityReached { network: coin.network() });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Config> Pallet<T> {
|
||||
/// Add genesis liquidity for the given account. All accounts that provide liquidity
|
||||
/// will receive the genesis SRI according to their liquidity ratio.
|
||||
pub fn add_coin_liquidity(account: PublicKey, balance: Balance) -> DispatchResult {
|
||||
// check we are still in genesis period
|
||||
if Self::genesis_ended() {
|
||||
Err(Error::<T>::GenesisPeriodEnded)?;
|
||||
}
|
||||
|
||||
// mint the coins
|
||||
Coins::<T>::mint(GENESIS_LIQUIDITY_ACCOUNT.into(), balance)?;
|
||||
|
||||
// save
|
||||
let existing = Liquidity::<T>::get(balance.coin, account).unwrap_or(0);
|
||||
let new = existing.checked_add(balance.amount.0).ok_or(Error::<T>::AmountOverflowed)?;
|
||||
Liquidity::<T>::set(balance.coin, account, Some(new));
|
||||
|
||||
Self::deposit_event(Event::GenesisLiquidityAdded { by: account.into(), balance });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove the provided genesis liquidity for an account. If called pre-economic security era,
|
||||
pub fn remove_coin_liquidity(
|
||||
account: PublicKey,
|
||||
balance: Balance,
|
||||
out_address: ExternalAddress,
|
||||
) -> DispatchResult {
|
||||
let origin = RawOrigin::Signed(GENESIS_LIQUIDITY_ACCOUNT.into());
|
||||
|
||||
// check we are still in genesis period
|
||||
if Self::genesis_ended() {
|
||||
// check user have enough to remove
|
||||
let existing = LiquidityTokensPerAddress::<T>::get(balance.coin, account).unwrap_or(0);
|
||||
if balance.amount.0 > existing {
|
||||
Err(Error::<T>::NotEnoughLiquidity)?;
|
||||
}
|
||||
|
||||
// remove liquidity from pool
|
||||
let prev_sri = Coins::<T>::balance(GENESIS_LIQUIDITY_ACCOUNT.into(), Coin::Serai);
|
||||
let prev_coin = Coins::<T>::balance(GENESIS_LIQUIDITY_ACCOUNT.into(), balance.coin);
|
||||
Dex::<T>::remove_liquidity(
|
||||
origin.clone().into(),
|
||||
balance.coin,
|
||||
balance.amount.0,
|
||||
1,
|
||||
1,
|
||||
GENESIS_LIQUIDITY_ACCOUNT.into(),
|
||||
)?;
|
||||
let current_sri = Coins::<T>::balance(GENESIS_LIQUIDITY_ACCOUNT.into(), Coin::Serai);
|
||||
let current_coin = Coins::<T>::balance(GENESIS_LIQUIDITY_ACCOUNT.into(), balance.coin);
|
||||
|
||||
// burn the SRI if necessary
|
||||
let mut sri = current_sri.0.saturating_sub(prev_sri.0);
|
||||
let distance_to_full_pay =
|
||||
GENESIS_SRI_TRICKLE_FEED - Self::blocks_since_ec_security(&balance.coin);
|
||||
let burn_sri_amount = sri.saturating_mul(distance_to_full_pay) / GENESIS_SRI_TRICKLE_FEED;
|
||||
Coins::<T>::burn(
|
||||
origin.clone().into(),
|
||||
Balance { coin: Coin::Serai, amount: Amount(burn_sri_amount) },
|
||||
)?;
|
||||
sri -= burn_sri_amount;
|
||||
|
||||
// transfer to owner
|
||||
let coin_out = current_coin.0 - prev_coin.0;
|
||||
Coins::<T>::transfer(
|
||||
origin.clone().into(),
|
||||
account,
|
||||
Balance { coin: balance.coin, amount: Amount(coin_out) },
|
||||
)?;
|
||||
Coins::<T>::transfer(
|
||||
origin.into(),
|
||||
account,
|
||||
Balance { coin: Coin::Serai, amount: Amount(sri) },
|
||||
)?;
|
||||
|
||||
// save
|
||||
let existing = LiquidityTokensPerAddress::<T>::get(balance.coin, account).unwrap_or(0);
|
||||
let new = existing.checked_sub(balance.amount.0).ok_or(Error::<T>::AmountOverflowed)?;
|
||||
LiquidityTokensPerAddress::<T>::set(balance.coin, account, Some(new));
|
||||
} else {
|
||||
let existing = Liquidity::<T>::get(balance.coin, account).unwrap_or(0);
|
||||
if balance.amount.0 > existing || balance.amount.0 == 0 {
|
||||
Err(Error::<T>::NotEnoughLiquidity)?;
|
||||
}
|
||||
if balance.amount.0 < existing {
|
||||
Err(Error::<T>::CanOnlyRemoveFullAmount)?;
|
||||
}
|
||||
|
||||
// TODO: do internal transfer instead?
|
||||
let origin = RawOrigin::Signed(GENESIS_LIQUIDITY_ACCOUNT.into());
|
||||
let instruction = OutInstructionWithBalance {
|
||||
instruction: OutInstruction { address: out_address, data: None },
|
||||
balance,
|
||||
};
|
||||
Coins::<T>::burn_with_instruction(origin.into(), instruction)?;
|
||||
|
||||
// save
|
||||
Liquidity::<T>::set(balance.coin, account, None);
|
||||
}
|
||||
|
||||
Self::deposit_event(Event::GenesisLiquidityRemoved { by: account.into(), balance });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns the number of blocks since the coin's network reached economic security first time.
|
||||
/// If the network is yet to be reached that threshold, 0 is returned. And maximum of
|
||||
/// `GENESIS_SRI_TRICKLE_FEED` returned.
|
||||
fn blocks_since_ec_security(coin: &Coin) -> u64 {
|
||||
let ec_security_block =
|
||||
EconomicSecurityReached::<T>::get(coin.network()).saturated_into::<u64>();
|
||||
let current = <frame_system::Pallet<T>>::block_number().saturated_into::<u64>();
|
||||
if ec_security_block > 0 {
|
||||
let diff = current - ec_security_block;
|
||||
if diff > GENESIS_SRI_TRICKLE_FEED {
|
||||
return GENESIS_SRI_TRICKLE_FEED;
|
||||
}
|
||||
|
||||
return diff;
|
||||
}
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
fn genesis_ended() -> bool {
|
||||
<frame_system::Pallet<T>>::block_number() >= BLOCKS_PER_MONTH.into()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub use pallet::*;
|
||||
25
substrate/genesis-liquidity/primitives/Cargo.toml
Normal file
25
substrate/genesis-liquidity/primitives/Cargo.toml
Normal file
@@ -0,0 +1,25 @@
|
||||
[package]
|
||||
name = "serai-genesis-liquidity-primitives"
|
||||
version = "0.1.0"
|
||||
description = "Serai genesis liquidity primitives"
|
||||
license = "MIT"
|
||||
repository = "https://github.com/serai-dex/serai/tree/develop/substrate/genesis-liquidity/primitives"
|
||||
authors = ["Akil Demir <aeg_asd@hotmail.com>"]
|
||||
edition = "2021"
|
||||
rust-version = "1.77"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
serai-primitives = { path = "../../primitives", default-features = false }
|
||||
|
||||
[features]
|
||||
std = [
|
||||
"serai-primitives/std",
|
||||
]
|
||||
default = ["std"]
|
||||
21
substrate/genesis-liquidity/primitives/LICENSE
Normal file
21
substrate/genesis-liquidity/primitives/LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Luke Parker
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
17
substrate/genesis-liquidity/primitives/src/lib.rs
Normal file
17
substrate/genesis-liquidity/primitives/src/lib.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
#![cfg_attr(docsrs, feature(doc_cfg))]
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
use serai_primitives::*;
|
||||
|
||||
// amount of blocks in 30 days for 6s per block.
|
||||
pub const BLOCKS_PER_MONTH: u32 = 10 * 60 * 24 * 30;
|
||||
|
||||
/// 180 days of blocks
|
||||
pub const GENESIS_SRI_TRICKLE_FEED: u64 = 10 * 60 * 24 * 180;
|
||||
|
||||
// 100 Million SRI
|
||||
pub const GENESIS_SRI: u64 = 100_000_000 * 10_u64.pow(8);
|
||||
|
||||
// This is the account to hold and manage the genesis liquidity.
|
||||
pub const GENESIS_LIQUIDITY_ACCOUNT: SeraiAddress = system_address(b"Genesis-liquidity-account");
|
||||
@@ -37,6 +37,7 @@ in-instructions-primitives = { package = "serai-in-instructions-primitives", pat
|
||||
coins-pallet = { package = "serai-coins-pallet", path = "../../coins/pallet", default-features = false }
|
||||
dex-pallet = { package = "serai-dex-pallet", path = "../../dex/pallet", default-features = false }
|
||||
validator-sets-pallet = { package = "serai-validator-sets-pallet", path = "../../validator-sets/pallet", default-features = false }
|
||||
genesis-liquidity-pallet = { package = "serai-genesis-liquidity-pallet", path = "../../genesis-liquidity/pallet", default-features = false }
|
||||
|
||||
[features]
|
||||
std = [
|
||||
@@ -58,5 +59,6 @@ std = [
|
||||
"coins-pallet/std",
|
||||
"dex-pallet/std",
|
||||
"validator-sets-pallet/std",
|
||||
"genesis-liquidity-pallet/std",
|
||||
]
|
||||
default = ["std"]
|
||||
|
||||
@@ -33,10 +33,14 @@ pub mod pallet {
|
||||
Config as ValidatorSetsConfig, Pallet as ValidatorSets,
|
||||
};
|
||||
|
||||
use genesis_liquidity_pallet::{Pallet as GenesisLiq, Config as GenesisLiqConfig};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[pallet::config]
|
||||
pub trait Config: frame_system::Config + CoinsConfig + DexConfig + ValidatorSetsConfig {
|
||||
pub trait Config:
|
||||
frame_system::Config + CoinsConfig + DexConfig + ValidatorSetsConfig + GenesisLiqConfig
|
||||
{
|
||||
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
|
||||
}
|
||||
|
||||
@@ -200,6 +204,14 @@ pub mod pallet {
|
||||
}
|
||||
}
|
||||
}
|
||||
InInstruction::GenesisLiquidity(ops) => match ops {
|
||||
GenesisLiquidityOperation::Add(address, balance) => {
|
||||
GenesisLiq::<T>::add_coin_liquidity(address.into(), balance)?;
|
||||
}
|
||||
GenesisLiquidityOperation::Remove(address, balance, out_address) => {
|
||||
GenesisLiq::<T>::remove_coin_liquidity(address.into(), balance, out_address)?;
|
||||
}
|
||||
},
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -71,6 +71,15 @@ pub enum DexCall {
|
||||
Swap(Balance, OutAddress),
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)]
|
||||
#[cfg_attr(feature = "std", derive(Zeroize))]
|
||||
#[cfg_attr(feature = "borsh", derive(BorshSerialize, BorshDeserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub enum GenesisLiquidityOperation {
|
||||
Add(SeraiAddress, Balance),
|
||||
Remove(SeraiAddress, Balance, ExternalAddress),
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)]
|
||||
#[cfg_attr(feature = "std", derive(Zeroize))]
|
||||
#[cfg_attr(feature = "borsh", derive(BorshSerialize, BorshDeserialize))]
|
||||
@@ -78,6 +87,7 @@ pub enum DexCall {
|
||||
pub enum InInstruction {
|
||||
Transfer(SeraiAddress),
|
||||
Dex(DexCall),
|
||||
GenesisLiquidity(GenesisLiquidityOperation),
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Encode, Decode, MaxEncodedLen, TypeInfo, RuntimeDebug)]
|
||||
|
||||
@@ -7,6 +7,7 @@ use sc_service::ChainType;
|
||||
use serai_runtime::{
|
||||
primitives::*, WASM_BINARY, BABE_GENESIS_EPOCH_CONFIG, RuntimeGenesisConfig, SystemConfig,
|
||||
CoinsConfig, DexConfig, ValidatorSetsConfig, SignalsConfig, BabeConfig, GrandpaConfig,
|
||||
EmissionsConfig,
|
||||
};
|
||||
|
||||
pub type ChainSpec = sc_service::GenericChainSpec<RuntimeGenesisConfig>;
|
||||
@@ -59,6 +60,10 @@ fn testnet_genesis(
|
||||
.collect(),
|
||||
participants: validators.clone(),
|
||||
},
|
||||
emissions: EmissionsConfig {
|
||||
networks: serai_runtime::primitives::NETWORKS.to_vec(),
|
||||
participants: validators.clone(),
|
||||
},
|
||||
signals: SignalsConfig::default(),
|
||||
babe: BabeConfig {
|
||||
authorities: validators.iter().map(|validator| ((*validator).into(), 1)).collect(),
|
||||
|
||||
@@ -15,7 +15,9 @@ use sp_core::{ConstU32, bounded::BoundedVec};
|
||||
use crate::{borsh_serialize_bounded_vec, borsh_deserialize_bounded_vec};
|
||||
|
||||
/// The type used to identify networks.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)]
|
||||
#[derive(
|
||||
Clone, Copy, PartialEq, Eq, Hash, Debug, Encode, Decode, PartialOrd, Ord, MaxEncodedLen, TypeInfo,
|
||||
)]
|
||||
#[cfg_attr(feature = "std", derive(Zeroize))]
|
||||
#[cfg_attr(feature = "borsh", derive(BorshSerialize, BorshDeserialize))]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
|
||||
@@ -59,6 +59,8 @@ coins-pallet = { package = "serai-coins-pallet", path = "../coins/pallet", defau
|
||||
dex-pallet = { package = "serai-dex-pallet", path = "../dex/pallet", default-features = false }
|
||||
|
||||
validator-sets-pallet = { package = "serai-validator-sets-pallet", path = "../validator-sets/pallet", default-features = false }
|
||||
genesis-liquidity-pallet = { package = "serai-genesis-liquidity-pallet", path = "../genesis-liquidity/pallet", default-features = false }
|
||||
emissions-pallet = { package = "serai-emissions-pallet", path = "../emissions/pallet", default-features = false }
|
||||
|
||||
in-instructions-pallet = { package = "serai-in-instructions-pallet", path = "../in-instructions/pallet", default-features = false }
|
||||
|
||||
@@ -112,6 +114,8 @@ std = [
|
||||
"dex-pallet/std",
|
||||
|
||||
"validator-sets-pallet/std",
|
||||
"genesis-liquidity-pallet/std",
|
||||
"emissions-pallet/std",
|
||||
|
||||
"in-instructions-pallet/std",
|
||||
|
||||
|
||||
@@ -32,6 +32,9 @@ pub use signals_pallet as signals;
|
||||
pub use pallet_babe as babe;
|
||||
pub use pallet_grandpa as grandpa;
|
||||
|
||||
pub use genesis_liquidity_pallet as genesis_liquidity;
|
||||
pub use emissions_pallet as emissions;
|
||||
|
||||
// Actually used by the runtime
|
||||
use sp_core::OpaqueMetadata;
|
||||
use sp_std::prelude::*;
|
||||
@@ -288,6 +291,14 @@ impl in_instructions::Config for Runtime {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
}
|
||||
|
||||
impl genesis_liquidity::Config for Runtime {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
}
|
||||
|
||||
impl emissions::Config for Runtime {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
}
|
||||
|
||||
// for publishing equivocation evidences.
|
||||
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime
|
||||
where
|
||||
@@ -364,6 +375,8 @@ construct_runtime!(
|
||||
Dex: dex,
|
||||
|
||||
ValidatorSets: validator_sets,
|
||||
GenesisLiquidity: genesis_liquidity,
|
||||
Emissions: emissions,
|
||||
|
||||
InInstructions: in_instructions,
|
||||
|
||||
|
||||
@@ -489,11 +489,12 @@ pub mod pallet {
|
||||
network: NetworkId,
|
||||
account: T::AccountId,
|
||||
amount: Amount,
|
||||
block_reward: bool,
|
||||
) -> DispatchResult {
|
||||
let old_allocation = Self::allocation((network, account)).unwrap_or(Amount(0)).0;
|
||||
let new_allocation = old_allocation + amount.0;
|
||||
let allocation_per_key_share = Self::allocation_per_key_share(network).unwrap().0;
|
||||
if new_allocation < allocation_per_key_share {
|
||||
if new_allocation < allocation_per_key_share && !block_reward {
|
||||
Err(Error::<T>::InsufficientAllocation)?;
|
||||
}
|
||||
|
||||
@@ -796,6 +797,15 @@ pub mod pallet {
|
||||
total_required
|
||||
}
|
||||
|
||||
pub fn deposit_stake(
|
||||
network: NetworkId,
|
||||
account: T::AccountId,
|
||||
amount: Amount,
|
||||
) -> DispatchResult {
|
||||
// TODO: make the increase_allocation public instead?
|
||||
Self::increase_allocation(network, account, amount, true)
|
||||
}
|
||||
|
||||
fn can_slash_serai_validator(validator: Public) -> bool {
|
||||
// Checks if they're active or actively deallocating (letting us still slash them)
|
||||
// We could check if they're upcoming/still allocating, yet that'd mean the equivocation is
|
||||
@@ -936,7 +946,7 @@ pub mod pallet {
|
||||
Self::account(),
|
||||
Balance { coin: Coin::Serai, amount },
|
||||
)?;
|
||||
Self::increase_allocation(network, validator, amount)
|
||||
Self::increase_allocation(network, validator, amount, false)
|
||||
}
|
||||
|
||||
#[pallet::call_index(3)]
|
||||
|
||||
Reference in New Issue
Block a user