Skip to content

Commit

Permalink
Add classes for IDs with slot index (iotaledger#1962)
Browse files Browse the repository at this point in the history
* Add classes for IDs with slot index

* Extend String

* Fix test

* Replace HexEncodedString by IDs

* Replace more

* Separate OutputId more

---------

Co-authored-by: Thibault Martinez <[email protected]>
Co-authored-by: /alex/ <[email protected]>
  • Loading branch information
3 people authored Feb 8, 2024
1 parent 0e958a7 commit 1ce7d0c
Show file tree
Hide file tree
Showing 24 changed files with 138 additions and 58 deletions.
6 changes: 4 additions & 2 deletions bindings/nodejs/examples/client/04-get-output.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright 2021-2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

import { Client, initLogger } from '@iota/sdk';
import { Client, initLogger, OutputId } from '@iota/sdk';
require('dotenv').config({ path: '.env' });

// Run with command:
Expand All @@ -22,7 +22,9 @@ async function run() {
});
try {
const output = await client.getOutput(
'0x022aefa73dff09b35b21ab5493412b0d354ad07a970a12b71e8087c6f3a7b8660000',
new OutputId(
'0x022aefa73dff09b35b21ab5493412b0d354ad07a970a12b71e8087c6f3a7b866000000000000',
),
);
console.log('Output: ', output);
} catch (error) {
Expand Down
12 changes: 10 additions & 2 deletions bindings/nodejs/examples/client/05-get-address-balance.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
// Copyright 2021-2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

import { Client, CommonOutput, SecretManager, initLogger } from '@iota/sdk';
import {
Client,
CommonOutput,
SecretManager,
initLogger,
OutputId,
} from '@iota/sdk';
require('dotenv').config({ path: '.env' });

// Run with command:
Expand Down Expand Up @@ -45,7 +51,9 @@ async function run() {
});

// Get outputs by their IDs
const addressOutputs = await client.getOutputs(outputIdsResponse.items);
const addressOutputs = await client.getOutputs(
outputIdsResponse.items.map((id) => new OutputId(id)),
);

// Calculate the total amount and native tokens
let totalAmount = BigInt(0);
Expand Down
6 changes: 4 additions & 2 deletions bindings/nodejs/examples/how_tos/client/get-outputs.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright 2021-2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

import { Client, initLogger } from '@iota/sdk';
import { Client, initLogger, OutputId } from '@iota/sdk';
require('dotenv').config({ path: '.env' });

