From a4a7d1bc6e5f24b69dbb966daaa3f8e49f75ef6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maciej=20W=C3=B3jcik?= Date: Thu, 5 Dec 2024 11:19:40 +0100 Subject: [PATCH 1/3] rename prepayment-related enums --- execution_engine/src/runtime_context/mod.rs | 2 +- storage/src/tracking_copy/byte_size.rs | 2 +- storage/src/tracking_copy/mod.rs | 4 ++-- types/src/execution/transform_kind.rs | 4 ++-- types/src/gens.rs | 2 +- types/src/stored_value.rs | 22 +++++++++---------- types/src/system/prepayment.rs | 4 ++-- .../{prepaid_kind.rs => prepayment_kind.rs} | 4 ++-- types/src/transaction/pricing_mode.rs | 2 +- 9 files changed, 23 insertions(+), 23 deletions(-) rename types/src/system/prepayment/{prepaid_kind.rs => prepayment_kind.rs} (95%) diff --git a/execution_engine/src/runtime_context/mod.rs b/execution_engine/src/runtime_context/mod.rs index 97cf50166e..c3b9d5e44c 100644 --- a/execution_engine/src/runtime_context/mod.rs +++ b/execution_engine/src/runtime_context/mod.rs @@ -753,7 +753,7 @@ where | StoredValue::ContractWasm(_) | StoredValue::MessageTopic(_) | StoredValue::Message(_) - | StoredValue::Prepaid(_) + | StoredValue::Prepayment(_) | StoredValue::EntryPoint(_) | StoredValue::RawBytes(_) => Ok(()), } diff --git a/storage/src/tracking_copy/byte_size.rs b/storage/src/tracking_copy/byte_size.rs index d81fd4137a..da6794d6d8 100644 --- a/storage/src/tracking_copy/byte_size.rs +++ b/storage/src/tracking_copy/byte_size.rs @@ -47,7 +47,7 @@ impl ByteSize for StoredValue { } StoredValue::Message(message_summary) => message_summary.serialized_length(), StoredValue::NamedKey(named_key) => named_key.serialized_length(), - StoredValue::Prepaid(reservation_kind) => reservation_kind.serialized_length(), + StoredValue::Prepayment(prepayment_kind) => prepayment_kind.serialized_length(), StoredValue::EntryPoint(entry_point) => entry_point.serialized_length(), StoredValue::RawBytes(raw_bytes) => raw_bytes.serialized_length(), } diff --git a/storage/src/tracking_copy/mod.rs b/storage/src/tracking_copy/mod.rs index 6208469c1e..e6a52022b7 100644 --- a/storage/src/tracking_copy/mod.rs +++ b/storage/src/tracking_copy/mod.rs @@ -853,8 +853,8 @@ where StoredValue::EntryPoint(_) => { return Ok(query.into_not_found_result("EntryPoint value found.")); } - StoredValue::Prepaid(_) => { - return Ok(query.into_not_found_result("Prepaid value found.")) + StoredValue::Prepayment(_) => { + return Ok(query.into_not_found_result("Prepayment value found.")) } StoredValue::RawBytes(_) => { return Ok(query.into_not_found_result("RawBytes value found.")); diff --git a/types/src/execution/transform_kind.rs b/types/src/execution/transform_kind.rs index 9ec62e63c8..94c11db9de 100644 --- a/types/src/execution/transform_kind.rs +++ b/types/src/execution/transform_kind.rs @@ -196,9 +196,9 @@ impl TransformKindV2 { let found = "RawBytes".to_string(); Err(StoredValueTypeMismatch::new(expected, found).into()) } - StoredValue::Prepaid(_) => { + StoredValue::Prepayment(_) => { let expected = "Contract or Account".to_string(); - let found = "Reservation".to_string(); + let found = "Prepayment".to_string(); Err(StoredValueTypeMismatch::new(expected, found).into()) } StoredValue::EntryPoint(_) => { diff --git a/types/src/gens.rs b/types/src/gens.rs index 71661bf71c..ac4cb6f836 100644 --- a/types/src/gens.rs +++ b/types/src/gens.rs @@ -1015,7 +1015,7 @@ pub fn stored_value_arb() -> impl Strategy { StoredValue::MessageTopic(_) => stored_value, StoredValue::Message(_) => stored_value, StoredValue::NamedKey(_) => stored_value, - StoredValue::Prepaid(_) => stored_value, + StoredValue::Prepayment(_) => stored_value, StoredValue::EntryPoint(_) => stored_value, StoredValue::RawBytes(_) => stored_value, }) diff --git a/types/src/stored_value.rs b/types/src/stored_value.rs index eea12fb1fd..010e6479dc 100644 --- a/types/src/stored_value.rs +++ b/types/src/stored_value.rs @@ -25,7 +25,7 @@ use crate::{ package::Package, system::{ auction::{Bid, BidKind, EraInfo, Unbond, UnbondingPurse, WithdrawPurse}, - prepayment::PrepaidKind, + prepayment::PrepaymentKind, }, AddressableEntity, ByteCode, CLValue, DeployInfo, EntryPointValue, TransferV1, }; @@ -72,8 +72,8 @@ pub enum StoredValueTag { Message = 16, /// A NamedKey record. NamedKey = 17, - /// A reservation record. - Reservation = 18, + /// A prepayment record. + Prepayment = 18, /// An entrypoint record. EntryPoint = 19, /// Raw bytes. @@ -126,8 +126,8 @@ pub enum StoredValue { Message(MessageChecksum), /// A NamedKey record. NamedKey(NamedKeyValue), - /// A reservation record. - Prepaid(PrepaidKind), + /// A prepayment record. + Prepayment(PrepaymentKind), /// An entrypoint record. EntryPoint(EntryPointValue), /// Raw bytes. Similar to a [`crate::StoredValue::CLValue`] but does not incur overhead of a @@ -443,7 +443,7 @@ impl StoredValue { StoredValue::MessageTopic(_) => "MessageTopic".to_string(), StoredValue::Message(_) => "Message".to_string(), StoredValue::NamedKey(_) => "NamedKey".to_string(), - StoredValue::Prepaid(_) => "Reservation".to_string(), + StoredValue::Prepayment(_) => "Prepayment".to_string(), StoredValue::EntryPoint(_) => "EntryPoint".to_string(), StoredValue::RawBytes(_) => "RawBytes".to_string(), } @@ -470,7 +470,7 @@ impl StoredValue { StoredValue::MessageTopic(_) => StoredValueTag::MessageTopic, StoredValue::Message(_) => StoredValueTag::Message, StoredValue::NamedKey(_) => StoredValueTag::NamedKey, - StoredValue::Prepaid(_) => StoredValueTag::Reservation, + StoredValue::Prepayment(_) => StoredValueTag::Prepayment, StoredValue::EntryPoint(_) => StoredValueTag::EntryPoint, StoredValue::RawBytes(_) => StoredValueTag::RawBytes, } @@ -779,7 +779,7 @@ impl ToBytes for StoredValue { } StoredValue::Message(message_digest) => message_digest.serialized_length(), StoredValue::NamedKey(named_key_value) => named_key_value.serialized_length(), - StoredValue::Prepaid(reservation_kind) => reservation_kind.serialized_length(), + StoredValue::Prepayment(prepayment_kind) => prepayment_kind.serialized_length(), StoredValue::EntryPoint(entry_point_value) => entry_point_value.serialized_length(), StoredValue::RawBytes(bytes) => bytes.serialized_length(), } @@ -808,7 +808,7 @@ impl ToBytes for StoredValue { } StoredValue::Message(message_digest) => message_digest.write_bytes(writer), StoredValue::NamedKey(named_key_value) => named_key_value.write_bytes(writer), - StoredValue::Prepaid(reservation_kind) => reservation_kind.write_bytes(writer), + StoredValue::Prepayment(prepayment_kind) => prepayment_kind.write_bytes(writer), StoredValue::EntryPoint(entry_point_value) => entry_point_value.write_bytes(writer), StoredValue::RawBytes(bytes) => bytes.write_bytes(writer), } @@ -912,7 +912,7 @@ mod serde_helpers { MessageTopic(&'a MessageTopicSummary), Message(&'a MessageChecksum), NamedKey(&'a NamedKeyValue), - Reservation(&'a PrepaidKind), + Prepayment(&'a PrepaymentKind), EntryPoint(&'a EntryPointValue), /// Raw bytes. RawBytes(Bytes), @@ -974,7 +974,7 @@ mod serde_helpers { HumanReadableSerHelper::Message(message_digest) } StoredValue::NamedKey(payload) => HumanReadableSerHelper::NamedKey(payload), - StoredValue::Prepaid(payload) => HumanReadableSerHelper::Reservation(payload), + StoredValue::Prepayment(payload) => HumanReadableSerHelper::Prepayment(payload), StoredValue::EntryPoint(payload) => HumanReadableSerHelper::EntryPoint(payload), StoredValue::RawBytes(bytes) => { HumanReadableSerHelper::RawBytes(bytes.as_slice().into()) diff --git a/types/src/system/prepayment.rs b/types/src/system/prepayment.rs index 3b94f698bf..2ac4f1dbf2 100644 --- a/types/src/system/prepayment.rs +++ b/types/src/system/prepayment.rs @@ -1,4 +1,4 @@ //! Contains implementation of the gas prepayment system -mod prepaid_kind; +mod prepayment_kind; -pub use prepaid_kind::PrepaidKind; +pub use prepayment_kind::PrepaymentKind; diff --git a/types/src/system/prepayment/prepaid_kind.rs b/types/src/system/prepayment/prepayment_kind.rs similarity index 95% rename from types/src/system/prepayment/prepaid_kind.rs rename to types/src/system/prepayment/prepayment_kind.rs index c89284f813..179e8c2e89 100644 --- a/types/src/system/prepayment/prepaid_kind.rs +++ b/types/src/system/prepayment/prepayment_kind.rs @@ -14,13 +14,13 @@ use serde::{Deserialize, Serialize}; #[derive(Eq, PartialEq, Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "datasize", derive(DataSize))] #[cfg_attr(feature = "json-schema", derive(JsonSchema))] -pub struct PrepaidKind { +pub struct PrepaymentKind { receipt: Digest, prepayment_kind: u8, prepayment_data: Bytes, } -impl ToBytes for PrepaidKind { +impl ToBytes for PrepaymentKind { fn to_bytes(&self) -> Result, bytesrepr::Error> { let mut buffer = bytesrepr::allocate_buffer(self)?; self.write_bytes(&mut buffer)?; diff --git a/types/src/transaction/pricing_mode.rs b/types/src/transaction/pricing_mode.rs index 73f51c9163..af7da31a9d 100644 --- a/types/src/transaction/pricing_mode.rs +++ b/types/src/transaction/pricing_mode.rs @@ -411,7 +411,7 @@ impl Display for PricingMode { payment_amount, gas_price, standard_payment ) } - PricingMode::Prepaid { receipt } => write!(formatter, "reserved: {}", receipt), + PricingMode::Prepaid { receipt } => write!(formatter, "prepaid: {}", receipt), PricingMode::Fixed { gas_price_tolerance, additional_computation_factor, From 91feaa4a031c7d013d0b691fee644943741b2cb1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maciej=20W=C3=B3jcik?= Date: Thu, 5 Dec 2024 11:21:19 +0100 Subject: [PATCH 2/3] remove dummy file --- storage/src/system/auction/detail.rs.orig | 1249 --------------------- 1 file changed, 1249 deletions(-) delete mode 100644 storage/src/system/auction/detail.rs.orig diff --git a/storage/src/system/auction/detail.rs.orig b/storage/src/system/auction/detail.rs.orig deleted file mode 100644 index a9ed98b849..0000000000 --- a/storage/src/system/auction/detail.rs.orig +++ /dev/null @@ -1,1249 +0,0 @@ -use std::{collections::BTreeMap, convert::TryInto, ops::Mul}; - -use num_rational::Ratio; - -use casper_types::{ - account::AccountHash, - bytesrepr::{FromBytes, ToBytes}, - system::auction::{ - BidAddr, BidKind, Delegator, DelegatorBids, Error, Reservation, Reservations, - SeigniorageAllocation, SeigniorageRecipientV2, SeigniorageRecipientsSnapshotV1, - SeigniorageRecipientsSnapshotV2, SeigniorageRecipientsV2, UnbondingPurse, UnbondingPurses, - ValidatorBid, ValidatorBids, ValidatorCredit, ValidatorCredits, AUCTION_DELAY_KEY, - DELEGATION_RATE_DENOMINATOR, ERA_END_TIMESTAMP_MILLIS_KEY, ERA_ID_KEY, - SEIGNIORAGE_RECIPIENTS_SNAPSHOT_KEY, UNBONDING_DELAY_KEY, VALIDATOR_SLOTS_KEY, - }, - ApiError, CLTyped, EraId, Key, KeyTag, PublicKey, URef, U512, -}; -use tracing::{debug, error, warn}; - -use super::{ - Auction, EraValidators, MintProvider, RuntimeProvider, StorageProvider, ValidatorWeights, -}; - -/// Maximum length of bridge records chain. -/// Used when looking for the most recent bid record to avoid unbounded computations. -const MAX_BRIDGE_CHAIN_LENGTH: u64 = 20; - -fn read_from(provider: &mut P, name: &str) -> Result -where - P: StorageProvider + RuntimeProvider + ?Sized, - T: FromBytes + CLTyped, -{ - let key = match provider.named_keys_get(name) { - None => { - error!("auction missing named key {:?}", name); - return Err(Error::MissingKey); - } - Some(key) => key, - }; - let uref = key.into_uref().ok_or(Error::InvalidKeyVariant)?; - let value: T = provider.read(uref)?.ok_or(Error::MissingValue)?; - Ok(value) -} - -fn write_to(provider: &mut P, name: &str, value: T) -> Result<(), Error> -where - P: StorageProvider + RuntimeProvider + ?Sized, - T: ToBytes + CLTyped, -{ - let key = provider.named_keys_get(name).ok_or(Error::MissingKey)?; - let uref = key.into_uref().ok_or(Error::InvalidKeyVariant)?; - provider.write(uref, value) -} - -/// Aggregated bid data for a Validator. -#[derive(Debug, Default)] -pub struct ValidatorBidsDetail { - validator_bids: ValidatorBids, - validator_credits: ValidatorCredits, - delegator_bids: DelegatorBids, - reservations: Reservations, -} - -impl ValidatorBidsDetail { - /// Ctor. - pub fn new() -> Self { - ValidatorBidsDetail { - validator_bids: BTreeMap::new(), - validator_credits: BTreeMap::new(), - delegator_bids: BTreeMap::new(), - reservations: BTreeMap::new(), - } - } - - /// Inserts a validator bid. - pub fn insert_bid( - &mut self, - validator: PublicKey, - validator_bid: Box, - delegators: Vec>, - reservations: Vec>, - ) -> Option> { - self.delegator_bids.insert(validator.clone(), delegators); - self.reservations.insert(validator.clone(), reservations); - self.validator_bids.insert(validator, validator_bid) - } - - /// Inserts a validator credit. - pub fn insert_credit( - &mut self, - validator: PublicKey, - era_id: EraId, - validator_credit: Box, - ) { - let credits = &mut self.validator_credits; - - credits - .entry(validator.clone()) - .and_modify(|inner| { - inner - .entry(era_id) - .and_modify(|_| { - warn!( - ?validator, - ?era_id, - "multiple validator credit entries in same era" - ) - }) - .or_insert(validator_credit.clone()); - }) - .or_insert_with(|| { - let mut inner = BTreeMap::new(); - inner.insert(era_id, validator_credit); - inner - }); - } - - /// Get validator weights. - #[allow(clippy::too_many_arguments)] - pub fn validator_weights( - &mut self, - era_ending: EraId, - era_end_timestamp_millis: u64, - vesting_schedule_period_millis: u64, - locked: bool, - include_credits: bool, - cap: Ratio, - ) -> Result { - let mut ret = BTreeMap::new(); - - for (validator_public_key, bid) in self.validator_bids.iter().filter(|(_, v)| { - locked - == v.is_locked_with_vesting_schedule( - era_end_timestamp_millis, - vesting_schedule_period_millis, - ) - && !v.inactive() - }) { - let mut staked_amount = bid.staked_amount(); - if let Some(delegators) = self.delegator_bids.get(validator_public_key) { - staked_amount = staked_amount - .checked_add(delegators.iter().map(|d| d.staked_amount()).sum()) - .ok_or(Error::InvalidAmount)?; - } - - let credit_amount = self.credit_amount( - validator_public_key, - era_ending, - staked_amount, - include_credits, - cap, - ); - let total = staked_amount.saturating_add(credit_amount); - ret.insert(validator_public_key.clone(), total); - } - - Ok(ret) - } - - fn credit_amount( - &self, - validator_public_key: &PublicKey, - era_ending: EraId, - staked_amount: U512, - include_credit: bool, - cap: Ratio, - ) -> U512 { - if !include_credit { - return U512::zero(); - } - - if let Some(inner) = self.validator_credits.get(validator_public_key) { - if let Some(credit) = inner.get(&era_ending) { - let capped = Ratio::new_raw(staked_amount, U512::one()) - .mul(cap) - .to_integer(); - let credit_amount = credit.amount(); - return credit_amount.min(capped); - } - } - - U512::zero() - } - - pub(crate) fn validator_bids(&self) -> &ValidatorBids { - &self.validator_bids - } - - pub(crate) fn validator_bids_mut(&mut self) -> &mut ValidatorBids { - &mut self.validator_bids - } - - /// Consume self into in underlying collections. - pub fn destructure(self) -> (ValidatorBids, ValidatorCredits, DelegatorBids, Reservations) { - ( - self.validator_bids, - self.validator_credits, - self.delegator_bids, - self.reservations, - ) - } -} - -/// Prunes away all validator credits for the imputed era, which should be the era ending. -/// -/// This is intended to be called at the end of an era, after calculating validator weights. -pub fn prune_validator_credits

( - provider: &mut P, - era_ending: EraId, - validator_credits: &ValidatorCredits, -) where - P: StorageProvider + RuntimeProvider + ?Sized, -{ - for (validator_public_key, inner) in validator_credits { - if inner.contains_key(&era_ending) { - provider.prune_bid(BidAddr::new_credit(validator_public_key, era_ending)) - } - } -} - -/// Returns the imputed validator bids. -pub fn get_validator_bids

(provider: &mut P, era_id: EraId) -> Result -where - P: StorageProvider + RuntimeProvider + ?Sized, -{ - let bids_keys = provider.get_keys(&KeyTag::BidAddr)?; - - let mut ret = ValidatorBidsDetail::new(); - - for key in bids_keys { - match provider.read_bid(&key)? { - Some(BidKind::Validator(validator_bid)) => { - let validator_public_key = validator_bid.validator_public_key(); - let delegator_bids = delegators(provider, validator_public_key)?; - let reservations = reservations(provider, validator_public_key)?; - ret.insert_bid( - validator_public_key.clone(), - validator_bid, - delegator_bids, - reservations, - ); - } - Some(BidKind::Credit(credit)) => { - ret.insert_credit(credit.validator_public_key().clone(), era_id, credit); - } - Some(_) => { - // noop - } - None => return Err(Error::ValidatorNotFound), - }; - } - - Ok(ret) -} - -/// Sets the imputed validator bids. -pub fn set_validator_bids

(provider: &mut P, validators: ValidatorBids) -> Result<(), Error> -where - P: StorageProvider + RuntimeProvider + ?Sized, -{ - for (validator_public_key, validator_bid) in validators.into_iter() { - let bid_addr = BidAddr::from(validator_public_key.clone()); - provider.write_bid(bid_addr.into(), BidKind::Validator(validator_bid))?; - } - Ok(()) -} - -/// Returns the unbonding purses. -pub fn get_unbonding_purses

(provider: &mut P) -> Result -where - P: StorageProvider + RuntimeProvider + ?Sized, -{ - let unbond_keys = provider.get_keys(&KeyTag::Unbond)?; - - let mut ret = BTreeMap::new(); - - for key in unbond_keys { - let account_hash = match key { - Key::Unbond(account_hash) => account_hash, - _ => return Err(Error::InvalidKeyVariant), - }; - let unbonding_purses = provider.read_unbonds(&account_hash)?; - ret.insert(account_hash, unbonding_purses); - } - - Ok(ret) -} - -/// Sets the unbonding purses. -pub fn set_unbonding_purses

( - provider: &mut P, - unbonding_purses: UnbondingPurses, -) -> Result<(), Error> -where - P: StorageProvider + RuntimeProvider + ?Sized, -{ - for (account_hash, unbonding_purses) in unbonding_purses.into_iter() { - provider.write_unbonds(account_hash, unbonding_purses)?; - } - Ok(()) -} - -/// Returns the era id. -pub fn get_era_id

(provider: &mut P) -> Result -where - P: StorageProvider + RuntimeProvider + ?Sized, -{ - read_from(provider, ERA_ID_KEY) -} - -/// Sets the era id. -pub fn set_era_id

(provider: &mut P, era_id: EraId) -> Result<(), Error> -where - P: StorageProvider + RuntimeProvider + ?Sized, -{ - write_to(provider, ERA_ID_KEY, era_id) -} - -/// Returns the era end timestamp. -pub fn get_era_end_timestamp_millis

(provider: &mut P) -> Result -where - P: StorageProvider + RuntimeProvider + ?Sized, -{ - read_from(provider, ERA_END_TIMESTAMP_MILLIS_KEY) -} - -/// Sets the era end timestamp. -pub fn set_era_end_timestamp_millis

( - provider: &mut P, - era_end_timestamp_millis: u64, -) -> Result<(), Error> -where - P: StorageProvider + RuntimeProvider + ?Sized, -{ - write_to( - provider, - ERA_END_TIMESTAMP_MILLIS_KEY, - era_end_timestamp_millis, - ) -} - -/// Returns seigniorage recipients snapshot. -pub fn get_seigniorage_recipients_snapshot

( - provider: &mut P, -) -> Result -where - P: StorageProvider + RuntimeProvider + ?Sized, -{ - read_from(provider, SEIGNIORAGE_RECIPIENTS_SNAPSHOT_KEY) -} - -pub fn get_legacy_seigniorage_recipients_snapshot

( - provider: &mut P, -) -> Result -where - P: StorageProvider + RuntimeProvider + ?Sized, -{ - read_from(provider, SEIGNIORAGE_RECIPIENTS_SNAPSHOT_KEY) -} - -/// Set seigniorage recipients snapshot. -pub fn set_seigniorage_recipients_snapshot

( - provider: &mut P, - snapshot: SeigniorageRecipientsSnapshotV2, -) -> Result<(), Error> -where - P: StorageProvider + RuntimeProvider + ?Sized, -{ - write_to(provider, SEIGNIORAGE_RECIPIENTS_SNAPSHOT_KEY, snapshot) -} - -/// Returns the number of validator slots. -pub fn get_validator_slots

(provider: &mut P) -> Result -where - P: StorageProvider + RuntimeProvider + ?Sized, -{ - let validator_slots: u32 = match read_from(provider, VALIDATOR_SLOTS_KEY) { - Ok(ret) => ret, - Err(err) => { - error!("Failed to find VALIDATOR_SLOTS_KEY {}", err); - return Err(err); - } - }; - let validator_slots = validator_slots - .try_into() - .map_err(|_| Error::InvalidValidatorSlotsValue)?; - Ok(validator_slots) -} - -/// Returns auction delay. -pub fn get_auction_delay

(provider: &mut P) -> Result -where - P: StorageProvider + RuntimeProvider + ?Sized, -{ - let auction_delay: u64 = match read_from(provider, AUCTION_DELAY_KEY) { - Ok(ret) => ret, - Err(err) => { - error!("Failed to find AUCTION_DELAY_KEY {}", err); - return Err(err); - } - }; - Ok(auction_delay) -} - -fn get_unbonding_delay

(provider: &mut P) -> Result -where - P: StorageProvider + RuntimeProvider + ?Sized, -{ - read_from(provider, UNBONDING_DELAY_KEY) -} - -/// Iterates over unbonding entries and checks if a locked amount can be paid already if -/// a specific era is reached. -/// -/// This function can be called by the system only. -pub fn process_unbond_requests( - provider: &mut P, - max_delegators_per_validator: u32, -) -> Result<(), ApiError> { - if provider.get_caller() != PublicKey::System.to_account_hash() { - return Err(Error::InvalidCaller.into()); - } - - // Update `unbonding_purses` data - let mut unbonding_purses: UnbondingPurses = get_unbonding_purses(provider)?; - - let current_era_id = provider.read_era_id()?; - - let unbonding_delay = get_unbonding_delay(provider)?; - - for unbonding_list in unbonding_purses.values_mut() { - let mut new_unbonding_list = Vec::new(); - - for unbonding_purse in unbonding_list.iter() { - // Since `process_unbond_requests` is run before `run_auction`, we should check if - // current era id + unbonding delay is equal or greater than the `era_of_creation` that - // was calculated on `unbond` attempt. - if current_era_id >= unbonding_purse.era_of_creation() + unbonding_delay { - let redelegation_result = - handle_redelegation(provider, unbonding_purse, max_delegators_per_validator) - .map_err(|err| { - error!(?err, ?unbonding_purse, "error processing unbond"); - err - })?; - match redelegation_result { - UnbondRedelegationOutcome::SuccessfullyRedelegated => { - // noop; on successful redelegation, no actual unbond occurs - } - uro @ UnbondRedelegationOutcome::NonexistantRedelegationTarget - | uro @ UnbondRedelegationOutcome::DelegationAmountBelowCap - | uro @ UnbondRedelegationOutcome::DelegationAmountAboveCap - | uro @ UnbondRedelegationOutcome::RedelegationTargetHasNoVacancy - | uro @ UnbondRedelegationOutcome::RedelegationTargetIsUnstaked - | uro @ UnbondRedelegationOutcome::Withdrawal => { - // Move funds from bid purse to unbonding purse - provider.unbond(unbonding_purse).map_err(|err| { - error!(?err, ?uro, "error unbonding purse"); - ApiError::from(Error::TransferToUnbondingPurse) - })? - } - } - } else { - new_unbonding_list.push(unbonding_purse.clone()); - } - } - *unbonding_list = new_unbonding_list; - } - - set_unbonding_purses(provider, unbonding_purses)?; - Ok(()) -} - -/// Creates a new purse in unbonding_purses given a validator's key, amount, and a destination -/// unbonding purse. Returns the amount of motes remaining in the validator's bid purse. -pub fn create_unbonding_purse( - provider: &mut P, - validator_public_key: PublicKey, - unbonder_public_key: PublicKey, - bonding_purse: URef, - amount: U512, - new_validator: Option, -) -> Result<(), Error> { - if provider - .available_balance(bonding_purse)? - .unwrap_or_default() - < amount - { - return Err(Error::UnbondTooLarge); - } - - let account_hash = AccountHash::from(&unbonder_public_key); - let mut unbonding_purses = provider.read_unbonds(&account_hash)?; - let era_of_creation = provider.read_era_id()?; - let new_unbonding_purse = UnbondingPurse::new( - bonding_purse, - validator_public_key, - unbonder_public_key, - era_of_creation, - amount, - new_validator, - ); - unbonding_purses.push(new_unbonding_purse); - provider.write_unbonds(account_hash, unbonding_purses)?; - - Ok(()) -} - -/// Returns most recent validator public key if public key has been changed -/// or the validator has withdrawn their bid completely. -pub fn get_most_recent_validator_public_key

( - provider: &mut P, - mut validator_public_key: PublicKey, -) -> Result -where - P: RuntimeProvider + StorageProvider, -{ - let mut validator_bid_addr = BidAddr::from(validator_public_key.clone()); - let mut found_validator_bid_chain_tip = false; - for _ in 0..MAX_BRIDGE_CHAIN_LENGTH { - match provider.read_bid(&validator_bid_addr.into())? { - Some(BidKind::Validator(validator_bid)) => { - validator_public_key = validator_bid.validator_public_key().clone(); - found_validator_bid_chain_tip = true; - break; - } - Some(BidKind::Bridge(bridge)) => { - validator_public_key = bridge.new_validator_public_key().clone(); - validator_bid_addr = BidAddr::from(validator_public_key.clone()); - } - _ => { - // Validator has withdrawn their bid, so there's nothing at the tip. - // In this case we add the reward to a delegator's unbond. - found_validator_bid_chain_tip = true; - break; - } - }; - } - if !found_validator_bid_chain_tip { - Err(Error::BridgeRecordChainTooLong) - } else { - Ok(validator_public_key) - } -} - -/// Attempts to apply the delegator reward to the existing stake. If the reward recipient has -/// completely unstaked, applies it to their unbond instead. In either case, returns -/// the purse the amount should be applied to. -pub fn distribute_delegator_rewards

( - provider: &mut P, - seigniorage_allocations: &mut Vec, - validator_public_key: PublicKey, - rewards: impl IntoIterator, -) -> Result, Error> -where - P: RuntimeProvider + StorageProvider, -{ - let mut delegator_payouts = Vec::new(); - for (delegator_public_key, delegator_reward_trunc) in rewards { - let bid_key = - BidAddr::new_from_public_keys(&validator_public_key, Some(&delegator_public_key)) - .into(); - - let delegator_bonding_purse = match read_delegator_bid(provider, &bid_key) { - Ok(mut delegator_bid) if !delegator_bid.staked_amount().is_zero() => { - let purse = *delegator_bid.bonding_purse(); - delegator_bid.increase_stake(delegator_reward_trunc)?; - provider.write_bid(bid_key, BidKind::Delegator(delegator_bid))?; - purse - } - Ok(_) | Err(Error::DelegatorNotFound) => { - // check to see if there are unbond entries for this recipient - // (validator + delegator match), and if there are apply the amount - // to the unbond entry with the highest era. - let account_hash = delegator_public_key.to_account_hash(); - match provider.read_unbonds(&account_hash) { - Ok(mut unbonds) => { - match unbonds - .iter_mut() - .filter(|x| x.validator_public_key() == &validator_public_key) - .max_by(|x, y| x.era_of_creation().cmp(&y.era_of_creation())) - { - Some(unbond) => { - let purse = *unbond.bonding_purse(); - let new_amount = - unbond.amount().saturating_add(delegator_reward_trunc); - unbond.with_amount(new_amount); - provider.write_unbonds(account_hash, unbonds)?; - purse - } - None => { - return Err(Error::DelegatorNotFound); - } - } - } - Err(err) => return Err(err), - } - } - Err(err) => { - return Err(err); - } - }; - - delegator_payouts.push(( - delegator_public_key.to_account_hash(), - delegator_reward_trunc, - delegator_bonding_purse, - )); - - let allocation = SeigniorageAllocation::delegator( - delegator_public_key, - validator_public_key.clone(), - delegator_reward_trunc, - ); - - seigniorage_allocations.push(allocation); - } - - Ok(delegator_payouts) -} - -/// Attempts to apply the validator reward to the existing stake. If the reward recipient has -/// completely unstaked, applies it to their unbond instead. In either case, returns -/// the purse the amount should be applied to. -pub fn distribute_validator_rewards

( - provider: &mut P, - seigniorage_allocations: &mut Vec, - validator_public_key: PublicKey, - amount: U512, -) -> Result -where - P: StorageProvider, -{ - let bid_key: Key = BidAddr::from(validator_public_key.clone()).into(); - let bonding_purse = match read_current_validator_bid(provider, bid_key) { - Ok(mut validator_bid) => { - let purse = *validator_bid.bonding_purse(); - validator_bid.increase_stake(amount)?; - provider.write_bid(bid_key, BidKind::Validator(validator_bid))?; - purse - } - Err(Error::ValidatorNotFound) => { - // check to see if there are unbond entries for this recipient, and if there are - // apply the amount to the unbond entry with the highest era. - let account_hash = validator_public_key.to_account_hash(); - match provider.read_unbonds(&account_hash) { - Ok(mut unbonds) => { - match unbonds - .iter_mut() - .max_by(|x, y| x.era_of_creation().cmp(&y.era_of_creation())) - { - Some(unbond) => { - let purse = *unbond.bonding_purse(); - let new_amount = unbond.amount().saturating_add(amount); - unbond.with_amount(new_amount); - provider.write_unbonds(account_hash, unbonds)?; - purse - } - None => { - return Err(Error::ValidatorNotFound); - } - } - } - Err(err) => return Err(err), - } - } - Err(err) => return Err(err), - }; - - let allocation = SeigniorageAllocation::validator(validator_public_key, amount); - seigniorage_allocations.push(allocation); - Ok(bonding_purse) -} - -#[derive(Debug)] -enum UnbondRedelegationOutcome { - Withdrawal, - SuccessfullyRedelegated, - NonexistantRedelegationTarget, - RedelegationTargetHasNoVacancy, - RedelegationTargetIsUnstaked, - DelegationAmountBelowCap, - DelegationAmountAboveCap, -} - -fn handle_redelegation

( - provider: &mut P, - unbonding_purse: &UnbondingPurse, - max_delegators_per_validator: u32, -) -> Result -where - P: StorageProvider + MintProvider + RuntimeProvider, -{ - let redelegation_target_public_key = match unbonding_purse.new_validator() { - Some(public_key) => { - // get updated key if `ValidatorBid` public key was changed - let validator_bid_addr = BidAddr::from(public_key.clone()); - match read_current_validator_bid(provider, validator_bid_addr.into()) { - Ok(validator_bid) => validator_bid.validator_public_key().clone(), - Err(err) => { - error!(?err, ?unbonding_purse, redelegate_to=?public_key, "error redelegating"); - return Ok(UnbondRedelegationOutcome::NonexistantRedelegationTarget); - } - } - } - None => return Ok(UnbondRedelegationOutcome::Withdrawal), - }; - - let redelegation = handle_delegation( - provider, - unbonding_purse.unbonder_public_key().clone(), - redelegation_target_public_key, - *unbonding_purse.bonding_purse(), - *unbonding_purse.amount(), - max_delegators_per_validator, - ); - match redelegation { - Ok(_) => Ok(UnbondRedelegationOutcome::SuccessfullyRedelegated), - Err(ApiError::AuctionError(err)) if err == Error::BondTooSmall as u8 => { - Ok(UnbondRedelegationOutcome::RedelegationTargetIsUnstaked) - } - Err(ApiError::AuctionError(err)) if err == Error::DelegationAmountTooSmall as u8 => { - Ok(UnbondRedelegationOutcome::DelegationAmountBelowCap) - } - Err(ApiError::AuctionError(err)) if err == Error::DelegationAmountTooLarge as u8 => { - Ok(UnbondRedelegationOutcome::DelegationAmountAboveCap) - } - Err(ApiError::AuctionError(err)) if err == Error::ValidatorNotFound as u8 => { - Ok(UnbondRedelegationOutcome::NonexistantRedelegationTarget) - } - Err(ApiError::AuctionError(err)) if err == Error::ExceededDelegatorSizeLimit as u8 => { - Ok(UnbondRedelegationOutcome::RedelegationTargetHasNoVacancy) - } - Err(err) => Err(err), - } -} - -/// Checks if a reservation for a given delegator exists. -fn has_reservation

( - provider: &mut P, - delegator: &PublicKey, - validator: &PublicKey, -) -> Result -where - P: RuntimeProvider + StorageProvider + ?Sized, -{ - let reservation_bid_key = BidAddr::Reservation { - validator: AccountHash::from(validator), - delegator: AccountHash::from(delegator), - } - .into(); - if let Some(BidKind::Reservation(_)) = provider.read_bid(&reservation_bid_key)? { - Ok(true) - } else { - Ok(false) - } -} - -/// If specified validator exists, and if validator is not yet at max delegators count, processes -/// delegation. For a new delegation a delegator bid record will be created to track the delegation, -/// otherwise the existing tracking record will be updated. -#[allow(clippy::too_many_arguments)] -pub fn handle_delegation

( - provider: &mut P, - delegator_public_key: PublicKey, - validator_public_key: PublicKey, - source: URef, - amount: U512, - max_delegators_per_validator: u32, -) -> Result -where - P: StorageProvider + MintProvider + RuntimeProvider, -{ - if amount.is_zero() { - return Err(Error::BondTooSmall.into()); - } - - let validator_bid_addr = BidAddr::from(validator_public_key.clone()); - // is there such a validator? - let validator_bid = read_validator_bid(provider, &validator_bid_addr.into())?; - if amount < U512::from(validator_bid.minimum_delegation_amount()) { - return Err(Error::DelegationAmountTooSmall.into()); - } - if amount > U512::from(validator_bid.maximum_delegation_amount()) { - return Err(Error::DelegationAmountTooLarge.into()); - } - - // is there already a record for this delegator? - let delegator_bid_key = - BidAddr::new_from_public_keys(&validator_public_key, Some(&delegator_public_key)).into(); - - let (target, delegator_bid) = if let Some(BidKind::Delegator(mut delegator_bid)) = - provider.read_bid(&delegator_bid_key)? - { - delegator_bid.increase_stake(amount)?; - (*delegator_bid.bonding_purse(), delegator_bid) - } else { - // is this validator over the delegator limit - // or is there a reservation for given delegator public key? - let delegator_count = provider.delegator_count(&validator_bid_addr)?; - let reserved_slots_count = validator_bid.reserved_slots(); - let reservation_count = provider.reservation_count(&validator_bid_addr)?; - let has_reservation = - has_reservation(provider, &delegator_public_key, &validator_public_key)?; - if delegator_count >= (max_delegators_per_validator - reserved_slots_count) as usize - && !has_reservation - { - warn!( - %delegator_count, %max_delegators_per_validator, %reservation_count, %has_reservation, - "delegator_count {}, max_delegators_per_validator {}, reservation_count {}, has_reservation {}", - delegator_count, max_delegators_per_validator, reservation_count, has_reservation - ); - return Err(Error::ExceededDelegatorSizeLimit.into()); - } - - let bonding_purse = provider.create_purse()?; - let delegator_bid = Delegator::unlocked( - delegator_public_key, - amount, - bonding_purse, - validator_public_key, - ); - (bonding_purse, Box::new(delegator_bid)) - }; - - // transfer token to bonding purse - provider - .mint_transfer_direct( - Some(PublicKey::System.to_account_hash()), - source, - target, - amount, - None, - ) - .map_err(|_| Error::TransferToDelegatorPurse)? - .map_err(|mint_error| { - // Propagate mint contract's error that occured during execution of transfer - // entrypoint. This will improve UX in case of (for example) - // unapproved spending limit error. - ApiError::from(mint_error) - })?; - - let updated_amount = delegator_bid.staked_amount(); - provider.write_bid(delegator_bid_key, BidKind::Delegator(delegator_bid))?; - - Ok(updated_amount) -} - -<<<<<<< HEAD -/// If specified validator exists, and if validator is not yet at max reservations count, processes -/// reservation. For a new reservation a bid record will be created to track the reservation, -/// otherwise the existing tracking record will be updated. -#[allow(clippy::too_many_arguments)] -pub fn handle_add_reservation

(provider: &mut P, reservation: Reservation) -> Result<(), Error> -where - P: StorageProvider + MintProvider + RuntimeProvider, -{ - // is there such a validator? - let validator_bid_addr = BidAddr::from(reservation.validator_public_key().clone()); - let bid = read_validator_bid(provider, &validator_bid_addr.into())?; - - // is there already a record for this delegator? - let reservation_bid_key = BidAddr::Reservation { - validator: AccountHash::from(reservation.validator_public_key()), - delegator: AccountHash::from(reservation.delegator_public_key()), - } - .into(); - if provider.read_bid(&reservation_bid_key)?.is_none() { - // ensure reservation list has capacity to create a new reservation - let reservation_count = provider.reservation_count(&validator_bid_addr)?; - let reserved_slots = bid.reserved_slots() as usize; - if reservation_count >= reserved_slots { - warn!( - %reservation_count, %reserved_slots, - "reservation_count {}, reserved_slots {}", - reservation_count, reserved_slots - ); - return Err(Error::ExceededReservationsLimit); - } - }; - - // validate specified delegation rate - if reservation.delegation_rate() > &DELEGATION_RATE_DENOMINATOR { - return Err(Error::DelegationRateTooLarge); - } - - provider.write_bid( - reservation_bid_key, - BidKind::Reservation(Box::new(reservation)), - )?; - - Ok(()) -} - -/// Attempts to remove a reservation if one exists. If not it returns an error. -/// -/// If there is already a delegator bid associated with a given reservation it validates that -/// there are free public slots available. If not, it returns an error since the delegator -/// cannot be "downgraded". -pub fn handle_cancel_reservation

( - provider: &mut P, - validator: PublicKey, - delegator: PublicKey, - max_delegators_per_validator: u32, -) -> Result<(), Error> -where - P: StorageProvider + MintProvider + RuntimeProvider, -{ - // is there such a validator? - let validator_bid_addr = BidAddr::from(validator.clone()); - let validator_bid = read_validator_bid(provider, &validator_bid_addr.into())?; - - // is there a reservation for this delegator? - let reservation_bid_addr = BidAddr::Reservation { - validator: AccountHash::from(&validator), - delegator: AccountHash::from(&delegator), - }; - if provider.read_bid(&reservation_bid_addr.into())?.is_none() { - return Err(Error::ReservationNotFound); - } - - // is there such a delegator? - let delegator_bid_addr = BidAddr::new_from_public_keys(&validator, Some(&delegator)); - if read_delegator_bid(provider, &delegator_bid_addr.into()).is_ok() { - // is there a free public slot - let reserved_slots = validator_bid.reserved_slots(); - let delegator_count = provider.delegator_count(&validator_bid_addr)?; - let used_reservation_count = provider.used_reservation_count(&validator_bid_addr)?; - let normal_delegators = delegator_count - used_reservation_count; - let public_slots = max_delegators_per_validator - reserved_slots; - - // cannot "downgrade" a delegator if there are no free public slots available - if public_slots == normal_delegators as u32 { - return Err(Error::ExceededDelegatorSizeLimit); - } - } - - provider.prune_bid(reservation_bid_addr); - Ok(()) -} - -======= -/// Returns validator bid by key. ->>>>>>> feat-2.0 -pub fn read_validator_bid

(provider: &mut P, bid_key: &Key) -> Result, Error> -where - P: StorageProvider + ?Sized, -{ - if !bid_key.is_bid_addr_key() { - return Err(Error::InvalidKeyVariant); - } - if let Some(BidKind::Validator(validator_bid)) = provider.read_bid(bid_key)? { - Ok(validator_bid) - } else { - Err(Error::ValidatorNotFound) - } -} - -/// Returns current `ValidatorBid` in case the public key was changed. -pub fn read_current_validator_bid

( - provider: &mut P, - mut bid_key: Key, -) -> Result, Error> -where - P: StorageProvider + ?Sized, -{ - if !bid_key.is_bid_addr_key() { - return Err(Error::InvalidKeyVariant); - } - - for _ in 0..MAX_BRIDGE_CHAIN_LENGTH { - match provider.read_bid(&bid_key)? { - Some(BidKind::Validator(validator_bid)) => return Ok(validator_bid), - Some(BidKind::Bridge(bridge)) => { - debug!( - ?bid_key, - ?bridge, - "read_current_validator_bid: bridge found" - ); - let validator_bid_addr = BidAddr::from(bridge.new_validator_public_key().clone()); - bid_key = validator_bid_addr.into(); - } - _ => break, - } - } - Err(Error::ValidatorNotFound) -} - -/// Returns all delegator bids for imputed validator. -pub fn read_delegator_bids

( - provider: &mut P, - validator_public_key: &PublicKey, -) -> Result, Error> -where - P: RuntimeProvider + StorageProvider + ?Sized, -{ - let mut ret = vec![]; - let bid_addr = BidAddr::from(validator_public_key.clone()); - let delegator_bid_keys = provider.get_keys_by_prefix( - &bid_addr - .delegators_prefix() - .map_err(|_| Error::Serialization)?, - )?; - for delegator_bid_key in delegator_bid_keys { - let delegator_bid = read_delegator_bid(provider, &delegator_bid_key)?; - ret.push(*delegator_bid); - } - - Ok(ret) -} - -/// Returns delegator bid by key. -pub fn read_delegator_bid

(provider: &mut P, bid_key: &Key) -> Result, Error> -where - P: RuntimeProvider + ?Sized + StorageProvider, -{ - if !bid_key.is_bid_addr_key() { - return Err(Error::InvalidKeyVariant); - } - if let Some(BidKind::Delegator(delegator_bid)) = provider.read_bid(bid_key)? { - Ok(delegator_bid) - } else { - Err(Error::DelegatorNotFound) - } -} - -<<<<<<< HEAD -pub fn read_reservation_bids

( - provider: &mut P, - validator_public_key: &PublicKey, -) -> Result, Error> -where - P: RuntimeProvider + StorageProvider + ?Sized, -{ - let mut ret = vec![]; - let bid_addr = BidAddr::from(validator_public_key.clone()); - let reservation_bid_keys = provider.get_keys_by_prefix( - &bid_addr - .reservation_prefix() - .map_err(|_| Error::Serialization)?, - )?; - for reservation_bid_key in reservation_bid_keys { - let reservation_bid = read_reservation_bid(provider, &reservation_bid_key)?; - ret.push(*reservation_bid); - } - - Ok(ret) -} - -pub fn read_reservation_bid

(provider: &mut P, bid_key: &Key) -> Result, Error> -where - P: RuntimeProvider + ?Sized + StorageProvider, -{ - if !bid_key.is_bid_addr_key() { - return Err(Error::InvalidKeyVariant); - } - if let Some(BidKind::Reservation(reservation_bid)) = provider.read_bid(bid_key)? { - Ok(reservation_bid) - } else { - Err(Error::ReservationNotFound) - } -} - -======= -/// Applies seigniorage recipient changes. ->>>>>>> feat-2.0 -pub fn seigniorage_recipients( - validator_weights: &ValidatorWeights, - validator_bids: &ValidatorBids, - delegator_bids: &DelegatorBids, - reservations: &Reservations, -) -> Result { - let mut recipients = SeigniorageRecipientsV2::new(); - for (validator_public_key, validator_total_weight) in validator_weights { - // check if validator bid exists before processing. - let validator_bid = validator_bids - .get(validator_public_key) - .ok_or(Error::ValidatorNotFound)?; - // calculate delegator portion(s), if any - let mut delegators_weight = U512::zero(); - let mut delegators_stake = BTreeMap::new(); - if let Some(delegators) = delegator_bids.get(validator_public_key) { - for delegator_bid in delegators { - if delegator_bid.staked_amount().is_zero() { - continue; - } - let delegator_staked_amount = delegator_bid.staked_amount(); - delegators_weight = delegators_weight.saturating_add(delegator_staked_amount); - delegators_stake.insert( - delegator_bid.delegator_public_key().clone(), - delegator_staked_amount, - ); - } - } - - let mut reservation_delegation_rates = BTreeMap::new(); - if let Some(reservations) = reservations.get(validator_public_key) { - for reservation in reservations { - reservation_delegation_rates.insert( - reservation.delegator_public_key().clone(), - *reservation.delegation_rate(), - ); - } - } - - // determine validator's personal stake (total weight - sum of delegators weight) - let validator_stake = validator_total_weight.saturating_sub(delegators_weight); - let seigniorage_recipient = SeigniorageRecipientV2::new( - validator_stake, - *validator_bid.delegation_rate(), - delegators_stake, - reservation_delegation_rates, - ); - recipients.insert(validator_public_key.clone(), seigniorage_recipient); - } - Ok(recipients) -} - -/// Returns the era validators from a snapshot. -/// -/// This is `pub` as it is used not just in the relevant auction entry point, but also by the -/// engine state while directly querying for the era validators. -pub fn era_validators_from_snapshot(snapshot: SeigniorageRecipientsSnapshotV2) -> EraValidators { - snapshot - .into_iter() - .map(|(era_id, recipients)| { - let validator_weights = recipients - .into_iter() - .filter_map(|(public_key, bid)| bid.total_stake().map(|stake| (public_key, stake))) - .collect::(); - (era_id, validator_weights) - }) - .collect() -} - -/// Returns the era validators from a legacy snapshot. -pub(crate) fn era_validators_from_legacy_snapshot( - snapshot: SeigniorageRecipientsSnapshotV1, -) -> EraValidators { - snapshot - .into_iter() - .map(|(era_id, recipients)| { - let validator_weights = recipients - .into_iter() - .filter_map(|(public_key, bid)| bid.total_stake().map(|stake| (public_key, stake))) - .collect::(); - (era_id, validator_weights) - }) - .collect() -} - -/// Initializes the vesting schedule of provided bid if the provided timestamp is greater than -/// or equal to the bid's initial release timestamp and the bid is owned by a genesis -/// validator. -/// -/// Returns `true` if the provided bid's vesting schedule was initialized. -pub fn process_with_vesting_schedule

( - provider: &mut P, - validator_bid: &mut ValidatorBid, - timestamp_millis: u64, - vesting_schedule_period_millis: u64, -) -> Result -where - P: StorageProvider + RuntimeProvider + ?Sized, -{ - let validator_public_key = validator_bid.validator_public_key().clone(); - - let delegator_bids = read_delegator_bids(provider, &validator_public_key)?; - for mut delegator_bid in delegator_bids { - let delegator_staked_amount = delegator_bid.staked_amount(); - let delegator_vesting_schedule = match delegator_bid.vesting_schedule_mut() { - Some(vesting_schedule) => vesting_schedule, - None => continue, - }; - if timestamp_millis < delegator_vesting_schedule.initial_release_timestamp_millis() { - continue; - } - if delegator_vesting_schedule - .initialize_with_schedule(delegator_staked_amount, vesting_schedule_period_millis) - { - let delegator_bid_addr = BidAddr::new_from_public_keys( - &validator_public_key, - Some(delegator_bid.delegator_public_key()), - ); - provider.write_bid( - delegator_bid_addr.into(), - BidKind::Delegator(Box::new(delegator_bid)), - )?; - } - } - - let validator_staked_amount = validator_bid.staked_amount(); - let validator_vesting_schedule = match validator_bid.vesting_schedule_mut() { - Some(vesting_schedule) => vesting_schedule, - None => return Ok(false), - }; - if timestamp_millis < validator_vesting_schedule.initial_release_timestamp_millis() { - Ok(false) - } else { - Ok(validator_vesting_schedule - .initialize_with_schedule(validator_staked_amount, vesting_schedule_period_millis)) - } -} - -/// Returns all delegators for imputed validator. -pub fn delegators

( - provider: &mut P, - validator_public_key: &PublicKey, -) -> Result>, Error> -where - P: RuntimeProvider + ?Sized + StorageProvider, -{ - let mut ret = vec![]; - let bid_addr = BidAddr::from(validator_public_key.clone()); - let delegator_bid_keys = provider.get_keys_by_prefix( - &bid_addr - .delegators_prefix() - .map_err(|_| Error::Serialization)?, - )?; - - for delegator_bid_key in delegator_bid_keys { - let delegator = read_delegator_bid(provider, &delegator_bid_key)?; - ret.push(delegator); - } - - Ok(ret) -} - -pub fn reservations

( - provider: &mut P, - validator_public_key: &PublicKey, -) -> Result>, Error> -where - P: RuntimeProvider + ?Sized + StorageProvider, -{ - let mut ret = vec![]; - let bid_addr = BidAddr::from(validator_public_key.clone()); - let reservation_bid_keys = provider.get_keys_by_prefix( - &bid_addr - .reservation_prefix() - .map_err(|_| Error::Serialization)?, - )?; - - for reservation_bid_key in reservation_bid_keys { - let reservation = read_reservation_bid(provider, &reservation_bid_key)?; - ret.push(reservation); - } - - Ok(ret) -} From 1a9deaad8b7d7b1ad26e3dc790ca29d20bb70c20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maciej=20W=C3=B3jcik?= Date: Thu, 5 Dec 2024 14:08:58 +0100 Subject: [PATCH 3/3] update JSON schema --- resources/test/sse_data_schema.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/resources/test/sse_data_schema.json b/resources/test/sse_data_schema.json index a47357346d..9dcb7ae27c 100644 --- a/resources/test/sse_data_schema.json +++ b/resources/test/sse_data_schema.json @@ -3890,14 +3890,14 @@ "additionalProperties": false }, { - "description": "A reservation record.", + "description": "A prepayment record.", "type": "object", "required": [ - "Prepaid" + "Prepayment" ], "properties": { - "Prepaid": { - "$ref": "#/definitions/PrepaidKind" + "Prepayment": { + "$ref": "#/definitions/PrepaymentKind" } }, "additionalProperties": false @@ -4774,7 +4774,7 @@ } } }, - "PrepaidKind": { + "PrepaymentKind": { "description": "Container for bytes recording location, type and data for a gas pre payment", "type": "object", "required": [