Skip to content

Commit

Permalink
fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
akildemir committed Jul 26, 2024
1 parent 84b534a commit 8eb7e66
Show file tree
Hide file tree
Showing 15 changed files with 270 additions and 190 deletions.
19 changes: 3 additions & 16 deletions substrate/client/src/serai/dex.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
use sp_core::bounded_vec::BoundedVec;
use serai_abi::primitives::{SeraiAddress, Amount, Coin};

use scale::{decode_from_bytes, Encode};

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

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

Expand Down Expand Up @@ -63,19 +61,8 @@ impl<'a> SeraiDex<'a> {
}

/// 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((coin, Coin::Serai).encode())],
)
.await?;
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(result.map(|amounts| (Amount(amounts.0), Amount(amounts.1))))
pub async fn get_reserves(&self, coin: Coin) -> Result<Option<(u64, u64)>, SeraiError> {
self.0.runtime_api("DexApi_get_reserves", (coin, Coin::Serai)).await
}

pub async fn oracle_value(&self, coin: Coin) -> Result<Option<Amount>, SeraiError> {
Expand Down
4 changes: 4 additions & 0 deletions substrate/client/src/serai/genesis_liquidity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,8 @@ impl<'a> SeraiGenesisLiquidity<'a> {
pub async fn supply(&self, coin: Coin) -> Result<LiquidityAmount, SeraiError> {
Ok(self.0.storage(PALLET, "Supply", coin).await?.unwrap_or(LiquidityAmount::zero()))
}

pub async fn genesis_complete(&self) -> Result<Option<()>, SeraiError> {
self.0.storage(PALLET, "GenesisComplete", ()).await
}
}
33 changes: 22 additions & 11 deletions substrate/client/src/serai/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,17 +198,6 @@ impl Serai {
Ok(())
}

// TODO: move this into substrate/client/src/validator_sets.rs
async fn active_network_validators(&self, network: NetworkId) -> Result<Vec<Public>, SeraiError> {
let validators: String = self
.call("state_call", ["SeraiRuntimeApi_validators".to_string(), hex::encode(network.encode())])
.await?;
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?;
Self::hex_decode(hash)?.try_into().map_err(|_| {
Expand Down Expand Up @@ -378,6 +367,28 @@ impl<'a> TemporalSerai<'a> {
})?))
}

async fn runtime_api<P: Encode, R: Decode>(
&self,
method: &'static str,
params: P,
) -> Result<R, SeraiError> {
let result: String = self
.serai
.call(
"state_call",
[method.to_string(), hex::encode(params.encode()), hex::encode(self.block)],
)
.await?;

let bytes = Serai::hex_decode(result.clone())?;
R::decode(&mut bytes.as_slice()).map_err(|_| {
SeraiError::InvalidRuntime(format!(
"different type than what is expected returned, raw value: {}",
hex::encode(result)
))
})
}

