Skip to content

Commit

Permalink
fix pr comments
Browse files Browse the repository at this point in the history
  • Loading branch information
akildemir committed Jun 28, 2024
1 parent f75fe67 commit c14923f
Show file tree
Hide file tree
Showing 17 changed files with 256 additions and 283 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 0 additions & 9 deletions substrate/abi/src/coins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,6 @@ pub enum Call {
burn_with_instruction { instruction: OutInstructionWithBalance },
}

#[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))]
#[cfg_attr(all(feature = "std", feature = "serde"), derive(serde::Deserialize))]
pub enum LiquidityTokensCall {
transfer { to: SeraiAddress, balance: Balance },
burn { balance: Balance },
}

#[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))]
Expand Down
5 changes: 3 additions & 2 deletions substrate/abi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub mod system;
pub mod timestamp;

pub mod coins;
pub mod liquidity_tokens;
pub mod dex;

pub mod validator_sets;
Expand All @@ -29,7 +30,7 @@ pub mod tx;
pub enum Call {
Timestamp(timestamp::Call),
Coins(coins::Call),
LiquidityTokens(coins::LiquidityTokensCall),
LiquidityTokens(liquidity_tokens::Call),
Dex(dex::Call),
GenesisLiquidity(genesis_liquidity::Call),
ValidatorSets(validator_sets::Call),
Expand All @@ -51,7 +52,7 @@ pub enum Event {
Timestamp,
TransactionPayment(TransactionPaymentEvent),
Coins(coins::Event),
LiquidityTokens(coins::Event),
LiquidityTokens(liquidity_tokens::Event),
Dex(dex::Event),
GenesisLiquidity(genesis_liquidity::Event),
ValidatorSets(validator_sets::Event),
Expand Down
23 changes: 11 additions & 12 deletions substrate/client/src/serai/dex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use serai_abi::primitives::{SeraiAddress, Amount, Coin};

use scale::{decode_from_bytes, Encode};

use crate::{SeraiError, hex_decode, TemporalSerai};
use crate::{Serai, SeraiError, TemporalSerai};

pub type DexEvent = serai_abi::dex::Event;

Expand Down Expand Up @@ -60,20 +60,19 @@ impl<'a> SeraiDex<'a> {
})
}

pub async fn get_reserves(
&self,
coin1: Coin,
coin2: Coin,
) -> Result<Option<(Amount, Amount)>, SeraiError> {
let hash = self
/// Returns the reserves of `coin:SRI` pool.
pub async fn get_reserves(&self, coin: Coin) -> Result<Option<(Amount, Amount)>, SeraiError> {
let reserves = self
.0
.serai
.call("state_call", ["DexApi_get_reserves".to_string(), hex::encode((coin1, coin2).encode())])
.call(
"state_call",
["DexApi_get_reserves".to_string(), hex::encode((coin, Coin::Serai).encode())],
)
.await?;
let bytes = hex_decode(hash)
.map_err(|_| SeraiError::InvalidNode("expected hex from node wasn't hex".to_string()))?;
let resut = decode_from_bytes::<Option<(u64, u64)>>(bytes.into())
let bytes = Serai::hex_decode(reserves)?;
let result = decode_from_bytes::<Option<(u64, u64)>>(bytes.into())
.map_err(|e| SeraiError::ErrorInResponse(e.to_string()))?;
Ok(resut.map(|amounts| (Amount(amounts.0), Amount(amounts.1))))
Ok(result.map(|amounts| (Amount(amounts.0), Amount(amounts.1))))
}
}
44 changes: 16 additions & 28 deletions substrate/client/src/serai/genesis_liquidity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,24 +29,6 @@ impl<'a> SeraiGenesisLiquidity<'a> {
.await
}

pub async fn liquidity_tokens(
&self,
address: &SeraiAddress,
coin: Coin,
) -> Result<Amount, SeraiError> {
Ok(
self
.0
.storage(
PALLET,
"LiquidityTokensPerAddress",
(coin, sp_core::hashing::blake2_128(&address.encode()), &address.0),
)
.await?
.unwrap_or(Amount(0)),
)
}