// Run with command:
Expand Down Expand Up @@ -33,7 +33,9 @@ async function run() {
console.log('First output of query:');
console.log('ID: ', outputIdsResponse.items[0]);

const outputs = await client.getOutputs(outputIdsResponse.items);
const outputs = await client.getOutputs(
outputIdsResponse.items.map((id) => new OutputId(id)),
);
console.log(outputs[0]);
} catch (error) {
console.error('Error: ', error);
Expand Down
29 changes: 28 additions & 1 deletion bindings/nodejs/lib/types/block/id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,28 @@
// SPDX-License-Identifier: Apache-2.0

import { HexEncodedString } from '../utils';
import { SlotIndex } from './slot';

/**
* Base class for IDs with a hex encoded slot index at the end.
*/
export class IdWithSlotIndex extends String {
slotIndex(): SlotIndex {
const numberString = super.slice(-8);
const chunks = [];
for (
let i = 0, charsLength = numberString.length;
i < charsLength;
i += 2
) {
chunks.push(numberString.substring(i, i + 2));
}
const separated = chunks.map((n) => parseInt(n, 16));
const buf = Uint8Array.from(separated).buffer;
const view = new DataView(buf);
return view.getUint32(0, true);
}
}

/**
* An Account ID represented as hex-encoded string.
Expand All @@ -21,13 +43,18 @@ export type NftId = HexEncodedString;
/**
* A Block ID represented as hex-encoded string.
*/
export type BlockId = HexEncodedString;
export class BlockId extends IdWithSlotIndex {}

/**
* A Token ID represented as hex-encoded string.
*/
export type TokenId = HexEncodedString;

/**
* A Transaction ID represented as hex-encoded string.
*/
export class TransactionId extends IdWithSlotIndex {}

/**
* A Foundry ID represented as hex-encoded string.
*/
Expand Down
12 changes: 6 additions & 6 deletions bindings/nodejs/lib/types/block/input/input.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
// Copyright 2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

import { HexEncodedString } from '../../utils';
import { Transform, Type } from 'class-transformer';
import { TransactionId } from '../id';
import { OutputId } from '../output';

/**
Expand Down Expand Up @@ -33,7 +34,9 @@ class UTXOInput extends Input {
/**
* The transaction ID.
*/
readonly transactionId: HexEncodedString;
@Type(() => TransactionId)
@Transform(({ value }) => new TransactionId(value), { toClassOnly: true })
readonly transactionId: TransactionId;
/**
* The output index.
*/
Expand All @@ -43,10 +46,7 @@ class UTXOInput extends Input {
* @param transactionId The ID of the transaction it is an input of.
* @param transactionOutputIndex The index of the input within the transaction.
*/
constructor(
transactionId: HexEncodedString,
transactionOutputIndex: number,
) {
constructor(transactionId: TransactionId, transactionOutputIndex: number) {
super(InputType.UTXO);
this.transactionId = transactionId;
this.transactionOutputIndex = transactionOutputIndex;
Expand Down
25 changes: 22 additions & 3 deletions bindings/nodejs/lib/types/block/output/output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,32 @@ import { Feature, FeatureDiscriminator, NativeTokenFeature } from './feature';

// Temp solution for not double parsing JSON
import { plainToInstance, Type } from 'class-transformer';
import { HexEncodedString, NumericString, u64 } from '../../utils';
import { NumericString, u64 } from '../../utils';
import { TokenScheme, TokenSchemeDiscriminator } from './token-scheme';
import { AccountId, NftId, AnchorId, DelegationId } from '../id';
import { AccountId, NftId, AnchorId, DelegationId, TransactionId } from '../id';
import { EpochIndex } from '../../block/slot';
import { NativeToken } from '../../models/native-token';

export type OutputId = HexEncodedString;
export class OutputId extends String {
transactionId(): TransactionId {
return new TransactionId(this.slice(74));
}
outputIndex(): number {
const numberString = this.slice(-4);
const chunks = [];
for (
let i = 0, charsLength = numberString.length;
i < charsLength;
i += 2
) {
chunks.push(numberString.substring(i, i + 2));
}
const separated = chunks.map((n) => parseInt(n, 16));
const buf = Uint8Array.from(separated).buffer;
const view = new DataView(buf);
return view.getUint16(0, true);
}
}

/**
* All of the output types.
Expand Down
3 changes: 2 additions & 1 deletion bindings/nodejs/lib/types/block/slot/commitment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0

import { u64 } from '../..';
import { IdWithSlotIndex } from '../id';

/**
* Timeline is divided into slots, and each slot has a corresponding slot index.
Expand All @@ -21,7 +22,7 @@ type EpochIndex = number;
/**
* Identifier of a slot commitment
*/
type SlotCommitmentId = string;
class SlotCommitmentId extends IdWithSlotIndex {}

/**
* A BLAKE2b-256 hash of concatenating multiple sparse merkle tree roots of a slot.
Expand Down
7 changes: 4 additions & 3 deletions bindings/nodejs/lib/types/client/bridge/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import type {
OutputId,
Payload,
SlotIndex,
SlotCommitmentId,
} from '../../block';
import type { PreparedTransactionData } from '../prepared-transaction-data';
import type {
Expand Down Expand Up @@ -223,21 +224,21 @@ export interface __GetTransactionMetadataMethod__ {
export interface __GetCommitmentMethod__ {
name: 'getCommitment';
data: {
commitmentId: HexEncodedString;
commitmentId: SlotCommitmentId;
};
}

export interface __GetUtxoChangesMethod__ {
name: 'getUtxoChanges';
data: {
commitmentId: HexEncodedString;
commitmentId: SlotCommitmentId;
};
}

export interface __GetUtxoChangesFullMethod__ {
name: 'getUtxoChangesFull';
data: {
commitmentId: HexEncodedString;
commitmentId: SlotCommitmentId;
};
}

Expand Down
6 changes: 3 additions & 3 deletions bindings/nodejs/lib/types/client/prepared-transaction-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@

import { Type } from 'class-transformer';
import { Address, AddressDiscriminator } from '../block/address';
import { Output, OutputDiscriminator, OutputId } from '../block/output/output';
import { Output, OutputDiscriminator } from '../block/output/output';
import { Transaction } from '../block/payload/signed_transaction';
import { IOutputMetadataResponse } from '../models/api';
import { Bip44 } from '../secret_manager';
import { NumericString } from '../utils';
import { HexEncodedString, NumericString } from '../utils';

/**
* Helper struct for offline signing.
Expand All @@ -28,7 +28,7 @@ export class PreparedTransactionData {
/**
* Mana rewards by input.
*/
manaRewards?: { [outputId: OutputId]: NumericString };
manaRewards?: { [outputId: HexEncodedString]: NumericString };
}

/**
Expand Down
5 changes: 3 additions & 2 deletions bindings/nodejs/lib/types/models/api/block-id-response.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
// Copyright 2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

import type { HexEncodedString } from '../../utils/hex-encoding';
import { BlockId } from '../../block';

/**
* Block id response.
*/
export interface IBlockIdResponse {
/**
* The block id.
*/
blockId: HexEncodedString;
blockId: BlockId;
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// Copyright 2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

import { OutputId } from '../../../../block/output/output';
import { NumericString } from '../../../../utils';
import type { HexEncodedString } from '../../../../utils/hex-encoding';

/**
* Details of an outputs response from the indexer plugin.
Expand All @@ -23,5 +23,5 @@ export interface IOutputsResponse {
/**
* The output IDs (transaction hash + output index) of the outputs on this address.
*/
items: HexEncodedString[];
items: OutputId[];
}
5 changes: 3 additions & 2 deletions bindings/nodejs/lib/types/models/api/tips-response.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
// Copyright 2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

import type { HexEncodedString } from '../../utils/hex-encoding';
import { BlockId } from '../../block/id';

/**
* Response from the tips endpoint.
*/
export interface ITipsResponse {
/**
* The block ids of the tip.
*/
tips: HexEncodedString[];
tips: BlockId[];
}
6 changes: 2 additions & 4 deletions bindings/nodejs/lib/types/models/block-metadata.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
// Copyright 2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

import type { HexEncodedString } from '../utils/hex-encoding';
import { BlockState, TransactionState } from './state';
import { BlockFailureReason } from './block-failure-reason';
import { Block } from '../block';
import { TransactionId } from '../wallet';
import { Block, BlockId, TransactionId } from '../block';
import { TransactionFailureReason } from './transaction-failure-reason';

/**
Expand All @@ -15,7 +13,7 @@ export interface IBlockMetadata {
/**
* The block id.
*/
blockId: HexEncodedString;
blockId: BlockId;
/**
* The block state.
*/
Expand Down
2 changes: 1 addition & 1 deletion bindings/nodejs/lib/types/utils/bridge/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ export interface __VerifyTransactionSemantic__ {
inputs: InputSigningData[];
protocolParameters: ProtocolParameters;
unlocks?: Unlock[];
manaRewards?: { [outputId: OutputId]: NumericString };
manaRewards?: { [outputId: HexEncodedString]: NumericString };
};
}

Expand Down
7 changes: 1 addition & 6 deletions bindings/nodejs/lib/types/wallet/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,10 @@
import type { OutputData } from './output';
import { InclusionState } from './transaction';
import { InputSigningData, Remainder } from '../client';
import { Transaction, SignedTransactionPayload } from '../block';
import { Transaction, SignedTransactionPayload, TransactionId } from '../block';
import { OutputResponse } from '../models';
import { HexEncodedString } from '../utils';

/**
* A Transaction ID represented as hex-encoded string.
*/
export type TransactionId = string;

/**
* All of the wallet event types.
*/
Expand Down
4 changes: 2 additions & 2 deletions bindings/nodejs/lib/types/wallet/participation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0

import type { INode } from '../client';
import type { OutputId } from '../block/output';
import { HexEncodedString } from '../utils';

/**
* An object containing an account's entire participation overview.
Expand All @@ -16,7 +16,7 @@ export interface ParticipationOverview {
*/
export interface Participations {
[eventId: ParticipationEventId]: {
[outputId: OutputId]: TrackedParticipationOverview;
[outputId: HexEncodedString]: TrackedParticipationOverview;
};
}

Expand Down
5 changes: 2 additions & 3 deletions bindings/nodejs/lib/types/wallet/signed-transaction-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
import { Type } from 'class-transformer';
import { SignedTransactionPayload } from '../block/payload/signed_transaction';
import { InputSigningData } from '../client';
import { OutputId } from '../block/output';
import { NumericString } from '../utils';
import { HexEncodedString, NumericString } from '../utils';

/** The signed transaction with inputs data */
export class SignedTransactionData {
Expand All @@ -16,5 +15,5 @@ export class SignedTransactionData {
@Type(() => InputSigningData)
inputsData!: InputSigningData;
/** Mana rewards by input */
manaRewards?: { [outputId: OutputId]: NumericString };
manaRewards?: { [outputId: HexEncodedString]: NumericString };
}
Loading

0 comments on commit 1ce7d0c

Please sign in to comment.