Skip to content

Commit

Permalink
SlotIndex and EpochIndex as u32 (#1337)
Browse files Browse the repository at this point in the history
* SlotIndex and EpochIndex as u32

* Clippy

* Nodejs changes

* Use ::LENGTH

* Some test fixes

* Comment out tests for now

* Update examples

---------

Co-authored-by: Thoralf Müller <[email protected]>
Co-authored-by: Thoralf-M <[email protected]>
  • Loading branch information
3 people authored Oct 11, 2023
1 parent 54e8ee6 commit 994defa
Show file tree
Hide file tree
Showing 27 changed files with 193 additions and 180 deletions.
4 changes: 2 additions & 2 deletions bindings/nodejs/examples/client/11-build-output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ async function run() {
addressUnlockCondition,
new ExpirationUnlockCondition(
new Ed25519Address(hexAddress),
BigInt(1),
1,
),
],
});
Expand All @@ -91,7 +91,7 @@ async function run() {
amount: BigInt(1000000),
unlockConditions: [
addressUnlockCondition,
new TimelockUnlockCondition(BigInt(1)),
new TimelockUnlockCondition(1),
],
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ async function run() {

// Create an output with amount 1_000_000 and a timelock of 1 hour
// TODO Make the slot index properly 1h ahead
const slotIndex = BigInt(1000);
const slotIndex = 1000;
const basicOutput = await client.buildBasicOutput({
unlockConditions: [
new AddressUnlockCondition(
Expand Down
4 changes: 2 additions & 2 deletions bindings/nodejs/examples/how_tos/outputs/unlock-conditions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ async function run() {
const basicOutputWithTimelock = await client.buildBasicOutput({
unlockConditions: [
addressUnlockCondition,
new TimelockUnlockCondition(BigInt(1)),
new TimelockUnlockCondition(1),
],
});

Expand All @@ -76,7 +76,7 @@ async function run() {
addressUnlockCondition,
new ExpirationUnlockCondition(
new Ed25519Address(hexAddress),
BigInt(1),
1,
),
],
});
Expand Down
9 changes: 5 additions & 4 deletions bindings/nodejs/lib/types/block/output/feature.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
BlockIssuerKeyDiscriminator,
} from './block-issuer-key';
import { u64 } from '../../utils/type-aliases';
import { EpochIndex } from '../../block/slot';

/**
* All of the feature block types.
Expand Down Expand Up @@ -144,17 +145,17 @@ class StakingFeature extends Feature {
/**
* The epoch index in which the staking started.
*/
readonly startEpoch: u64;
readonly startEpoch: EpochIndex;
/**
* The epoch index in which the staking ends.
*/
readonly endEpoch: u64;
readonly endEpoch: EpochIndex;

constructor(
stakedAmount: u64,
fixedCost: u64,
startEpoch: u64,
endEpoch: u64,
startEpoch: EpochIndex,
endEpoch: EpochIndex,
) {
super(FeatureType.Staking);
this.stakedAmount = stakedAmount;
Expand Down
9 changes: 5 additions & 4 deletions bindings/nodejs/lib/types/block/output/output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { HexEncodedString, hexToBigInt, u64 } from '../../utils';
import { TokenScheme, TokenSchemeDiscriminator } from './token-scheme';
import { INativeToken } from '../../models';
import { AccountId, DelegationId } from '../id';
import { EpochIndex } from '../../block/slot';

export type OutputId = string;

Expand Down Expand Up @@ -327,11 +328,11 @@ class DelegationOutput extends Output {
/**
* The index of the first epoch for which this output delegates.
*/
readonly startEpoch: u64;
readonly startEpoch: EpochIndex;
/**
* The index of the last epoch for which this output delegates.
*/
readonly endEpoch: u64;
readonly endEpoch: EpochIndex;
/**
* The unlock conditions for the output.
*/
Expand All @@ -354,8 +355,8 @@ class DelegationOutput extends Output {
delegatedAmount: u64,
delegationId: DelegationId,
validatorId: AccountId,
startEpoch: u64,
endEpoch: u64,
startEpoch: EpochIndex,
endEpoch: EpochIndex,
unlockConditions: UnlockCondition[],
) {
super(OutputType.Delegation, amount);
Expand Down
12 changes: 10 additions & 2 deletions bindings/nodejs/lib/types/block/slot/commitment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,15 @@ import { u64 } from '../..';
* To calculate the slot index of a timestamp, `genesisTimestamp` and the duration of a slot are needed.
* The slot index of timestamp `ts` is `(ts - genesisTimestamp)/duration + 1`.
*/
type SlotIndex = u64;
type SlotIndex = number;

/**
* The tangle timeline is divided into epochs, and each epoch has a corresponding epoch index.
* Epochs are further subdivided into slots, each with a `SlotIndex.
* To calculate the epoch index of a timestamp, `slotsPerEpochExponent` and `slotDurationInSeconds` are needed.
* An epoch consists of `2^slotsPerEpochExponent` slots.
*/
type EpochIndex = number;

/**
* Identifier of a slot commitment
Expand Down Expand Up @@ -59,4 +67,4 @@ class SlotCommitment {
}
}

export { SlotCommitment, SlotIndex, SlotCommitmentId, RootsId };
export { SlotCommitment, SlotIndex, EpochIndex, SlotCommitmentId, RootsId };
15 changes: 8 additions & 7 deletions bindings/nodejs/lib/types/models/info/node-info-protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import { u64 } from '../../utils';
import type { RentStructure } from '../rent-structure';
import { EpochIndex } from '../../block/slot';

/**
* The Protocol Info.
Expand All @@ -11,7 +12,7 @@ export interface ProtocolInfo {
/**
* The start epoch of the set of protocol parameters.
*/
startEpoch: string;
startEpoch: EpochIndex;
/**
* The protocol parameters.
*/
Expand Down Expand Up @@ -69,31 +70,31 @@ export interface ProtocolParameters {
/**
* The unbonding period in epochs before an account can stop staking.
*/
stakingUnbondingPeriod: u64;
stakingUnbondingPeriod: number;
/**
* The number of validation blocks that each validator should issue each slot.
*/
validationBlocksPerSlot: number;
/**
* The number of epochs worth of Mana that a node is punished with for each additional validation block it issues.
*/
punishmentEpochs: u64;
punishmentEpochs: number;
/**
* Determine if a block is eligible by evaluating issuingTime and commitments in its pastcone to ATT and lastCommittedSlot respectively.
*/
livenessThreshold: u64;
livenessThreshold: number;
/**
* MinCommittableAge is the minimum age relative to the accepted tangle time slot index that a slot can be committed.
*/
minCommittableAge: u64;
minCommittableAge: number;
/**
* MaxCommittableAge is the maximum age for a slot commitment to be included in a block relative to the slot index of the block issuing time.
*/
maxCommittableAge: u64;
maxCommittableAge: number;
/**
* Determine the slot that should trigger a new committee selection for the next and upcoming epoch.
*/
epochNearingThreshold: u64;
epochNearingThreshold: number;
/**
* Congestion Control Parameters defines the parameters used to calculate the Reference Mana Cost (RMC).
*/
Expand Down
10 changes: 6 additions & 4 deletions bindings/nodejs/lib/types/models/info/node-info-status.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Copyright 2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

import { SlotIndex, EpochIndex } from '../../block/slot';

/**
* Response from the /info endpoint.
*/
Expand Down Expand Up @@ -32,17 +34,17 @@ export interface INodeInfoStatus {
/**
* The index of latest finalized slot.
*/
latestFinalizedSlot: string;
latestFinalizedSlot: SlotIndex;
/**
* The slot index of the latest accepted block.
*/
latestAcceptedBlockSlot?: string;
latestAcceptedBlockSlot?: SlotIndex;
/**
* The slot index of the latest confirmed block.
*/
latestConfirmedBlockSlot?: string;
latestConfirmedBlockSlot?: SlotIndex;
/**
* The index of the epoch before which the tangle history is pruned.
*/
pruningEpoch: string;
pruningEpoch: EpochIndex;
}
2 changes: 1 addition & 1 deletion bindings/nodejs/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion bindings/nodejs/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4051,7 +4051,7 @@
"inherits" "^2.0.3"
"readable-stream" "^3.1.1"

"tar@^2.0.0", "tar@^4.4.19":
"tar@^4.4.19":
"integrity" "sha512-a20gEsvHnWe0ygBY8JbxoM4w3SJdhc7ZAuxkLqh+nvNQN2IOt0B5lLgM490X5Hl8FF0dl0tOf2ewFYAlIFgzVA=="
"resolved" "https://registry.npmjs.org/tar/-/tar-4.4.19.tgz"
"version" "4.4.19"
Expand Down
4 changes: 2 additions & 2 deletions sdk/src/types/api/plugins/participation/responses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,9 @@ impl OutputStatusResponse {
pub fn mock() -> Self {
Self {
participations: [(
ParticipationEventId::new([42; 32]),
ParticipationEventId::new([42; ParticipationEventId::LENGTH]),
TrackedParticipation {
block_id: BlockId::new([23; 40]),
block_id: BlockId::new([23; BlockId::LENGTH]),
amount: 100,
start_milestone_index: 1000,
end_milestone_index: 9999,
Expand Down
2 changes: 1 addition & 1 deletion sdk/src/types/block/block_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ pub struct BlockId {

impl BlockId {
/// The length of a [`BlockId`]
pub const LENGTH: usize = 40;
pub const LENGTH: usize = 36;

pub fn new(bytes: [u8; Self::LENGTH]) -> Self {
unsafe { core::mem::transmute(bytes) }
Expand Down
6 changes: 3 additions & 3 deletions sdk/src/types/block/output/unlock_condition/timelock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,14 @@ pub(crate) mod dto {
struct TimelockUnlockConditionDto {
#[serde(rename = "type")]
kind: u8,
slot_index: u64,
slot_index: SlotIndex,
}

impl From<&TimelockUnlockCondition> for TimelockUnlockConditionDto {
fn from(value: &TimelockUnlockCondition) -> Self {
Self {
kind: TimelockUnlockCondition::KIND,
slot_index: *value.slot_index(),
slot_index: value.slot_index(),
}
}
}
Expand All @@ -67,7 +67,7 @@ pub(crate) mod dto {
type Error = Error;

fn try_from(value: TimelockUnlockConditionDto) -> Result<Self, Error> {
Self::new(SlotIndex::from(value.slot_index)).map_err(|_| Error::InvalidField("timelockUnlockCondition"))
Self::new(value.slot_index).map_err(|_| Error::InvalidField("timelockUnlockCondition"))
}
}

Expand Down
24 changes: 9 additions & 15 deletions sdk/src/types/block/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,28 +55,22 @@ pub struct ProtocolParameters {
#[getset(skip)]
pub(crate) mana_structure: ManaStructure,
/// The unbonding period in epochs before an account can stop staking.
#[cfg_attr(feature = "serde", serde(with = "crate::utils::serde::string"))]
pub(crate) staking_unbonding_period: u64,
pub(crate) staking_unbonding_period: u32,
/// The number of validation blocks that each validator should issue each slot.
pub(crate) validation_blocks_per_slot: u16,
/// The number of epochs worth of Mana that a node is punished with for each additional validation block it issues.
#[cfg_attr(feature = "serde", serde(with = "crate::utils::serde::string"))]
pub(crate) punishment_epochs: u64,
pub(crate) punishment_epochs: u32,
/// Liveness Threshold is used by tip-selection to determine if a block is eligible by evaluating issuingTimes and
/// commitments in its past-cone to Accepted Tangle Time and lastCommittedSlot respectively.
#[cfg_attr(feature = "serde", serde(with = "crate::utils::serde::string"))]
pub(crate) liveness_threshold: u64,
pub(crate) liveness_threshold: u32,
/// Minimum age relative to the accepted tangle time slot index that a slot can be committed.
#[cfg_attr(feature = "serde", serde(with = "crate::utils::serde::string"))]
pub(crate) min_committable_age: u64,
pub(crate) min_committable_age: u32,
/// Maximum age for a slot commitment to be included in a block relative to the slot index of the block issuing
/// time.
#[cfg_attr(feature = "serde", serde(with = "crate::utils::serde::string"))]
pub(crate) max_committable_age: u64,
pub(crate) max_committable_age: u32,
/// Epoch Nearing Threshold is used by the epoch orchestrator to detect the slot that should trigger a new
/// committee selection for the next and upcoming epoch.
#[cfg_attr(feature = "serde", serde(with = "crate::utils::serde::string"))]
pub(crate) epoch_nearing_threshold: u64,
pub(crate) epoch_nearing_threshold: u32,
/// Parameters used to calculate the Reference Mana Cost (RMC).
pub(crate) congestion_control_parameters: CongestionControlParameters,
/// Defines the parameters used to signal a protocol parameters upgrade.
Expand Down Expand Up @@ -132,7 +126,7 @@ impl ProtocolParameters {
token_supply: u64,
genesis_unix_timestamp: u64,
slot_duration_in_seconds: u8,
epoch_nearing_threshold: u64,
epoch_nearing_threshold: u32,
) -> Result<Self, Error> {
Ok(Self {
version,
Expand Down Expand Up @@ -163,8 +157,8 @@ impl ProtocolParameters {
}

/// Returns the slots per epoch of the [`ProtocolParameters`].
pub fn slots_per_epoch(&self) -> u64 {
2_u64.pow(self.slots_per_epoch_exponent() as u32)
pub fn slots_per_epoch(&self) -> u32 {
2_u32.pow(self.slots_per_epoch_exponent() as u32)
}

/// Gets a [`SlotIndex`] from a unix timestamp.
Expand Down
5 changes: 3 additions & 2 deletions sdk/src/types/block/rand/output/feature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use crate::types::block::{
address::rand_address,
bytes::rand_bytes,
number::{rand_number, rand_number_range},
slot::{rand_epoch_index, rand_slot_index},
},
};

Expand Down Expand Up @@ -64,7 +65,7 @@ pub fn rand_block_issuer_keys(len: usize) -> BTreeSet<BlockIssuerKey> {
/// Generates a random [`BlockIssuerFeature`].
pub fn rand_block_issuer_feature() -> BlockIssuerFeature {
BlockIssuerFeature::new(
rand_number::<u64>(),
rand_slot_index(),
rand_block_issuer_keys(rand_number_range(
BlockIssuerKeys::COUNT_MIN as usize..=BlockIssuerKeys::COUNT_MAX as usize,
)),
Expand All @@ -74,7 +75,7 @@ pub fn rand_block_issuer_feature() -> BlockIssuerFeature {

/// Generates a random [`StakingFeature`].
pub fn rand_staking_feature() -> StakingFeature {
StakingFeature::new(rand_number(), rand_number(), rand_number::<u64>(), rand_number::<u64>())
StakingFeature::new(rand_number(), rand_number(), rand_epoch_index(), rand_epoch_index())
}

fn rand_feature_from_flag(flag: &FeatureFlags) -> Feature {
Expand Down
7 changes: 6 additions & 1 deletion sdk/src/types/block/rand/slot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

use crate::types::block::{
rand::{bytes::rand_bytes_array, number::rand_number},
slot::{SlotCommitmentId, SlotIndex},
slot::{EpochIndex, SlotCommitmentId, SlotIndex},
};

/// Generates a random slot commitment id.
Expand All @@ -15,3 +15,8 @@ pub fn rand_slot_commitment_id() -> SlotCommitmentId {
pub fn rand_slot_index() -> SlotIndex {
SlotIndex::new(rand_number())
}

/// Generates a random epoch index.
pub fn rand_epoch_index() -> EpochIndex {
EpochIndex::new(rand_number())
}
Loading

0 comments on commit 994defa

Please sign in to comment.