pub fn set_initial_price(prices: Prices, signature: Signature) -> Transaction {
Serai::unsigned(serai_abi::Call::GenesisLiquidity(
serai_abi::genesis_liquidity::Call::set_initial_price { prices, signature },
Expand All @@ -59,15 +41,21 @@ impl<'a> SeraiGenesisLiquidity<'a> {
})
}

pub async fn liquidity(&self, address: &SeraiAddress, coin: Coin) -> Option<Amount> {
self
.0
.storage(
PALLET,
"Liquidity",
(coin, sp_core::hashing::blake2_128(&address.encode()), &address.0),
)
.await
.unwrap()
pub async fn liquidity(&self, address: &SeraiAddress, coin: Coin) -> Result<Amount, SeraiError> {
Ok(
self
.0
.storage(
PALLET,
"Liquidity",
(coin, sp_core::hashing::blake2_128(&address.encode()), &address.0),
)
.await?
.unwrap_or(Amount(0)),
)
}

pub async fn supply(&self, coin: Coin) -> Result<(Amount, Amount), SeraiError> {
Ok(self.0.storage(PALLET, "Supply", coin).await?.unwrap_or((Amount(0), Amount(0))))
}
}
4 changes: 2 additions & 2 deletions substrate/client/src/serai/liquidity_tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ impl<'a> SeraiLiquidityTokens<'a> {
}

pub fn transfer(to: SeraiAddress, balance: Balance) -> serai_abi::Call {
serai_abi::Call::Coins(serai_abi::coins::Call::transfer { to, balance })
serai_abi::Call::LiquidityTokens(serai_abi::liquidity_tokens::Call::transfer { to, balance })
}

pub fn burn(balance: Balance) -> serai_abi::Call {
serai_abi::Call::Coins(serai_abi::coins::Call::burn { balance })
serai_abi::Call::LiquidityTokens(serai_abi::liquidity_tokens::Call::burn { balance })
}
}
38 changes: 16 additions & 22 deletions substrate/client/src/serai/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use hex::FromHexError;
use thiserror::Error;

use async_lock::RwLock;
Expand Down Expand Up @@ -87,14 +86,6 @@ impl<'a> Clone for TemporalSerai<'a> {
}
}

pub fn hex_decode(str: String) -> Result<Vec<u8>, FromHexError> {
if let Some(stripped) = str.strip_prefix("0x") {
hex::decode(stripped)
} else {
hex::decode(str)
}
}

