Skip to content

Commit

Permalink
chore: simplify withdraw state tables
Browse files Browse the repository at this point in the history
  • Loading branch information
matthias-wright committed Dec 23, 2024
1 parent cc714a8 commit 18a6807
Show file tree
Hide file tree
Showing 9 changed files with 67 additions and 90 deletions.
31 changes: 22 additions & 9 deletions core/application/src/state/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ use lightning_interfaces::types::{
UpdateMethod,
UpdateRequest,
Value,
WithdrawInfo,
MAX_MEASUREMENTS_PER_TX,
MAX_MEASUREMENTS_SUBMIT,
MAX_UPDATES_CONTENT_REGISTRY,
Expand Down Expand Up @@ -131,8 +132,7 @@ pub struct StateExecutor<B: Backend> {
),
>,
pub committee_selection_beacon_non_revealing_node: B::Ref<NodeIndex, ()>,
pub flk_withdraws: B::Ref<u64, (EthAddress, HpUfixed<18>)>,
pub usdc_withdraws: B::Ref<u64, (EthAddress, HpUfixed<6>)>,
pub withdraws: B::Ref<u64, WithdrawInfo>,
pub backend: B,
}

Expand Down Expand Up @@ -164,8 +164,7 @@ impl<B: Backend> StateExecutor<B> {
committee_selection_beacon: backend.get_table_reference("committee_selection_beacon"),
committee_selection_beacon_non_revealing_node: backend
.get_table_reference("committee_selection_beacon_non_revealing_node"),
flk_withdraws: backend.get_table_reference("flk_withdraws"),
usdc_withdraws: backend.get_table_reference("usdc_withdraws"),
withdraws: backend.get_table_reference("withdraws"),
backend,
}
}
Expand Down Expand Up @@ -477,7 +476,7 @@ impl<B: Backend> StateExecutor<B> {
fn withdraw(
&self,
sender: TransactionSender,
reciever: EthAddress,
receiver: EthAddress,
amount: HpUfixed<18>,
token: Tokens,
) -> TransactionResponse {
Expand All @@ -501,9 +500,16 @@ impl<B: Backend> StateExecutor<B> {
if amount > account.flk_balance {
return TransactionResponse::Revert(ExecutionError::InsufficientBalance);
}

account.flk_balance -= amount.clone();
self.flk_withdraws.set(withdraw_id, (reciever, amount));
self.withdraws.set(
withdraw_id,
WithdrawInfo {
epoch: 0,
token: Tokens::FLK,
receiver,
amount,
},
);
self.metadata
.set(Metadata::WithdrawId, Value::WithdrawId(withdraw_id + 1));
},
Expand All @@ -513,9 +519,16 @@ impl<B: Backend> StateExecutor<B> {
if amount > account.stables_balance {
return TransactionResponse::Revert(ExecutionError::InsufficientBalance);
}

account.stables_balance -= amount.clone();
self.usdc_withdraws.set(withdraw_id, (reciever, amount));
self.withdraws.set(
withdraw_id,
WithdrawInfo {
epoch: 0,
token: Tokens::USDC,
receiver,
amount: amount.convert_precision::<18>(),
},
);
self.metadata
.set(Metadata::WithdrawId, Value::WithdrawId(withdraw_id + 1));
},
Expand Down
3 changes: 1 addition & 2 deletions core/application/src/state/executor/epoch_change.rs
Original file line number Diff line number Diff line change
Expand Up @@ -677,8 +677,7 @@ impl<B: Backend> StateExecutor<B> {
self.executed_digests.clear();

// Clear withdraws
self.flk_withdraws.clear();
self.usdc_withdraws.clear();
self.withdraws.clear();
self.metadata
.set(Metadata::WithdrawId, Value::WithdrawId(0));

Expand Down
34 changes: 9 additions & 25 deletions core/application/src/state/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ use lightning_interfaces::types::{
TransactionResponse,
TxHash,
Value,
WithdrawInfo,
WithdrawInfoWithId,
};
use lightning_interfaces::{SyncQueryRunnerInterface, WithdrawPagingParams};
use merklize::{StateRootHash, StateTree};
Expand Down Expand Up @@ -79,8 +81,7 @@ pub struct QueryRunner {
),
>,
committee_selection_beacon_non_revealing_node: ResolvedTableReference<NodeIndex, ()>,
flk_withdraws: ResolvedTableReference<u64, (EthAddress, HpUfixed<18>)>,
usdc_withdraws: ResolvedTableReference<u64, (EthAddress, HpUfixed<6>)>,
withdraws: ResolvedTableReference<u64, WithdrawInfo>,
}

impl QueryRunner {
Expand Down Expand Up @@ -124,8 +125,7 @@ impl SyncQueryRunnerInterface for QueryRunner {
)>("committee_selection_beacon"),
committee_selection_beacon_non_revealing_node: atomo
.resolve::<NodeIndex, ()>("committee_selection_beacon_non_revealing_node"),
flk_withdraws: atomo.resolve::<u64, (EthAddress, HpUfixed<18>)>("flk_withdraws"),
usdc_withdraws: atomo.resolve::<u64, (EthAddress, HpUfixed<6>)>("usdc_withdraws"),
withdraws: atomo.resolve::<u64, WithdrawInfo>("withdraws"),
inner: atomo,
}
}
Expand Down Expand Up @@ -376,28 +376,12 @@ impl SyncQueryRunnerInterface for QueryRunner {
self.get_metadata(&Metadata::Epoch).is_some()
}

fn get_flk_withdraws(
&self,
paging: WithdrawPagingParams,
) -> Vec<(u64, EthAddress, HpUfixed<18>)> {
self.inner
.run(|ctx| self.flk_withdraws.get(ctx).as_map())
.iter()
.map(|(id, (address, amount))| (*id, *address, amount.clone()))
.filter(|(id, _, _)| id >= &paging.start)
.take(paging.limit)
.collect()
}

fn get_usdc_withdraws(
&self,
paging: WithdrawPagingParams,
) -> Vec<(u64, EthAddress, HpUfixed<6>)> {
fn get_withdraws(&self, paging: WithdrawPagingParams) -> Vec<WithdrawInfoWithId> {
self.inner
.run(|ctx| self.usdc_withdraws.get(ctx).as_map())
.iter()
.map(|(id, (address, amount))| (*id, *address, amount.clone()))
.filter(|(id, _, _)| id >= &paging.start)
.run(|ctx| self.withdraws.get(ctx).as_map())
.into_iter()
.map(|(id, info)| WithdrawInfoWithId { id, info })
.filter(|info| info.id >= paging.start)
.take(paging.limit)
.collect()
}
Expand Down
7 changes: 3 additions & 4 deletions core/application/src/state/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ use lightning_interfaces::types::{
TotalServed,
TxHash,
Value,
WithdrawInfo,
};
use lightning_interfaces::SyncQueryRunnerInterface;
use merklize::StateTree;
Expand Down Expand Up @@ -188,8 +189,7 @@ impl ApplicationState<AtomoStorage, DefaultSerdeBackend, ApplicationStateTree> {
Option<CommitteeSelectionBeaconReveal>,
)>("committee_selection_beacon")
.with_table::<NodeIndex, ()>("committee_selection_beacon_non_revealing_node")
.with_table::<u64, (EthAddress, HpUfixed<18>)>("flk_withdraws")
.with_table::<u64, (EthAddress, HpUfixed<6>)>("usdc_withdraws")
.with_table::<u64, WithdrawInfo>("withdraws")
.enable_iter("current_epoch_served")
.enable_iter("rep_measurements")
.enable_iter("submitted_rep_measurements")
Expand All @@ -203,8 +203,7 @@ impl ApplicationState<AtomoStorage, DefaultSerdeBackend, ApplicationStateTree> {
.enable_iter("node_to_uri")
.enable_iter("committee_selection_beacon")
.enable_iter("committee_selection_beacon_non_revealing_node")
.enable_iter("flk_withdraws")
.enable_iter("usdc_withdraws");
.enable_iter("withdraws");

#[cfg(debug_assertions)]
{
Expand Down
12 changes: 6 additions & 6 deletions core/application/src/tests/balances.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,12 +255,12 @@ async fn test_withdraw_usdc_works_properly() {
let update = prepare_update_request_account(withdraw, &owner_secret_key, 1);
expect_tx_success(update, &update_socket, ExecutionData::None).await;

let withdraws = query_runner.get_usdc_withdraws(WithdrawPagingParams {
let withdraws = query_runner.get_withdraws(WithdrawPagingParams {
start: 0,
limit: 100,
});
assert_eq!(withdraws[0].1, receiver);
assert_eq!(withdraws[0].2, withdraw_amount.into());
assert_eq!(withdraws[0].info.receiver, receiver);
assert_eq!(withdraws[0].info.amount, withdraw_amount.into());
}

#[tokio::test]
Expand Down Expand Up @@ -294,10 +294,10 @@ async fn test_withdraw_flk_works_properly() {
let update = prepare_update_request_account(withdraw, &owner_secret_key, 1);
expect_tx_success(update, &update_socket, ExecutionData::None).await;

let withdraws = query_runner.get_flk_withdraws(WithdrawPagingParams {
let withdraws = query_runner.get_withdraws(WithdrawPagingParams {
start: 0,
limit: 100,
});
assert_eq!(withdraws[0].1, receiver);
assert_eq!(withdraws[0].2, withdraw_amount.into());
assert_eq!(withdraws[0].info.receiver, receiver);
assert_eq!(withdraws[0].info.amount, withdraw_amount.into());
}
15 changes: 3 additions & 12 deletions core/interfaces/src/application.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ use atomo::{Atomo, InMemoryStorage, KeyIterator, QueryPerm, StorageBackend};
use fdi::BuildGraph;
use fleek_crypto::{ClientPublicKey, EthAddress, NodePublicKey};
use fxhash::FxHashMap;
use hp_fixed::unsigned::HpUfixed;
use lightning_types::{
AccountInfo,
Blake3Hash,
Expand All @@ -25,6 +24,7 @@ use lightning_types::{
TransactionRequest,
TxHash,
Value,
WithdrawInfoWithId,
};
use merklize::trees::mpt::MptStateProof;
use merklize::StateRootHash;
Expand Down Expand Up @@ -242,17 +242,8 @@ pub trait SyncQueryRunnerInterface: Clone + Send + Sync + 'static {
// Returns whether the genesis block has been applied.
fn has_genesis(&self) -> bool;

/// Returns a list of FLK withdraws
fn get_flk_withdraws(
&self,
paging: WithdrawPagingParams,
) -> Vec<(u64, EthAddress, HpUfixed<18>)>;

/// Returns a list of USDC withdraws
fn get_usdc_withdraws(
&self,
paging: WithdrawPagingParams,
) -> Vec<(u64, EthAddress, HpUfixed<6>)>;
/// Returns a list of withdraws
fn get_withdraws(&self, paging: WithdrawPagingParams) -> Vec<WithdrawInfoWithId>;
}

#[derive(Clone, Debug)]
Expand Down
15 changes: 4 additions & 11 deletions core/rpc/src/api/flk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use lightning_interfaces::types::{
};
use lightning_interfaces::{NodePagingParams, WithdrawPagingParams};
use lightning_openrpc_macros::open_rpc;
use lightning_types::{ProtocolParamKey, StateProofKey, StateProofValue};
use lightning_types::{ProtocolParamKey, StateProofKey, StateProofValue, WithdrawInfoWithId};
use merklize::{StateRootHash, StateTree};

#[open_rpc(namespace = "flk", tag = "1.0.0")]
Expand Down Expand Up @@ -220,19 +220,12 @@ pub trait FleekApi {
#[method(name = "metrics")]
async fn metrics(&self) -> RpcResult<String>;

#[method(name = "get_flk_withdraws")]
async fn get_flk_withdraws(
#[method(name = "get_withdraws")]
async fn get_withdraws(
&self,
epoch: Option<u64>,
paging: WithdrawPagingParams,
) -> RpcResult<Vec<(u64, EthAddress, HpUfixed<18>)>>;

#[method(name = "get_usdc_withdraws")]
async fn get_usdc_withdraws(
&self,
epoch: Option<u64>,
paging: WithdrawPagingParams,
) -> RpcResult<Vec<(u64, EthAddress, HpUfixed<6>)>>;
) -> RpcResult<Vec<WithdrawInfoWithId>>;

#[subscription(name = "subscribe", item = Event)]
async fn handle_subscription(&self, event_type: Option<EventType>) -> SubscriptionResult;
Expand Down
24 changes: 4 additions & 20 deletions core/rpc/src/logic/flk_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ use lightning_types::{AggregateCheckpoint, StateProofKey, StateProofValue};
use lightning_utils::application::QueryRunnerExt;
use merklize::{StateRootHash, StateTree};
use serde_json::Value as JsonValue;
use types::ProtocolParamKey;
use types::{ProtocolParamKey, WithdrawInfoWithId};

use crate::api::FleekApiServer;
use crate::error::RPCError;
Expand Down Expand Up @@ -468,28 +468,12 @@ impl<C: NodeComponents> FleekApiServer for FleekApi<C> {
}
}

async fn get_flk_withdraws(
async fn get_withdraws(
&self,
epoch: Option<u64>,
paging: WithdrawPagingParams,
) -> RpcResult<Vec<(u64, EthAddress, HpUfixed<18>)>> {
Ok(self
.data
.query_runner(epoch)
.await?
.get_flk_withdraws(paging))
}

async fn get_usdc_withdraws(
&self,
epoch: Option<u64>,
paging: WithdrawPagingParams,
) -> RpcResult<Vec<(u64, EthAddress, HpUfixed<6>)>> {
Ok(self
.data
.query_runner(epoch)
.await?
.get_usdc_withdraws(paging))
) -> RpcResult<Vec<WithdrawInfoWithId>> {
Ok(self.data.query_runner(epoch).await?.get_withdraws(paging))
}

async fn handle_subscription(
Expand Down
16 changes: 15 additions & 1 deletion core/types/src/application.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use fleek_crypto::{EthAddress, NodePublicKey};
use hp_fixed::unsigned::HpUfixed;
use serde::{Deserialize, Serialize};

use crate::{BlockNumber, Staking, TransactionReceipt};
use crate::{BlockNumber, Epoch, Staking, Tokens, TransactionReceipt};

/// Max number of updates allowed in a content registry update transaction.
pub const MAX_UPDATES_CONTENT_REGISTRY: usize = 100;
Expand Down Expand Up @@ -211,3 +211,17 @@ pub struct AccountInfo {
/// enforce ordering
pub nonce: u64,
}

#[derive(Debug, Hash, Serialize, Deserialize, Clone, schemars::JsonSchema)]
pub struct WithdrawInfo {
pub epoch: Epoch,
pub token: Tokens,
pub receiver: EthAddress,
pub amount: HpUfixed<18>,
}

#[derive(Debug, Hash, Serialize, Deserialize, Clone, schemars::JsonSchema)]
pub struct WithdrawInfoWithId {
pub id: u64,
pub info: WithdrawInfo,
}

0 comments on commit 18a6807

Please sign in to comment.