Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Split pos_accounting::PoolData::pledge_amount into pledge and reward #1440

Merged
merged 6 commits into from
Jan 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ impl ApiServerInMemoryStorage {
Ok(latest_pools)
}

fn get_pool_data_with_largest_pledge(
fn get_pool_data_with_largest_staker_balance(
&self,
len: u32,
offset: u32,
Expand All @@ -232,7 +232,7 @@ impl ApiServerInMemoryStorage {
.map(|(pool_id, by_height)| (pool_id, by_height.values().last().expect("not empty")))
.collect();

pool_data.sort_by_key(|(_, data)| Reverse(data.pledge_amount()));
pool_data.sort_by_key(|(_, data)| Reverse(data.staker_balance().expect("no overflow")));
if offset >= pool_data.len() {
return Ok(vec![]);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,12 +86,12 @@ impl<'t> ApiServerStorageRead for ApiServerInMemoryStorageTransactionalRo<'t> {
self.transaction.get_latest_pool_ids(len, offset)
}

async fn get_pool_data_with_largest_pledge(
async fn get_pool_data_with_largest_staker_balance(
&self,
len: u32,
offset: u32,
) -> Result<Vec<(PoolId, PoolData)>, ApiServerStorageError> {
self.transaction.get_pool_data_with_largest_pledge(len, offset)
self.transaction.get_pool_data_with_largest_staker_balance(len, offset)
}

async fn get_transaction(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -279,12 +279,12 @@ impl<'t> ApiServerStorageRead for ApiServerInMemoryStorageTransactionalRw<'t> {
self.transaction.get_latest_pool_ids(len, offset)
}

async fn get_pool_data_with_largest_pledge(
async fn get_pool_data_with_largest_staker_balance(
&self,
len: u32,
offset: u32,
) -> Result<Vec<(PoolId, PoolData)>, ApiServerStorageError> {
self.transaction.get_pool_data_with_largest_pledge(len, offset)
self.transaction.get_pool_data_with_largest_staker_balance(len, offset)
}

async fn get_transaction(
Expand Down
2 changes: 1 addition & 1 deletion api-server/api-server-common/src/storage/impls/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

pub const CURRENT_STORAGE_VERSION: u32 = 0;
pub const CURRENT_STORAGE_VERSION: u32 = 1;

pub mod in_memory;
pub mod postgres;
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,7 @@ impl<'a, 'b> QueryFromConnection<'a, 'b> {
"CREATE TABLE ml_pool_data (
pool_id TEXT NOT NULL,
block_height bigint NOT NULL,
pledge_amount TEXT NOT NULL,
staker_balance TEXT NOT NULL,
data bytea NOT NULL,
PRIMARY KEY (pool_id, block_height)
);",
Expand Down Expand Up @@ -930,7 +930,7 @@ impl<'a, 'b> QueryFromConnection<'a, 'b> {
.collect()
}

pub async fn get_pool_data_with_largest_pledge(
pub async fn get_pool_data_with_largest_staker_balance(
&self,
len: u32,
offset: u32,
Expand All @@ -943,11 +943,11 @@ impl<'a, 'b> QueryFromConnection<'a, 'b> {
r#"
SELECT pool_id, data
FROM (
SELECT pool_id, data, pledge_amount, ROW_NUMBER() OVER(PARTITION BY pool_id ORDER BY block_height DESC) as newest
SELECT pool_id, data, staker_balance, ROW_NUMBER() OVER(PARTITION BY pool_id ORDER BY block_height DESC) as newest
FROM ml_pool_data
) AS sub
WHERE newest = 1
ORDER BY pledge_amount DESC
ORDER BY staker_balance DESC
OFFSET $1
LIMIT $2;
"#,
Expand Down Expand Up @@ -983,14 +983,14 @@ impl<'a, 'b> QueryFromConnection<'a, 'b> {
chain_config: &ChainConfig,
) -> Result<(), ApiServerStorageError> {
let height = Self::block_height_to_postgres_friendly(block_height);
let amount_str = amount_to_str(pool_data.pledge_amount());
let amount_str = amount_to_str(pool_data.staker_balance().expect("no overflow"));
let pool_id = Address::new(chain_config, &pool_id)
.map_err(|_| ApiServerStorageError::AddressableError)?;

self.tx
.execute(
r#"
INSERT INTO ml_pool_data (pool_id, block_height, pledge_amount, data)
INSERT INTO ml_pool_data (pool_id, block_height, staker_balance, data)
VALUES ($1, $2, $3, $4)
"#,
&[&pool_id.get(), &height, &amount_str, &pool_data.encode()],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,13 +166,15 @@ impl<'a> ApiServerStorageRead for ApiServerPostgresTransactionalRo<'a> {
Ok(res)
}

async fn get_pool_data_with_largest_pledge(
async fn get_pool_data_with_largest_staker_balance(
&self,
len: u32,
offset: u32,
) -> Result<Vec<(PoolId, PoolData)>, ApiServerStorageError> {
let conn = QueryFromConnection::new(self.connection.as_ref().expect(CONN_ERR));
let res = conn.get_pool_data_with_largest_pledge(len, offset, &self.chain_config).await?;
let res = conn
.get_pool_data_with_largest_staker_balance(len, offset, &self.chain_config)
.await?;

Ok(res)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -365,13 +365,15 @@ impl<'a> ApiServerStorageRead for ApiServerPostgresTransactionalRw<'a> {
Ok(res)
}

async fn get_pool_data_with_largest_pledge(
async fn get_pool_data_with_largest_staker_balance(
&self,
len: u32,
offset: u32,
) -> Result<Vec<(PoolId, PoolData)>, ApiServerStorageError> {
let conn = QueryFromConnection::new(self.connection.as_ref().expect(CONN_ERR));
let res = conn.get_pool_data_with_largest_pledge(len, offset, &self.chain_config).await?;
let res = conn
.get_pool_data_with_largest_staker_balance(len, offset, &self.chain_config)
.await?;

Ok(res)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ pub trait ApiServerStorageRead: Sync {
offset: u32,
) -> Result<Vec<(PoolId, PoolData)>, ApiServerStorageError>;

async fn get_pool_data_with_largest_pledge(
async fn get_pool_data_with_largest_staker_balance(
&self,
len: u32,
offset: u32,
Expand Down
18 changes: 7 additions & 11 deletions api-server/scanner-lib/src/blockchain_state/adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,8 @@ impl PoSAdapter {

pub fn get_pool_data_with_reward(&self, pool_id: PoolId) -> Option<PoolData> {
self.pools.get(&pool_id).map(|pool_data| {
let amount_to_add = self.get_pool_reward(pool_id);
PoolData::new(
pool_data.decommission_destination().clone(),
(pool_data.pledge_amount() + amount_to_add).expect("no overflow"),
pool_data.vrf_public_key().clone(),
pool_data.margin_ratio_per_thousand(),
pool_data.cost_per_block(),
)
let reward = self.get_pool_reward(pool_id);
pool_data.clone().increase_staker_rewards(reward).expect("cannot overflow")
})
}

Expand Down Expand Up @@ -83,8 +77,8 @@ impl PoSAccountingView for PoSAdapter {
Ok(self.pools.get(&pool_id).cloned())
}

fn get_pool_balance(&self, pool_id: PoolId) -> Result<Option<Amount>, Self::Error> {
Ok(self.pools.get(&pool_id).map(|data| data.pledge_amount()))
fn get_pool_balance(&self, _pool_id: PoolId) -> Result<Option<Amount>, Self::Error> {
unimplemented!()
}

fn get_delegation_data(
Expand Down Expand Up @@ -143,6 +137,7 @@ impl PoSAccountingOperations<()> for PoSAdapter {
amount_to_delegate: Amount,
) -> Result<(), pos_accounting::Error> {
self.delegation_rewards.push((delegation_target, amount_to_delegate));

Ok(())
}

Expand All @@ -166,12 +161,13 @@ impl PoSAccountingOperations<()> for PoSAdapter {
unimplemented!()
}

fn increase_pool_pledge_amount(
fn increase_staker_rewards(
&mut self,
pool_id: PoolId,
amount_to_add: Amount,
) -> Result<(), pos_accounting::Error> {
self.pool_rewards.insert(pool_id, amount_to_add);

Ok(())
}

Expand Down
33 changes: 12 additions & 21 deletions api-server/scanner-lib/src/blockchain_state/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,13 +275,7 @@ async fn update_tables_from_block_reward<T: ApiServerStorageWrite>(
}
TxOutput::CreateStakePool(pool_id, pool_data) => {
let staker = pool_data.staker();
let pool_data = PoolData::new(
pool_data.decommission_key().clone(),
pool_data.value(),
pool_data.vrf_public_key().clone(),
pool_data.margin_ratio_per_thousand(),
pool_data.cost_per_block(),
);
let pool_data: PoolData = pool_data.as_ref().clone().into();

db_tx
.set_pool_data_at_height(*pool_id, &pool_data, block_height)
Expand All @@ -306,7 +300,7 @@ async fn update_tables_from_block_reward<T: ApiServerStorageWrite>(
increase_address_amount(
db_tx,
&address,
&pool_data.pledge_amount(),
&pool_data.staker_balance().expect("no overflow"),
CoinOrTokenId::Coin,
block_height,
)
Expand Down Expand Up @@ -424,14 +418,14 @@ async fn tx_fees<T: ApiServerStorageWrite>(
let inputs_utxos = collect_inputs_utxos(db_tx, tx.inputs(), new_outputs).await?;
let pools = prefetch_pool_amounts(&inputs_utxos, db_tx).await?;

let pledge_getter = |pool_id: PoolId| Ok(pools.get(&pool_id).cloned());
let staker_balance_getter = |pool_id: PoolId| Ok(pools.get(&pool_id).cloned());
// only used for checks for attempted to print money but we don't need to check that here
let delegation_balance_getter = |_delegation_id: DelegationId| Ok(Some(Amount::MAX));

let inputs_accumulator = ConstrainedValueAccumulator::from_inputs(
chain_config,
block_height,
pledge_getter,
staker_balance_getter,
delegation_balance_getter,
tx.inputs(),
&inputs_utxos,
Expand All @@ -454,8 +448,12 @@ async fn prefetch_pool_amounts<T: ApiServerStorageWrite>(
Some(
TxOutput::CreateStakePool(pool_id, _) | TxOutput::ProduceBlockFromStake(_, pool_id),
) => {
let amount =
db_tx.get_pool_data(*pool_id).await?.expect("should exist").pledge_amount();
let amount = db_tx
.get_pool_data(*pool_id)
.await?
.expect("should exist")
.staker_balance()
.expect("no overflow");
pools.insert(*pool_id, amount);
}
Some(
Expand Down Expand Up @@ -759,7 +757,7 @@ async fn update_tables_from_transaction_inputs<T: ApiServerStorageWrite>(
decrease_address_amount(
db_tx,
address,
&pool_data.pledge_amount(),
&pool_data.staker_balance().expect("no overflow"),
CoinOrTokenId::Coin,
block_height,
)
Expand Down Expand Up @@ -961,14 +959,7 @@ async fn update_tables_from_transaction_outputs<T: ApiServerStorageWrite>(
}
TxOutput::CreateStakePool(pool_id, stake_pool_data) => {
// Create pool pledge

let new_pool_data = PoolData::new(
stake_pool_data.decommission_key().clone(),
stake_pool_data.value(),
stake_pool_data.vrf_public_key().clone(),
stake_pool_data.margin_ratio_per_thousand(),
stake_pool_data.cost_per_block(),
);
let new_pool_data: PoolData = stake_pool_data.as_ref().clone().into();

db_tx
.set_pool_data_at_height(*pool_id, &new_pool_data, block_height)
Expand Down
15 changes: 8 additions & 7 deletions api-server/scanner-lib/src/sync/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -577,7 +577,7 @@ async fn basic_sync_real_state(#[case] seed: Seed) {
)
.unwrap();

let pool_pledge = local_state
let staker_balance = local_state
.storage()
.transaction_ro()
.await
Expand All @@ -586,7 +586,8 @@ async fn basic_sync_real_state(#[case] seed: Seed) {
.await
.unwrap()
.unwrap()
.pledge_amount();
.staker_balance()
.unwrap();

tf.progress_time_seconds_since_epoch(target_block_time.as_secs());
let block = tf
Expand Down Expand Up @@ -614,8 +615,8 @@ async fn basic_sync_real_state(#[case] seed: Seed) {
.unwrap()
.unwrap();

// after decommission the pool pledge is 0
assert_eq!(decommissioned_pool.pledge_amount(), Amount::ZERO);
// after decommission the staker balance is 0
assert_eq!(decommissioned_pool.staker_balance().unwrap(), Amount::ZERO);
let address = Address::<Destination>::new(
tf.chain_config(),
decommissioned_pool.decommission_destination(),
Expand All @@ -633,7 +634,7 @@ async fn basic_sync_real_state(#[case] seed: Seed) {
.unwrap()
.unwrap_or(Amount::ZERO);

assert_eq!(balance, pool_pledge);
assert_eq!(balance, staker_balance);
}

#[allow(clippy::too_many_arguments)]
Expand Down Expand Up @@ -683,7 +684,7 @@ async fn sync_and_compare(
let tx = local_state.storage().transaction_ro().await.unwrap();
let scanner_data = tx.get_pool_data(pool_id).await.unwrap().unwrap();

assert_eq!(node_data.pledge_amount(), scanner_data.pledge_amount());
assert_eq!(node_data.staker_balance(), scanner_data.staker_balance());

let address =
Address::<Destination>::new(tf.chain_config(), scanner_data.decommission_destination())
Expand All @@ -695,7 +696,7 @@ async fn sync_and_compare(
.unwrap()
.unwrap_or(Amount::ZERO);

assert_eq!(balance, scanner_data.pledge_amount());
assert_eq!(balance, scanner_data.staker_balance().unwrap());

let node_delegations = tf
.chainstate
Expand Down
2 changes: 1 addition & 1 deletion api-server/stack-test-suite/tests/v1/pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ async fn ok(#[case] seed: Seed) {
decommission_key.get(),
);
assert_eq!(
body.get("pledge").unwrap(),
body.get("staker_balance").unwrap(),
&serde_json::json!(pool_data.value())
);

Expand Down
4 changes: 2 additions & 2 deletions api-server/stack-test-suite/tests/v1/pools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ async fn ok(#[case] seed: Seed) {
decommission_key.get(),
);
assert_eq!(
json.get("pledge").unwrap(),
json.get("staker_balance").unwrap(),
&serde_json::json!(pool_data.value())
);

Expand Down Expand Up @@ -280,7 +280,7 @@ async fn ok(#[case] seed: Seed) {
decommission_key.get(),
);
assert_eq!(
json.get("pledge").unwrap(),
json.get("staker_balance").unwrap(),
&serde_json::json!(pool_data.value())
);

Expand Down
Loading
Loading