impl Serai {
pub async fn call<Req: Serialize, Res: DeserializeOwned>(
&self,
Expand Down Expand Up @@ -147,11 +138,19 @@ impl Serai {
}
}

fn hex_decode(str: String) -> Result<Vec<u8>, SeraiError> {
(if let Some(stripped) = str.strip_prefix("0x") {
hex::decode(stripped)
} else {
hex::decode(str)
})
.map_err(|_| SeraiError::InvalidNode("expected hex from node wasn't hex".to_string()))
}

pub async fn block_hash(&self, number: u64) -> Result<Option<[u8; 32]>, SeraiError> {
let hash: Option<String> = self.call("chain_getBlockHash", [number]).await?;
let Some(hash) = hash else { return Ok(None) };
hex_decode(hash)
.map_err(|_| SeraiError::InvalidNode("expected hex from node wasn't hex".to_string()))?
Self::hex_decode(hash)?
.try_into()
.map_err(|_| SeraiError::InvalidNode("didn't respond to getBlockHash with hash".to_string()))
.map(Some)
Expand Down Expand Up @@ -204,21 +203,17 @@ impl Serai {
let validators: String = self
.call("state_call", ["SeraiRuntimeApi_validators".to_string(), hex::encode(network.encode())])
.await?;
let bytes = hex_decode(validators)
.map_err(|_| SeraiError::InvalidNode("expected hex from node wasn't hex".to_string()))?;
let bytes = Self::hex_decode(validators)?;
let r = Vec::<Public>::decode(&mut bytes.as_slice())
.map_err(|e| SeraiError::ErrorInResponse(e.to_string()))?;
Ok(r)
}

pub async fn latest_finalized_block_hash(&self) -> Result<[u8; 32], SeraiError> {
let hash: String = self.call("chain_getFinalizedHead", ()).await?;
hex_decode(hash)
.map_err(|_| SeraiError::InvalidNode("expected hex from node wasn't hex".to_string()))?
.try_into()
.map_err(|_| {
SeraiError::InvalidNode("didn't respond to getFinalizedHead with hash".to_string())
})
Self::hex_decode(hash)?.try_into().map_err(|_| {
SeraiError::InvalidNode("didn't respond to getFinalizedHead with hash".to_string())
})
}

pub async fn header(&self, hash: [u8; 32]) -> Result<Option<Header>, SeraiError> {
Expand All @@ -228,7 +223,7 @@ impl Serai {
pub async fn block(&self, hash: [u8; 32]) -> Result<Option<Block>, SeraiError> {
let block: Option<String> = self.call("chain_getBlockBin", [hex::encode(hash)]).await?;
let Some(block) = block else { return Ok(None) };
let Ok(bytes) = hex_decode(block) else {
let Ok(bytes) = Self::hex_decode(block) else {
Err(SeraiError::InvalidNode("didn't return a hex-encoded block".to_string()))?
};
let Ok(block) = Block::decode(&mut bytes.as_slice()) else {
Expand Down Expand Up @@ -374,8 +369,7 @@ impl<'a> TemporalSerai<'a> {
let res: Option<String> =
self.serai.call("state_getStorage", [hex::encode(full_key), hex::encode(self.block)]).await?;
let Some(res) = res else { return Ok(None) };
let res = hex_decode(res)
.map_err(|_| SeraiError::InvalidNode("expected hex from node wasn't hex".to_string()))?;
let res = Serai::hex_decode(res)?;
Ok(Some(R::decode(&mut res.as_slice()).map_err(|_| {
SeraiError::InvalidRuntime(format!(
"different type present at storage location, raw value: {}",
Expand Down
86 changes: 29 additions & 57 deletions substrate/client/tests/genesis_liquidity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use schnorrkel::Schnorrkel;

use serai_client::{
genesis_liquidity::{
primitives::{GENESIS_LIQUIDITY_ACCOUNT, GENESIS_SRI},
primitives::{GENESIS_LIQUIDITY_ACCOUNT, GENESIS_LP_SHARES},
SeraiGenesisLiquidity,
},
validator_sets::primitives::{musig_context, Session, ValidatorSet},
Expand All @@ -24,7 +24,7 @@ use sp_core::{sr25519::Signature, Pair as PairTrait};

use serai_client::{
primitives::{
Amount, NetworkId, Coin, Balance, BlockHash, SeraiAddress, insecure_pair_from_name,
Amount, NetworkId, Coin, Balance, BlockHash, SeraiAddress, insecure_pair_from_name, GENESIS_SRI,
},
in_instructions::primitives::{InInstruction, InInstructionWithBalance, Batch},
Serai,
Expand Down Expand Up @@ -63,8 +63,6 @@ async fn test_genesis_liquidity(serai: Serai) {
xmr_addresses.push((address, amount));
}
}
btc_addresses.sort_by(|a1, a2| a1.0.cmp(&a2.0));
xmr_addresses.sort_by(|a1, a2| a1.0.cmp(&a2.0));

// btc batch
let mut block_hash = BlockHash([0; 32]);
Expand Down Expand Up @@ -93,23 +91,25 @@ async fn test_genesis_liquidity(serai: Serai) {
let batch = Batch { network: NetworkId::Monero, id: 0, block: block_hash, instructions: xmr_ins };
provide_batch(&serai, batch).await;

// set prices
let prices = Prices { bitcoin: 10u64.pow(8), monero: 184100, ethereum: 4785000, dai: 1500 };
set_prices(&serai, &prices).await;

// wait until genesis ends..
tokio::time::timeout(tokio::time::Duration::from_secs(300), async {
while serai.latest_finalized_block().await.unwrap().number() < 25 {
while serai.latest_finalized_block().await.unwrap().number() < 10 {
tokio::time::sleep(Duration::from_secs(6)).await;
}
})
.await
.unwrap();

// set prices
let prices = Prices { bitcoin: 10u64.pow(8), monero: 184100, ethereum: 4785000, dai: 1500 };
set_prices(&serai, &prices).await;

// wait little bit..
tokio::time::sleep(Duration::from_secs(12)).await;

// check total SRI supply is +100M
let last_block = serai.latest_finalized_block().await.unwrap().hash();
let serai = serai.as_of(last_block);
// Check balance instead of supply
let sri = serai.coins().coin_supply(Coin::Serai).await.unwrap();
// there are 6 endowed accounts in dev-net. Take this into consideration when checking
// for the total sri minted at this time.
Expand All @@ -136,65 +136,37 @@ async fn test_genesis_liquidity(serai: Serai) {
let btc_sri = (pool_btc_value * u128::from(GENESIS_SRI)) / total_value;
let xmr_sri = ((pool_xmr_value * u128::from(GENESIS_SRI)) / total_value) + 1;

let btc_reserves = serai.dex().get_reserves(Coin::Bitcoin, Coin::Serai).await.unwrap().unwrap();
let btc_reserves = serai.dex().get_reserves(Coin::Bitcoin).await.unwrap().unwrap();
assert_eq!(u128::from(btc_reserves.0 .0), pool_btc);
assert_eq!(u128::from(btc_reserves.1 .0), btc_sri);

let xmr_reserves = serai.dex().get_reserves(Coin::Monero, Coin::Serai).await.unwrap().unwrap();
let xmr_reserves = serai.dex().get_reserves(Coin::Monero).await.unwrap().unwrap();
assert_eq!(u128::from(xmr_reserves.0 .0), pool_xmr);
assert_eq!(u128::from(xmr_reserves.1 .0), xmr_sri);

// check each btc liq provider got liq tokens proportional to their value
let btc_liq_token_supply = u128::from(
serai
.liquidity_tokens()
.token_balance(Coin::Bitcoin, GENESIS_LIQUIDITY_ACCOUNT)
.await
.unwrap()
.0,
);
let mut total_tokens_this_coin: u128 = 0;
for (i, (addr, amount)) in btc_addresses.iter().enumerate() {
let addr_value = (u128::from(amount.0) * u128::from(prices.bitcoin)) / 10u128.pow(8);
let addr_liq_tokens = if i == btc_addresses.len() - 1 {
btc_liq_token_supply - total_tokens_this_coin
} else {
(addr_value * btc_liq_token_supply) / pool_btc_value
};

let addr_actual_token_amount =
serai.genesis_liquidity().liquidity_tokens(addr, Coin::Bitcoin).await.unwrap();

assert_eq!(addr_liq_tokens, addr_actual_token_amount.0.into());
total_tokens_this_coin += addr_liq_tokens;
let btc_liq_supply = serai.genesis_liquidity().supply(Coin::Bitcoin).await.unwrap();
for (acc, amount) in btc_addresses {
let acc_liq_shares = serai.genesis_liquidity().liquidity(&acc, Coin::Bitcoin).await.unwrap().0;

// since we can't test the ratios directly(due to integer division giving 0)
// we test whether they give the same result when multiplied by another constant.
// Following test ensures the account in fact has the right amount of shares.
let shares_ratio = (GENESIS_LP_SHARES * acc_liq_shares) / btc_liq_supply.0 .0;
let amounts_ratio = (GENESIS_LP_SHARES * amount.0) / u64::try_from(pool_btc).unwrap();
assert_eq!(shares_ratio, amounts_ratio);
}

// check each xmr liq provider got liq tokens proportional to their value
let xmr_liq_token_supply = u128::from(
serai
.liquidity_tokens()
.token_balance(Coin::Monero, GENESIS_LIQUIDITY_ACCOUNT)
.await
.unwrap()
.0,
);
total_tokens_this_coin = 0;
for (i, (addr, amount)) in xmr_addresses.iter().enumerate() {
let addr_value = (u128::from(amount.0) * u128::from(prices.monero)) / 10u128.pow(12);
let addr_liq_tokens = if i == xmr_addresses.len() - 1 {
xmr_liq_token_supply - total_tokens_this_coin
} else {
(addr_value * xmr_liq_token_supply) / pool_xmr_value
};

let addr_actual_token_amount =
serai.genesis_liquidity().liquidity_tokens(addr, Coin::Monero).await.unwrap();

assert_eq!(addr_liq_tokens, addr_actual_token_amount.0.into());
total_tokens_this_coin += addr_liq_tokens;
let xmr_liq_supply = serai.genesis_liquidity().supply(Coin::Monero).await.unwrap();
for (acc, amount) in xmr_addresses {
let acc_liq_shares = serai.genesis_liquidity().liquidity(&acc, Coin::Monero).await.unwrap().0;
let shares_ratio = (GENESIS_LP_SHARES * acc_liq_shares) / xmr_liq_supply.0 .0;
let amounts_ratio = (GENESIS_LP_SHARES * amount.0) / u64::try_from(pool_xmr).unwrap();
assert_eq!(shares_ratio, amounts_ratio);
}

// TODO: remove the liq before/after genesis ended.
// TODO: test remove the liq before/after genesis ended.
}

async fn set_prices(serai: &Serai, prices: &Prices) {
Expand Down
2 changes: 1 addition & 1 deletion substrate/dex/pallet/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub use coins_pallet as coins;

use coins::Pallet as CoinsPallet;

use serai_primitives::*;
use serai_primitives::{Balance, COINS, PublicKey, system_address, Amount};

type LiquidityTokens<T> = coins_pallet::Pallet<T, coins::Instance1>;
type LiquidityTokensError<T> = coins_pallet::Error<T, coins::Instance1>;
Expand Down
Loading

0 comments on commit c14923f

Please sign in to comment.