pub fn coins(&'a self) -> SeraiCoins<'a> {
SeraiCoins(self)
}
Expand Down
10 changes: 9 additions & 1 deletion substrate/client/src/serai/validator_sets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ impl<'a> SeraiValidatorSets<'a> {
&self,
network: NetworkId,
) -> Result<Vec<Public>, SeraiError> {
self.0.serai.active_network_validators(network).await
self.0.runtime_api("SeraiRuntimeApi_validators", network).await
}

// TODO: Store these separately since we almost never need both at once?
Expand All @@ -178,6 +178,14 @@ impl<'a> SeraiValidatorSets<'a> {
self.0.storage(PALLET, "PendingSlashReport", network).await
}

pub async fn session_begin_block(
&self,
network: NetworkId,
session: Session,
) -> Result<Option<u64>, SeraiError> {
self.0.storage(PALLET, "SessionBeginBlock", (network, session)).await
}

pub fn set_keys(
network: NetworkId,
removed_participants: sp_runtime::BoundedVec<
Expand Down
45 changes: 22 additions & 23 deletions substrate/client/tests/common/genesis_liquidity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ use serai_client::{
use crate::common::{in_instructions::provide_batch, tx::publish_tx};

#[allow(dead_code)]
pub async fn test_genesis_liquidity(serai: Serai) {
pub async fn test_genesis_liquidity(serai: Serai) -> HashMap<NetworkId, u32> {
// all coins except the native
let coins = COINS.into_iter().filter(|c| *c != Coin::native()).collect::<Vec<_>>();

Expand Down Expand Up @@ -79,21 +79,8 @@ pub async fn test_genesis_liquidity(serai: Serai) {
provide_batch(&serai, batch).await;
}

// wait until genesis ends
let genesis_blocks = 10; // TODO
let block_time = 6; // TODO
tokio::time::timeout(
tokio::time::Duration::from_secs(3 * (genesis_blocks * block_time)),
async {
while serai.latest_finalized_block().await.unwrap().number() < 10 {
tokio::time::sleep(Duration::from_secs(6)).await;
}
},
)
.await
.unwrap();

// set values relative to each other
// set values relative to each other. We can do that without checking for genesis period blocks
// since we are running in test(fast-epoch) mode.
// TODO: Random values here
let values = Values { monero: 184100, ether: 4785000, dai: 1500 };
set_values(&serai, &values).await;
Expand All @@ -103,8 +90,19 @@ pub async fn test_genesis_liquidity(serai: Serai) {
(Coin::Dai, values.dai),
]);

// wait a little bit..
tokio::time::sleep(Duration::from_secs(12)).await;
// wait until genesis is complete
while serai
.as_of_latest_finalized_block()
.await
.unwrap()
.genesis_liquidity()
.genesis_complete()
.await
.unwrap()
.is_none()
{
tokio::time::sleep(Duration::from_secs(1)).await;
}

// check total SRI supply is +100M
// there are 6 endowed accounts in dev-net. Take this into consideration when checking
Expand Down Expand Up @@ -147,8 +145,8 @@ pub async fn test_genesis_liquidity(serai: Serai) {
total_sri_distributed += sri;

let reserves = serai.dex().get_reserves(coin).await.unwrap().unwrap();
assert_eq!(u128::from(reserves.0 .0), pool_amounts[&coin].0); // coin side
assert_eq!(u128::from(reserves.1 .0), sri); // SRI side
assert_eq!(u128::from(reserves.0), pool_amounts[&coin].0); // coin side
assert_eq!(u128::from(reserves.1), sri); // SRI side
}

// check each liquidity provider got liquidity tokens proportional to their value
Expand All @@ -172,17 +170,18 @@ pub async fn test_genesis_liquidity(serai: Serai) {
assert_eq!(shares_ratio, amounts_ratio);
}
}

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

batch_ids
}

#[allow(dead_code)]
async fn set_values(serai: &Serai, values: &Values) {
// prepare a Musig tx to oraclize the relative values
let pair = insecure_pair_from_name("Alice");
let public = pair.public();
// we publish the tx in set 4
let set = ValidatorSet { session: Session(4), network: NetworkId::Serai };
// we publish the tx in set 1
let set = ValidatorSet { session: Session(1), network: NetworkId::Serai };

let public_key = <Ristretto as Ciphersuite>::read_G::<&[u8]>(&mut public.0.as_ref()).unwrap();
let secret_key = <Ristretto as Ciphersuite>::read_F::<&[u8]>(
Expand Down
12 changes: 6 additions & 6 deletions substrate/client/tests/common/in_instructions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use sp_core::Pair;

use serai_client::{
primitives::{insecure_pair_from_name, BlockHash, NetworkId, Balance, SeraiAddress},
validator_sets::primitives::{Session, ValidatorSet, KeyPair},
validator_sets::primitives::{ValidatorSet, KeyPair},
in_instructions::{
primitives::{Batch, SignedBatch, batch_message, InInstruction, InInstructionWithBalance},
InInstructionsEvent,
Expand All @@ -22,12 +22,12 @@ use crate::common::{tx::publish_tx, validator_sets::set_keys};

#[allow(dead_code)]
pub async fn provide_batch(serai: &Serai, batch: Batch) -> [u8; 32] {
// TODO: Get the latest session
let set = ValidatorSet { session: Session(0), network: batch.network };
let serai_latest = serai.as_of_latest_finalized_block().await.unwrap();
let session = serai_latest.validator_sets().session(batch.network).await.unwrap().unwrap();
let set = ValidatorSet { session, network: batch.network };

let pair = insecure_pair_from_name(&format!("ValidatorSet {set:?}"));
let keys = if let Some(keys) =
serai.as_of_latest_finalized_block().await.unwrap().validator_sets().keys(set).await.unwrap()
{
let keys = if let Some(keys) = serai_latest.validator_sets().keys(set).await.unwrap() {
keys
} else {
let keys = KeyPair(pair.public(), vec![].try_into().unwrap());
Expand Down
32 changes: 2 additions & 30 deletions substrate/client/tests/dex.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
use rand_core::{RngCore, OsRng};
use scale::Encode;

use sp_core::{Pair as PairTrait, bounded_vec::BoundedVec, hashing::blake2_256};
use sp_core::{Pair as PairTrait, bounded_vec::BoundedVec};

use serai_abi::in_instructions::primitives::DexCall;

use serai_client::{
primitives::{
Amount, NetworkId, Coin, Balance, BlockHash, insecure_pair_from_name, ExternalAddress,
SeraiAddress, PublicKey,
SeraiAddress,
},
in_instructions::primitives::{
InInstruction, InInstructionWithBalance, Batch, IN_INSTRUCTION_EXECUTOR, OutAddress,
Expand All @@ -28,33 +27,6 @@ use common::{
// TODO: Modularize common code
// TODO: Check Transfer events
serai_test!(
create_pool: (|serai: Serai| async move {
let block = serai.finalized_block_by_number(0).await.unwrap().unwrap().hash();
let events = serai.as_of(block).dex().events().await.unwrap();

assert_eq!(
events,
vec![
DexEvent::PoolCreated {
pool_id: Coin::Bitcoin,
pool_account: PublicKey::from_raw(blake2_256(&Coin::Bitcoin.encode())).into(),
},
DexEvent::PoolCreated {
pool_id: Coin::Ether,
pool_account: PublicKey::from_raw(blake2_256(&Coin::Ether.encode())).into(),
},
DexEvent::PoolCreated {
pool_id: Coin::Dai,
pool_account: PublicKey::from_raw(blake2_256(&Coin::Dai.encode())).into(),
},
DexEvent::PoolCreated {
pool_id: Coin::Monero,
pool_account: PublicKey::from_raw(blake2_256(&Coin::Monero.encode())).into(),
},
]
);
})

add_liquidity: (|serai: Serai| async move {
let coin = Coin::Monero;
let pair = insecure_pair_from_name("Ferdie");
Expand Down
Loading

0 comments on commit 8eb7e66

Please sign in to comment.