Skip to content

Commit

Permalink
Add custom naming attribute to sbor for TimePrecision
Browse files Browse the repository at this point in the history
  • Loading branch information
talekhinezh committed Jan 6, 2024
1 parent 8acc196 commit 118d1d9
Show file tree
Hide file tree
Showing 12 changed files with 54 additions and 46 deletions.
4 changes: 2 additions & 2 deletions native-sdk/src/runtime/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ impl Runtime {
Ok(scrypto_decode(&rtn).unwrap())
}

pub fn current_time<Y, E>(api: &mut Y, precision: TimePrecision) -> Result<Instant, E>
pub fn current_time<Y, E>(api: &mut Y, precision: TimePrecisionV1) -> Result<Instant, E>
where
Y: ClientObjectApi<E>,
E: Debug + ScryptoCategorize + ScryptoDecode,
Expand All @@ -77,7 +77,7 @@ impl Runtime {
pub fn compare_against_current_time<Y, E>(
api: &mut Y,
instant: Instant,
precision: TimePrecision,
precision: TimePrecisionV1,
operator: TimeComparisonOperator,
) -> Result<bool, E>
where
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,22 +203,26 @@ pub struct ConsensusManagerStartInput {}

pub type ConsensusManagerStartOutput = ();

#[derive(Sbor, Copy, Clone, Debug, Eq, PartialEq)]
pub enum TimePrecision {
#[derive(Copy, Clone, Debug, Eq, PartialEq, Sbor)]
#[sbor(name = "TimePrecision")]
pub enum TimePrecisionV1 {
Minute,
}

#[derive(Sbor, Copy, Clone, Debug, Eq, PartialEq)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, Sbor)]
#[sbor(name = "TimePrecision")]
pub enum TimePrecisionV2 {
Minute,
Second,
}

pub type TimePrecision = TimePrecisionV2;

pub const CONSENSUS_MANAGER_GET_CURRENT_TIME_IDENT: &str = "get_current_time";

#[derive(Debug, Clone, Eq, PartialEq, Sbor)]
pub struct ConsensusManagerGetCurrentTimeInput {
pub precision: TimePrecision,
pub precision: TimePrecisionV1,
}

#[derive(Debug, Clone, Eq, PartialEq, Sbor)]
Expand All @@ -233,7 +237,7 @@ pub const CONSENSUS_MANAGER_COMPARE_CURRENT_TIME_IDENT: &str = "compare_current_
#[derive(Debug, Clone, Eq, PartialEq, ScryptoSbor)]
pub struct ConsensusManagerCompareCurrentTimeInput {
pub instant: Instant,
pub precision: TimePrecision,
pub precision: TimePrecisionV1,
pub operator: TimeComparisonOperator,
}

Expand Down
4 changes: 2 additions & 2 deletions radix-engine-tests/tests/blueprints/time.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use radix_engine_common::types::{Epoch, Round};
use radix_engine_interface::blueprints::consensus_manager::TimePrecision;
use radix_engine_interface::blueprints::consensus_manager::TimePrecisionV1;
use radix_engine_interface::time::UtcDateTime;
use scrypto_unit::*;

Expand Down Expand Up @@ -29,7 +29,7 @@ fn advancing_round_changes_app_facing_minute_resolution_clock() {
// Assert
assert_eq!(
test_runner
.get_current_time(TimePrecision::Minute)
.get_current_time(TimePrecisionV1::Minute)
.seconds_since_unix_epoch,
epoch_seconds_rounded_to_minutes
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use native_sdk::resource::NativeVault;
use native_sdk::runtime::Runtime;
use radix_engine_interface::api::*;
use radix_engine_interface::blueprints::access_controller::*;
use radix_engine_interface::blueprints::consensus_manager::TimePrecision;
use radix_engine_interface::blueprints::consensus_manager::TimePrecisionV1;
use radix_engine_interface::blueprints::resource::*;
use radix_engine_interface::time::TimeComparisonOperator;
use sbor::rust::boxed::Box;
Expand Down Expand Up @@ -153,7 +153,7 @@ impl TransitionMut<AccessControllerInitiateRecoveryAsRecoveryStateMachineInput>
_,
) => match self.timed_recovery_delay_in_minutes {
Some(delay_in_minutes) => {
let current_time = Runtime::current_time(api, TimePrecision::Minute)?;
let current_time = Runtime::current_time(api, TimePrecisionV1::Minute)?;
let timed_recovery_allowed_after = current_time
.add_minutes(delay_in_minutes as i64)
.map_or(access_controller_runtime_error!(TimeOverflow), |instant| {
Expand Down Expand Up @@ -454,7 +454,7 @@ impl TransitionMut<AccessControllerTimedConfirmRecoveryStateMachineInput>
let recovery_time_has_elapsed = Runtime::compare_against_current_time(
api,
timed_recovery_allowed_after.clone(),
TimePrecision::Minute,
TimePrecisionV1::Minute,
TimeComparisonOperator::Gte,
)?;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -708,14 +708,14 @@ impl ConsensusManagerBlueprint {
}

pub(crate) fn get_current_time_v1<Y>(
precision: TimePrecision,
precision: TimePrecisionV1,
api: &mut Y,
) -> Result<Instant, RuntimeError>
where
Y: ClientApi<RuntimeError>,
{
match precision {
TimePrecision::Minute => {
TimePrecisionV1::Minute => {
let handle = api.actor_open_field(
ACTOR_STATE_SELF,
ConsensusManagerField::ProposerMinuteTimestamp.into(),
Expand Down Expand Up @@ -780,15 +780,15 @@ impl ConsensusManagerBlueprint {

pub(crate) fn compare_current_time_v1<Y>(
other_arbitrary_precision_instant: Instant,
precision: TimePrecision,
precision: TimePrecisionV1,
operator: TimeComparisonOperator,
api: &mut Y,
) -> Result<bool, RuntimeError>
where
Y: ClientApi<RuntimeError>,
{
match precision {
TimePrecision::Minute => {
TimePrecisionV1::Minute => {
let other_epoch_minute = other_arbitrary_precision_instant
.seconds_since_unix_epoch
.checked_mul(MILLIS_IN_SECOND)
Expand Down
28 changes: 20 additions & 8 deletions sbor-derive-common/src/describe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,17 @@ fn handle_normal_describe(
let (impl_generics, ty_generics, where_clause, child_types, custom_type_kind_generic) =
build_describe_generics(&generics, &attrs, context_custom_type_kind)?;

let name = get_sbor_attribute_string_value(&attrs, "name")?;
let name_token_stream = if let Some(name) = name {
quote! {
#name
}
} else {
quote! {
stringify!(#ident)
}
};

let output = match data {
Data::Struct(s) => match &s.fields {
syn::Fields::Named(FieldsNamed { .. }) => {
Expand All @@ -135,10 +146,11 @@ fn handle_normal_describe(
..
} = process_fields_for_describe(&s.fields)?;
let unique_field_types: Vec<_> = get_unique_types(&unskipped_field_types);

quote! {
impl #impl_generics ::sbor::Describe <#custom_type_kind_generic> for #ident #ty_generics #where_clause {
const TYPE_ID: ::sbor::RustTypeId = ::sbor::RustTypeId::novel_with_code(
stringify!(#ident),
#name_token_stream,
// Here we really want to cause distinct types to have distinct hashes, whilst still supporting (most) recursive types.
// The code hash itself is pretty good for this, but if you allow generic types, it's not enough, as the same code can create
// different types depending on the generic types providing. Adding in the generic types' TYPE_IDs solves that issue.
Expand All @@ -155,7 +167,7 @@ fn handle_normal_describe(

fn type_data() -> ::sbor::TypeData<#custom_type_kind_generic, ::sbor::RustTypeId> {
::sbor::TypeData::struct_with_named_fields(
stringify!(#ident),
#name_token_stream,
::sbor::rust::vec![
#((#unskipped_field_name_strings, <#unskipped_field_types as ::sbor::Describe<#custom_type_kind_generic>>::TYPE_ID),)*
],
Expand All @@ -178,7 +190,7 @@ fn handle_normal_describe(
quote! {
impl #impl_generics ::sbor::Describe <#custom_type_kind_generic> for #ident #ty_generics #where_clause {
const TYPE_ID: ::sbor::RustTypeId = ::sbor::RustTypeId::novel_with_code(
stringify!(#ident),
#name_token_stream,
// Here we really want to cause distinct types to have distinct hashes, whilst still supporting (most) recursive types.
// The code hash itself is pretty good for this, but if you allow generic types, it's not enough, as the same code can create
// different types depending on the generic types providing. Adding in the generic types' TYPE_IDs solves that issue.
Expand All @@ -195,7 +207,7 @@ fn handle_normal_describe(

fn type_data() -> ::sbor::TypeData<#custom_type_kind_generic, ::sbor::RustTypeId> {
::sbor::TypeData::struct_with_unnamed_fields(
stringify!(#ident),
#name_token_stream,
::sbor::rust::vec![
#(<#unskipped_field_types as ::sbor::Describe<#custom_type_kind_generic>>::TYPE_ID,)*
],
Expand All @@ -212,13 +224,13 @@ fn handle_normal_describe(
quote! {
impl #impl_generics ::sbor::Describe <#custom_type_kind_generic> for #ident #ty_generics #where_clause {
const TYPE_ID: ::sbor::RustTypeId = ::sbor::RustTypeId::novel_with_code(
stringify!(#ident),
#name_token_stream,
&[#(<#child_types>::TYPE_ID,)*],
&#code_hash
);

fn type_data() -> ::sbor::TypeData<#custom_type_kind_generic, ::sbor::RustTypeId> {
::sbor::TypeData::struct_with_unit_fields(stringify!(#ident))
::sbor::TypeData::struct_with_unit_fields(#name_token_stream)
}
}
}
Expand Down Expand Up @@ -279,15 +291,15 @@ fn handle_normal_describe(
quote! {
impl #impl_generics ::sbor::Describe <#custom_type_kind_generic> for #ident #ty_generics #where_clause {
const TYPE_ID: ::sbor::RustTypeId = ::sbor::RustTypeId::novel_with_code(
stringify!(#ident),
#name_token_stream,
&[#(<#child_types>::TYPE_ID,)*],
&#code_hash
);

fn type_data() -> ::sbor::TypeData<#custom_type_kind_generic, ::sbor::RustTypeId> {
use ::sbor::rust::borrow::ToOwned;
::sbor::TypeData::enum_variants(
stringify!(#ident),
#name_token_stream,
::sbor::rust::prelude::indexmap![
#(#variant_discriminators => #variant_type_data,)*
],
Expand Down
2 changes: 1 addition & 1 deletion sbor-derive-common/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ fn parse_u8_from_literal(literal: &Lit) -> Option<u8> {
}
}

fn get_sbor_attribute_string_value(
pub fn get_sbor_attribute_string_value(
attributes: &[Attribute],
field_name: &str,
) -> Result<Option<String>> {
Expand Down
2 changes: 1 addition & 1 deletion scrypto-test/src/environment/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -788,7 +788,7 @@ impl TestEnvironment {

/// Gets the current time stamp from the Consensus Manager.
pub fn get_current_time(&mut self) -> Instant {
Runtime::current_time(self, TimePrecision::Minute).unwrap()
Runtime::current_time(self, TimePrecisionV1::Minute).unwrap()
}

pub fn set_current_time(&mut self, instant: Instant) {
Expand Down
4 changes: 2 additions & 2 deletions scrypto-unit/src/test_runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ use radix_engine_interface::blueprints::account::ACCOUNT_SECURIFY_IDENT;
use radix_engine_interface::blueprints::consensus_manager::{
ConsensusManagerConfig, ConsensusManagerGetCurrentEpochInput,
ConsensusManagerGetCurrentTimeInput, ConsensusManagerNextRoundInput, EpochChangeCondition,
LeaderProposalHistory, TimePrecision, CONSENSUS_MANAGER_GET_CURRENT_EPOCH_IDENT,
LeaderProposalHistory, TimePrecisionV1, CONSENSUS_MANAGER_GET_CURRENT_EPOCH_IDENT,
CONSENSUS_MANAGER_GET_CURRENT_TIME_IDENT, CONSENSUS_MANAGER_NEXT_ROUND_IDENT,
VALIDATOR_STAKE_AS_OWNER_IDENT,
};
Expand Down Expand Up @@ -2391,7 +2391,7 @@ impl<E: NativeVmExtension, D: TestDatabase> TestRunner<E, D> {
.into_latest()
}

pub fn get_current_time(&mut self, precision: TimePrecision) -> Instant {
pub fn get_current_time(&mut self, precision: TimePrecisionV1) -> Instant {
let receipt = self.execute_system_transaction(
vec![InstructionV1::CallMethod {
address: CONSENSUS_MANAGER.into(),
Expand Down
4 changes: 2 additions & 2 deletions scrypto/src/component/stubs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,11 @@ extern_blueprint_internal! {
{
fn get_current_epoch(&self) -> Epoch;
fn start(&mut self);
fn get_current_time(&self, precision: TimePrecision) -> Instant;
fn get_current_time(&self, precision: TimePrecisionV1) -> Instant;
fn compare_current_time(
&self,
instant: Instant,
precision: TimePrecision,
precision: TimePrecisionV1,
operator: TimeComparisonOperator,
) -> bool;
fn next_round(
Expand Down
20 changes: 6 additions & 14 deletions scrypto/src/runtime/clock.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use radix_engine_interface::blueprints::consensus_manager::{
ConsensusManagerCompareCurrentTimeInput, ConsensusManagerGetCurrentTimeInput,
ConsensusManagerGetCurrentTimeInputV2, TimePrecision, TimePrecisionV2,
CONSENSUS_MANAGER_COMPARE_CURRENT_TIME_IDENT, CONSENSUS_MANAGER_GET_CURRENT_TIME_IDENT,
ConsensusManagerCompareCurrentTimeInputV2, ConsensusManagerGetCurrentTimeInputV2,
TimePrecision, CONSENSUS_MANAGER_COMPARE_CURRENT_TIME_IDENT,
CONSENSUS_MANAGER_GET_CURRENT_TIME_IDENT,
};
use radix_engine_interface::constants::CONSENSUS_MANAGER;
use radix_engine_interface::data::scrypto::{scrypto_decode, scrypto_encode};
Expand All @@ -16,15 +16,7 @@ pub struct Clock {}
impl Clock {
/// Returns the current timestamp (in seconds)
pub fn current_time_rounded_to_seconds() -> Instant {
let rtn = ScryptoVmV1Api::object_call(
CONSENSUS_MANAGER.as_node_id(),
CONSENSUS_MANAGER_GET_CURRENT_TIME_IDENT,
scrypto_encode(&ConsensusManagerGetCurrentTimeInputV2 {
precision: TimePrecisionV2::Second,
})
.unwrap(),
);
scrypto_decode(&rtn).unwrap()
Self::current_time(TimePrecision::Second)
}

/// Returns the current timestamp (in seconds), rounded down to minutes
Expand All @@ -37,7 +29,7 @@ impl Clock {
let rtn = ScryptoVmV1Api::object_call(
CONSENSUS_MANAGER.as_node_id(),
CONSENSUS_MANAGER_GET_CURRENT_TIME_IDENT,
scrypto_encode(&ConsensusManagerGetCurrentTimeInput { precision }).unwrap(),
scrypto_encode(&ConsensusManagerGetCurrentTimeInputV2 { precision }).unwrap(),
);
scrypto_decode(&rtn).unwrap()
}
Expand Down Expand Up @@ -77,7 +69,7 @@ impl Clock {
let rtn = ScryptoVmV1Api::object_call(
CONSENSUS_MANAGER.as_node_id(),
CONSENSUS_MANAGER_COMPARE_CURRENT_TIME_IDENT,
scrypto_encode(&ConsensusManagerCompareCurrentTimeInput {
scrypto_encode(&ConsensusManagerCompareCurrentTimeInputV2 {
instant,
precision,
operator,
Expand Down
4 changes: 2 additions & 2 deletions simulator/src/resim/cmd_show_ledger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ impl ShowLedger {
)
.map_err(Error::IOError)?;

let instant = Self::get_current_time(out, TimePrecision::Minute)?;
let instant = Self::get_current_time(out, TimePrecisionV1::Minute)?;
let date_time = UtcDateTime::from_instant(&instant).unwrap();
writeln!(
out,
Expand Down Expand Up @@ -127,7 +127,7 @@ impl ShowLedger {

pub fn get_current_time<O: std::io::Write>(
out: &mut O,
precision: TimePrecision,
precision: TimePrecisionV1,
) -> Result<Instant, Error> {
let instructions = vec![InstructionV1::CallMethod {
address: CONSENSUS_MANAGER.into(),
Expand Down

0 comments on commit 118d1d9

Please sign in to comment.