From f395932eacaf5b615a9a6c2b70cb7d49d6854789 Mon Sep 17 00:00:00 2001 From: Oleksandr Myshchyshyn Date: Thu, 14 Nov 2024 01:07:08 +0200 Subject: [PATCH] Update all types with typedoc --- src/types/Account.ts | 39 +++ src/types/AddressableEntity.ts | 81 ++++- src/types/Args.ts | 89 ++++- src/types/AuctionState.ts | 33 ++ src/types/Bid.ts | 70 +++- src/types/BidKind.ts | 20 ++ src/types/Block.ts | 400 +++++++++++++++++++++- src/types/BlockProposer.ts | 46 ++- src/types/ByteConverters.ts | 68 ++-- src/types/Contract.ts | 27 +- src/types/ContractPackage.ts | 72 ++++ src/types/Conversions.ts | 19 +- src/types/Deploy.ts | 219 +++++++++--- src/types/DeployInfo.ts | 19 + src/types/EntryPoint.ts | 94 ++++- src/types/EraEnd.ts | 115 +++++++ src/types/EraInfo.ts | 60 ++++ src/types/EraSummary.ts | 29 ++ src/types/ExecutableDeployItem.ts | 251 ++++++++++++-- src/types/ExecutionResult.ts | 174 ++++++++++ src/types/HexBytes.ts | 41 +++ src/types/InitiatorAddr.ts | 34 ++ src/types/MessageTopic.ts | 51 +++ src/types/MinimalBlockInfo.ts | 25 ++ src/types/NamedKey.ts | 53 +++ src/types/Package.ts | 61 ++++ src/types/PricingMode.ts | 49 +++ src/types/Reservation.ts | 22 ++ src/types/SerializationUtils.ts | 68 ++-- src/types/StoredValue.ts | 65 ++++ src/types/Time.ts | 72 +++- src/types/Transaction.ts | 309 ++++++++++++++++- src/types/TransactionEntryPoint.ts | 78 ++++- src/types/TransactionScheduling.ts | 70 ++++ src/types/TransactionTarget.ts | 126 +++++++ src/types/Transfer.ts | 117 ++++++- src/types/Transform.ts | 235 ++++++++++++- src/types/UnbondingPurse.ts | 21 ++ src/types/ValidatorWeight.ts | 18 + src/types/clvalue/Any.ts | 19 +- src/types/clvalue/Bool.ts | 20 +- src/types/clvalue/ByteArray.ts | 21 +- src/types/clvalue/CLValue.ts | 31 +- src/types/clvalue/Int32.ts | 26 +- src/types/clvalue/Int64.ts | 30 +- src/types/clvalue/List.ts | 22 +- src/types/clvalue/Map.ts | 17 +- src/types/clvalue/Option.ts | 27 +- src/types/clvalue/Parser.ts | 7 +- src/types/clvalue/Result.ts | 21 +- src/types/clvalue/String.ts | 21 +- src/types/clvalue/Tuple1.ts | 15 +- src/types/clvalue/Tuple2.ts | 15 +- src/types/clvalue/Tuple3.ts | 15 +- src/types/clvalue/Uint128.ts | 17 +- src/types/clvalue/Uint256.ts | 17 +- src/types/clvalue/Uint32.ts | 24 +- src/types/clvalue/Uint512.ts | 33 +- src/types/clvalue/Uint64.ts | 21 +- src/types/clvalue/Uint8.ts | 20 +- src/types/clvalue/UintBig.ts | 55 +-- src/types/clvalue/Unit.ts | 2 +- src/types/clvalue/cltype/ByteArray.ts | 39 ++- src/types/clvalue/cltype/CLType.ts | 78 +++-- src/types/clvalue/cltype/CLTypeRaw.ts | 16 +- src/types/clvalue/cltype/Dynamic.ts | 24 +- src/types/clvalue/cltype/List.ts | 29 +- src/types/clvalue/cltype/Map.ts | 28 +- src/types/clvalue/cltype/Option.ts | 30 +- src/types/clvalue/cltype/Parser.ts | 28 +- src/types/clvalue/cltype/Result.ts | 28 +- src/types/clvalue/cltype/Tuple1.ts | 30 +- src/types/clvalue/cltype/Tuple2.ts | 30 +- src/types/clvalue/cltype/Tuple3.ts | 35 +- src/types/key/Account.ts | 34 +- src/types/key/AddressableEntity.ts | 30 +- src/types/key/BalanceHoldAddr.ts | 36 +- src/types/key/BidAddr.ts | 29 +- src/types/key/BlockGlobalAddr.ts | 34 +- src/types/key/ByteCode.ts | 38 +- src/types/key/Contract.ts | 32 +- src/types/key/ContractPackage.ts | 30 +- src/types/key/EntityAddr.ts | 19 +- src/types/key/EntryPointAddr.ts | 13 +- src/types/key/Era.ts | 24 +- src/types/key/Hash.ts | 38 +- src/types/key/Key.ts | 17 +- src/types/key/MessageAddr.ts | 36 +- src/types/key/NewNamedKeyAddr.ts | 33 +- src/types/key/Transfer.ts | 25 +- src/types/key/URef.ts | 57 +-- src/types/key/Uref.test.ts | 2 +- src/types/keypair/Algorithm.ts | 4 +- src/types/keypair/PrivateKey.ts | 2 + src/types/keypair/PublicKey.ts | 13 +- src/types/keypair/ed25519/PrivateKey.ts | 6 +- src/types/keypair/ed25519/PublicKey.ts | 8 +- src/types/keypair/secp256k1/PrivateKey.ts | 6 +- src/types/keypair/secp256k1/PublicKey.ts | 18 +- 99 files changed, 4074 insertions(+), 841 deletions(-) diff --git a/src/types/Account.ts b/src/types/Account.ts index 75d675965..31b8429f4 100644 --- a/src/types/Account.ts +++ b/src/types/Account.ts @@ -2,8 +2,15 @@ import { jsonObject, jsonMember, jsonArrayMember } from 'typedjson'; import { AccountHash, URef } from './key'; import { NamedKeys } from './NamedKey'; +/** + * Represents an associated key for an account, linking an `AccountHash` + * with a weight that determines its permission level. + */ @jsonObject export class AssociatedKey { + /** + * The account hash associated with this key, uniquely identifying the account. + */ @jsonMember({ name: 'account_hash', constructor: AccountHash, @@ -12,6 +19,9 @@ export class AssociatedKey { }) accountHash: AccountHash; + /** + * The weight assigned to this key, which determines the key’s authority level. + */ @jsonMember({ name: 'weight', constructor: Number @@ -19,14 +29,24 @@ export class AssociatedKey { weight: number; } +/** + * Represents action thresholds for an account, specifying minimum weights + * required for deployment and key management actions. + */ @jsonObject export class ActionThresholds { + /** + * The threshold for performing deployment actions, represented as a weight. + */ @jsonMember({ name: 'deployment', constructor: Number }) deployment: number; + /** + * The threshold for performing key management actions, represented as a weight. + */ @jsonMember({ name: 'key_management', constructor: Number @@ -34,8 +54,15 @@ export class ActionThresholds { keyManagement: number; } +/** + * Represents an account in the blockchain, containing account details such as + * associated keys, named keys, main purse, and action thresholds. + */ @jsonObject export class Account { + /** + * The account hash for this account, which serves as a unique identifier. + */ @jsonMember({ name: 'account_hash', deserializer: json => AccountHash.fromJSON(json), @@ -44,12 +71,18 @@ export class Account { }) accountHash: AccountHash; + /** + * The named keys associated with this account, mapping key names to `URef` values. + */ @jsonMember({ name: 'named_keys', constructor: NamedKeys }) namedKeys: NamedKeys; + /** + * The main purse associated with this account, represented as a `URef`. + */ @jsonMember({ name: 'main_purse', constructor: URef, @@ -58,9 +91,15 @@ export class Account { }) mainPurse: URef; + /** + * The list of associated keys for this account, each with an `AccountHash` and weight. + */ @jsonArrayMember(AssociatedKey, { name: 'associated_keys' }) associatedKeys: AssociatedKey[]; + /** + * The action thresholds for this account, setting required weights for specific actions. + */ @jsonMember({ name: 'action_thresholds', constructor: ActionThresholds }) actionThresholds: ActionThresholds; } diff --git a/src/types/AddressableEntity.ts b/src/types/AddressableEntity.ts index 713ef52dc..df6afa3ca 100644 --- a/src/types/AddressableEntity.ts +++ b/src/types/AddressableEntity.ts @@ -7,25 +7,32 @@ import { AccountHash, URef } from './key'; export type SystemEntityType = string; export type TransactionRuntime = 'VmCasperV1' | 'VmCasperV2'; +/** + * Defines different kinds of entities within the system, such as system entities, + * accounts, and smart contracts. Provides details on each entity type. + */ @jsonObject export class EntityKind { + /** + * Represents a system entity type, allowing flexible naming of system-specific entities. + */ @jsonMember({ name: 'System', constructor: String }) system?: SystemEntityType; + /** + * Represents an account entity, identified by an `AccountHash`. + */ @jsonMember({ name: 'Account', constructor: AccountHash, - deserializer: json => { - if (!json) return; - return AccountHash.fromJSON(json); - }, - serializer: value => { - if (!value) return; - return value.toJSON(); - } + deserializer: json => (json ? AccountHash.fromJSON(json) : undefined), + serializer: value => (value ? value.toJSON() : undefined) }) account?: AccountHash; + /** + * Represents a smart contract entity, specified by its transaction runtime version. + */ @jsonMember({ name: 'SmartContract', constructor: String @@ -33,41 +40,77 @@ export class EntityKind { smartContract?: TransactionRuntime; } +/** + * Defines thresholds for various actions that an entity can perform, + * with each threshold represented as a weight. + */ @jsonObject export class EntityActionThresholds { + /** + * The weight required to authorize deployment actions. + */ @jsonMember({ name: 'deployment', constructor: Number }) deployment: number; + /** + * The weight required to authorize upgrade management actions. + */ @jsonMember({ name: 'upgrade_management', constructor: Number }) upgradeManagement: number; + /** + * The weight required to authorize key management actions. + */ @jsonMember({ name: 'key_management', constructor: Number }) keyManagement: number; } +/** + * Represents an addressable entity, which can be a smart contract, account, or system entity. + * Each entity contains various properties such as action thresholds, associated keys, + * and message topics. + */ @jsonObject export class AddressableEntity { + /** + * Specifies the kind of the entity, such as system entity, account, or smart contract. + */ @jsonMember({ name: 'entity_kind', constructor: EntityKind }) entityKind: EntityKind; + /** + * The unique package hash associated with this entity. + */ @jsonMember({ name: 'package_hash', constructor: String }) packageHash: string; + /** + * The bytecode hash associated with this entity, representing its executable code. + */ @jsonMember({ name: 'byte_code_hash', constructor: String }) byteCodeHash: string; + /** + * The associated keys for this entity, each with an `AccountHash` and a weight. + */ @jsonArrayMember(AssociatedKey, { name: 'associated_keys' }) associatedKeys: AssociatedKey[]; + /** + * The action thresholds required for different operations, such as deployment or key management. + */ @jsonMember({ name: 'action_thresholds', constructor: EntityActionThresholds }) actionThresholds: EntityActionThresholds; + /** + * The main purse associated with this entity, used for managing funds. + */ @jsonMember({ name: 'main_purse', constructor: URef, @@ -76,25 +119,47 @@ export class AddressableEntity { }) mainPurse: URef; + /** + * The protocol version in use by this entity. + */ @jsonMember({ name: 'protocol_version', constructor: String }) protocolVersion: string; + /** + * A list of topics for messaging associated with this entity. + */ @jsonArrayMember(MessageTopic, { name: 'message_topics' }) messageTopics: MessageTopic[]; } +/** + * Represents an entry point in a smart contract, with a specific name and configuration. + */ @jsonObject export class NamedEntryPoint { + /** + * The entry point configuration, specifying the method and parameters. + */ @jsonMember({ name: 'entry_point', constructor: EntryPointV1 }) entryPoint: EntryPointV1; + /** + * The name of the entry point, used for identifying and invoking it. + */ @jsonMember({ name: 'name', constructor: String }) name: string; } +/** + * Returns the numeric tag associated with a given transaction runtime version. + * Useful for distinguishing between different virtual machine versions. + * + * @param runtime - The transaction runtime to retrieve the tag for. + * @returns A number representing the tag for the given runtime. + */ export function getRuntimeTag(runtime: TransactionRuntime): number { switch (runtime) { case 'VmCasperV1': diff --git a/src/types/Args.ts b/src/types/Args.ts index 590f97f30..701d02430 100644 --- a/src/types/Args.ts +++ b/src/types/Args.ts @@ -11,20 +11,38 @@ import { import { jsonMapMember, jsonObject } from 'typedjson'; import { toBytesString, toBytesU32 } from './ByteConverters'; +/** + * Represents a named argument with a name and associated `CLValue`, which can be serialized to bytes. + */ export class NamedArg { + /** + * Creates an instance of NamedArg. + * @param name - The name of the argument. + * @param value - The `CLValue` associated with this argument. + */ constructor(public name: string, public value: CLValue) {} + /** + * Converts the named argument to a byte array representation. + * @returns A `Uint8Array` containing the serialized argument name and value. + */ public toBytes(): Uint8Array { const name = toBytesString(this.name); const value = CLValueParser.toBytesWithType(this.value); return concat([name, value]); } + /** + * Creates a `NamedArg` instance from a byte array. + * @param bytes - The byte array to parse. + * @returns A new `NamedArg` instance. + * @throws Error if the value data is missing. + */ public static fromBytes(bytes: Uint8Array): NamedArg { const stringValue = CLValueString.fromBytes(bytes); if (!stringValue.bytes) { - new Error('Missing data for value of named arg'); + throw new Error('Missing data for value of named arg'); } const value = CLValueParser.fromBytesByType( @@ -35,6 +53,23 @@ export class NamedArg { } } +/** + * Serializes a map of arguments to an array format for JSON. + * @param map - The map of arguments to serialize. + * @returns An array where each entry is a key-value pair in JSON format. + */ +const serRA = (map: Map) => { + return Array.from(map, ([key, value]) => { + return [key, CLValueParser.toJSON(value)]; + }); +}; + +/** + * Deserializes an array format to a map of arguments. + * @param _arr - The array of key-value pairs to deserialize. + * @returns A map containing each key-value pair. + * @throws Error if a duplicate key is detected. + */ const desRA = (_arr: any) => { const parsed = new Map( Array.from(_arr, ([key, value]) => { @@ -49,32 +84,47 @@ const desRA = (_arr: any) => { return parsed; }; -const serRA = (map: Map) => { - return Array.from(map, ([key, value]) => { - return [key, CLValueParser.toJSON(value)]; - }); -}; - +/** + * Represents a set of named arguments (`NamedArg`) for a contract call. + * Provides methods to serialize, deserialize, and manipulate argument entries. + */ @jsonObject export class Args { + /** + * The map of argument names to `CLValue` values. + */ @jsonMapMember(String, CLValue, { serializer: serRA, deserializer: desRA }) public args: Map; + /** + * Creates an instance of `Args` from a map of arguments. + * @param args - A map containing argument names as keys and `CLValue` instances as values. + */ constructor(args: Map) { this.args = args; } - public static fromMap(args: Record) { + /** + * Creates an `Args` instance from an object. + * @param args - An object containing argument names as keys and `CLValue` instances as values. + * @returns A new `Args` instance. + */ + public static fromMap(args: Record): Args { const map: Map = new Map( Object.keys(args).map(k => [k, args[k]]) ); return new Args(map); } - public static fromNamedArgs(namedArgs: NamedArg[]) { + /** + * Creates an `Args` instance from an array of `NamedArg` instances. + * @param namedArgs - An array of `NamedArg` instances. + * @returns A new `Args` instance. + */ + public static fromNamedArgs(namedArgs: NamedArg[]): Args { const args = namedArgs.reduce>((pre, cur) => { pre[cur.name] = cur.value; return pre; @@ -82,10 +132,20 @@ export class Args { return this.fromMap(args); } + /** + * Inserts a new argument into the map. + * @param key - The argument name. + * @param value - The `CLValue` for the argument. + */ public insert(key: string, value: CLValue) { this.args.set(key, value); } + /** + * Converts the arguments to a byte array. + * The format includes the number of arguments followed by each argument in bytes. + * @returns A `Uint8Array` containing the serialized arguments. + */ public toBytes(): Uint8Array { const vec = Array.from(this.args.entries()).map((a: [string, CLValue]) => { return new NamedArg(a[0], a[1]); @@ -96,6 +156,13 @@ export class Args { return concat(valueByteList); } + /** + * Creates an `Args` instance from a byte array. + * Parses the byte array to extract each argument. + * @param bytes - The byte array to parse. + * @returns An object containing a new `Args` instance and any remaining bytes. + * @throws Error if there is an issue parsing the bytes. + */ public static fromBytes(bytes: Uint8Array): IResultWithBytes { const uint32 = CLValueUInt32.fromBytes(bytes); const size = uint32.result.getValue().toNumber(); @@ -104,11 +171,9 @@ export class Args { const res: NamedArg[] = []; for (let i = 0; i < size; i++) { if (!remainBytes) { - new Error('Error while parsing bytes'); - break; + throw new Error('Error while parsing bytes'); } const namedArg = NamedArg.fromBytes(remainBytes); - res.push(namedArg); remainBytes = undefined; } diff --git a/src/types/AuctionState.ts b/src/types/AuctionState.ts index 147f5e6ba..2d73ec12e 100644 --- a/src/types/AuctionState.ts +++ b/src/types/AuctionState.ts @@ -3,8 +3,14 @@ import { Bid } from './Bid'; import { ValidatorWeightAuction } from './ValidatorWeight'; import { PublicKey } from './keypair'; +/** + * Represents a public key and its corresponding bid in the auction state. + */ @jsonObject export class PublicKeyAndBid { + /** + * The public key associated with this bid. + */ @jsonMember({ name: 'public_key', constructor: PublicKey, @@ -13,30 +19,57 @@ export class PublicKeyAndBid { }) publicKey: PublicKey; + /** + * The bid associated with the public key. + */ @jsonMember({ name: 'bid', constructor: Bid }) bid: Bid; } +/** + * Represents validators for a specific era, including the era ID and validator weights. + */ @jsonObject export class EraValidators { + /** + * The unique identifier for the era. + */ @jsonMember({ name: 'era_id', constructor: Number }) eraID: number; + /** + * The weights of the validators for this era. + */ @jsonArrayMember(ValidatorWeightAuction, { name: 'validator_weights' }) validatorWeights: ValidatorWeightAuction[]; } +/** + * Represents the current auction state, including bids, era validators, and other state information. + */ @jsonObject export class AuctionState { + /** + * The list of public keys and bids in the auction. + */ @jsonArrayMember(PublicKeyAndBid, { name: 'bids' }) bids: PublicKeyAndBid[]; + /** + * The block height at which this auction state was recorded. + */ @jsonMember({ name: 'block_height', constructor: Number }) blockHeight: number; + /** + * The validators and their weights for each era in the auction state. + */ @jsonArrayMember(EraValidators, { name: 'era_validators' }) eraValidators: EraValidators[]; + /** + * The root hash of the state at the time of this auction state. + */ @jsonMember({ name: 'state_root_hash', constructor: String }) stateRootHash: string; } diff --git a/src/types/Bid.ts b/src/types/Bid.ts index cab32b863..0061132de 100644 --- a/src/types/Bid.ts +++ b/src/types/Bid.ts @@ -3,11 +3,20 @@ import { PublicKey } from './keypair'; import { CLValueUInt512 } from './clvalue'; import { URef } from './key'; +/** + * Represents a vesting schedule for staked amounts, including an initial release timestamp and locked amounts. + */ @jsonObject export class VestingSchedule { + /** + * The initial release timestamp in milliseconds. + */ @jsonMember({ name: 'initial_release_timestamp_millis', constructor: Number }) initialReleaseTimestampMillis: number; + /** + * The list of locked amounts associated with this vesting schedule. + */ @jsonArrayMember(CLValueUInt512, { name: 'locked_amounts', serializer: (value: CLValueUInt512[]) => value.map(it => it.toJSON()), @@ -17,8 +26,14 @@ export class VestingSchedule { lockedAmounts: CLValueUInt512[]; } +/** + * Represents a bid by a validator, including details about the bonding purse, delegation rate, stake, and vesting schedule. + */ @jsonObject export class ValidatorBid { + /** + * The bonding purse associated with the validator. + */ @jsonMember({ name: 'bonding_purse', constructor: URef, @@ -27,12 +42,21 @@ export class ValidatorBid { }) bondingPurse: URef; + /** + * The rate at which delegations to this validator are taxed. + */ @jsonMember({ name: 'delegation_rate', constructor: Number }) delegationRate: number; + /** + * Indicates whether the validator is currently inactive. + */ @jsonMember({ name: 'inactive', constructor: Boolean }) inactive: boolean; + /** + * The total amount staked by this validator. + */ @jsonMember({ name: 'staked_amount', constructor: CLValueUInt512, @@ -41,16 +65,25 @@ export class ValidatorBid { }) stakedAmount: CLValueUInt512; + /** + * Minimum and maximum amounts that can be delegated to this validator. + */ @jsonMember({ name: 'minimum_delegation_amount', constructor: Number }) minimumDelegationAmount: number; @jsonMember({ name: 'maximum_delegation_amount', constructor: Number }) maximumDelegationAmount: number; + /** + * The vesting schedule for this validator’s stake. + */ @jsonMember({ name: 'vesting_schedule', constructor: VestingSchedule }) vestingSchedule?: VestingSchedule; } +/** + * Represents a delegator who delegates their stake to a validator. + */ @jsonObject export class Delegator { constructor( @@ -67,7 +100,12 @@ export class Delegator { this.vestingSchedule = vestingSchedule; } - static newDelegatorFromDelegatorV1(v1: DelegatorV1) { + /** + * Creates a `Delegator` instance from a `DelegatorV1` instance. + * @param v1 - The `DelegatorV1` instance to convert. + * @returns A new `Delegator` instance. + */ + static newDelegatorFromDelegatorV1(v1: DelegatorV1): Delegator { return new Delegator( v1.bondingPurse, v1.stakedAmount, @@ -113,6 +151,9 @@ export class Delegator { vestingSchedule?: VestingSchedule; } +/** + * Represents a bid entry, including the bonding purse, delegation rate, inactive status, and vesting schedule. + */ @jsonObject export class Bid { @jsonMember({ @@ -152,6 +193,9 @@ export class Bid { vestingSchedule?: VestingSchedule; } +/** + * Represents a version 1 delegator with basic properties such as bonding purse and stake amount. + */ @jsonObject export class DelegatorV1 { @jsonMember({ @@ -190,11 +234,20 @@ export class DelegatorV1 { vestingSchedule?: VestingSchedule; } +/** + * Represents a credit in a staking system, tied to a specific era and validator. + */ @jsonObject export class Credit { + /** + * The era ID associated with this credit. + */ @jsonMember({ name: 'era_id', constructor: Number }) eraID: number; + /** + * The public key of the validator for this credit. + */ @jsonMember({ name: 'validator_public_key', constructor: PublicKey, @@ -203,6 +256,9 @@ export class Credit { }) validatorPublicKey: PublicKey; + /** + * The amount of the credit. + */ @jsonMember({ name: 'amount', constructor: CLValueUInt512, @@ -212,11 +268,20 @@ export class Credit { amount: CLValueUInt512; } +/** + * Represents a bridge between validators, including their public keys and the associated era. + */ @jsonObject export class Bridge { + /** + * The era ID during which this bridge was established. + */ @jsonMember({ name: 'era_id', constructor: Number }) eraID: number; + /** + * The public key of the old validator. + */ @jsonMember({ name: 'old_validator_public_key', constructor: PublicKey, @@ -225,6 +290,9 @@ export class Bridge { }) oldValidatorPublicKey: PublicKey; + /** + * The public key of the new validator. + */ @jsonMember({ name: 'new_validator_public_key', constructor: PublicKey, diff --git a/src/types/BidKind.ts b/src/types/BidKind.ts index 518bff7e6..170209656 100644 --- a/src/types/BidKind.ts +++ b/src/types/BidKind.ts @@ -1,20 +1,40 @@ import { jsonObject, jsonMember } from 'typedjson'; import { Bid, Bridge, Credit, Delegator, ValidatorBid } from './Bid'; +/** + * Represents a polymorphic bid kind, allowing for different types of bid-related entities. + * This class contains properties for various bid types, including unified bids, validator bids, + * delegators, bridge transitions, and credits. + */ @jsonObject export class BidKind { + /** + * A unified bid that combines multiple bid attributes. + */ @jsonMember({ name: 'Unified', constructor: Bid }) unified?: Bid; + /** + * A validator-specific bid, containing information unique to validators. + */ @jsonMember({ name: 'Validator', constructor: ValidatorBid }) validator?: ValidatorBid; + /** + * A bid specific to a delegator, which represents a user delegating their stake to a validator. + */ @jsonMember({ name: 'Delegator', constructor: Delegator }) delegator?: Delegator; + /** + * Represents a transition bridge between validators, connecting an old validator with a new one. + */ @jsonMember({ name: 'Bridge', constructor: Bridge }) bridge?: Bridge; + /** + * Represents a credit entry for a validator, specifying an amount and era. + */ @jsonMember({ name: 'Credit', constructor: Credit }) credit?: Credit; } diff --git a/src/types/Block.ts b/src/types/Block.ts index c72e89494..7afbdc1cc 100644 --- a/src/types/Block.ts +++ b/src/types/Block.ts @@ -11,8 +11,15 @@ import { import { PublicKey } from './keypair'; import { HexBytes } from './HexBytes'; +/** + * Represents a proof containing a public key and a signature, used for validating the authenticity of data. + */ @jsonObject export class Proof { + /** + * The public key associated with the proof. + * This key is used to verify the signature's validity. + */ @jsonMember(() => ({ constructor: PublicKey, name: 'public_key', @@ -21,6 +28,10 @@ export class Proof { })) public publicKey: PublicKey; + /** + * The signature generated by the associated public key. + * The signature proves the authenticity of the data or transaction. + */ @jsonMember(() => ({ name: 'signature', constructor: HexBytes, @@ -30,8 +41,15 @@ export class Proof { public signature: HexBytes; } +/** + * Represents a block in the blockchain containing metadata, transactions, and proof. + * A block includes information like the hash, height, parent block, transactions, and more. + */ @jsonObject export class Block { + /** + * The unique hash of the block. + */ @jsonMember(() => ({ name: 'hash', constructor: Hash, @@ -40,9 +58,15 @@ export class Block { })) public hash: Hash; + /** + * The height of the block in the blockchain. + */ @jsonMember({ name: 'height', constructor: Number }) public height: number; + /** + * The hash of the state root associated with the block. + */ @jsonMember(() => ({ name: 'state_root_hash', constructor: Hash, @@ -51,6 +75,10 @@ export class Block { })) public stateRootHash: Hash; + /** + * The hash of the block that switched the current state, if available. + * This can be `null` if not applicable. + */ @jsonMember(() => ({ name: 'last_switch_block_hash', constructor: Hash, @@ -60,6 +88,9 @@ export class Block { })) public lastSwitchBlockHash: Hash | null; + /** + * The hash of the parent block in the blockchain. + */ @jsonMember(() => ({ name: 'parent_hash', constructor: Hash, @@ -68,9 +99,15 @@ export class Block { })) public parentHash: Hash; + /** + * The era ID in which this block was created. + */ @jsonMember({ name: 'era_id', constructor: Number }) public eraID: number; + /** + * The timestamp indicating when the block was created. + */ @jsonMember(() => ({ name: 'timestamp', constructor: Timestamp, @@ -79,28 +116,38 @@ export class Block { })) public timestamp: Timestamp; + /** + * The accumulated seed for randomness in the block generation. + */ @jsonMember(() => ({ name: 'accumulated_seed', constructor: Hash, deserializer: (json: string) => { if (!json) return; - return Hash.fromJSON(json); }, serializer: (value: Hash) => { if (!value) return; - return value.toJSON(); } })) public accumulatedSeed?: Hash; + /** + * A random bit used for proof-of-stake consensus. + */ @jsonMember({ name: 'random_bit', constructor: Boolean }) public randomBit: boolean; + /** + * The current gas price for transactions included in the block. + */ @jsonMember({ name: 'current_gas_price', constructor: Number }) public currentGasPrice: number; + /** + * The proposer who created this block. + */ @jsonMember(() => ({ name: 'proposer', constructor: Proposer, @@ -109,28 +156,70 @@ export class Block { })) public proposer: Proposer; + /** + * The protocol version used for this block. + */ @jsonMember({ name: 'protocol_version', constructor: String }) public protocolVersion?: string; + /** + * The era end details, if available, for the block's era. + */ @jsonMember(() => ({ name: 'era_end', constructor: EraEnd })) public eraEnd?: EraEnd; + /** + * The list of transactions included in this block. + */ @jsonArrayMember(() => BlockTransaction, { name: 'transactions', deserializer: (json: string) => BlockTransaction.fromJSON(json) }) public transactions: BlockTransaction[]; + /** + * A list of signature IDs that were rewarded in this block. + */ @jsonArrayMember(Number, { name: 'rewarded_signatures' }) public rewardedSignatures: number[]; + /** + * A list of proofs associated with this block. + */ @jsonArrayMember(() => Proof, { name: 'proofs' }) public proofs: Proof[]; + /** + * The origin block in V1 format, if available. + */ public originBlockV1?: BlockV1; + /** + * The origin block in V2 format, if available. + */ public originBlockV2?: BlockV2; + /** + * Constructs a new `Block` instance. + * @param hash - The unique hash of the block. + * @param height - The height of the block in the blockchain. + * @param stateRootHash - The hash of the state root for the block. + * @param lastSwitchBlockHash - The hash of the block that switched the state, if available. + * @param parentHash - The hash of the parent block. + * @param eraID - The era ID in which the block was created. + * @param timestamp - The timestamp of the block creation. + * @param accumulatedSeed - The accumulated seed for randomness in the block. + * @param randomBit - A random bit used for consensus. + * @param currentGasPrice - The current gas price for transactions in the block. + * @param proposer - The proposer of the block. + * @param protocolVersion - The protocol version of the block. + * @param eraEnd - The era end details for the block's era, if available. + * @param transactions - The list of transactions included in the block. + * @param rewardedSignatures - The list of rewarded signatures. + * @param proofs - The list of proofs associated with the block. + * @param originBlockV1 - The origin block in V1 format, if available. + * @param originBlockV2 - The origin block in V2 format, if available. + */ constructor( hash: Hash, height: number, @@ -171,14 +260,29 @@ export class Block { this.originBlockV2 = originBlockV2; } + /** + * Retrieves the V1 format of the origin block, if available. + * @returns The origin block in V1 format, or `undefined` if not available. + */ getBlockV1(): BlockV1 | undefined { return this.originBlockV1; } + /** + * Retrieves the V2 format of the origin block, if available. + * @returns The origin block in V2 format, or `undefined` if not available. + */ getBlockV2(): BlockV2 | undefined { return this.originBlockV2; } + /** + * Creates a new `Block` instance from a `BlockWrapper` object, which may contain either V1 or V2 block format. + * @param blockWrapper - The `BlockWrapper` containing either `blockV1` or `blockV2`. + * @param proofs - The list of proofs associated with the block. + * @returns A new `Block` instance based on the provided `blockWrapper` and `proofs`. + * @throws Will throw an error if the `blockWrapper` does not contain a valid `blockV1` or `blockV2`. + */ static newBlockFromBlockWrapper( blockWrapper: BlockWrapper, proofs: Proof[] @@ -213,6 +317,11 @@ export class Block { throw new Error('BlockWrapper must contain either BlockV1 or BlockV2'); } + /** + * Creates a new `Block` instance from a V1 block format. + * @param blockV1 - The V1 block format. + * @returns A new `Block` instance created from the provided V1 block format. + */ static newBlockFromBlockV1(blockV1: BlockV1): Block { const blockTransactions: BlockTransaction[] = []; @@ -258,14 +367,29 @@ export class Block { } } +/** + * Represents a transaction within a block, identified by a category, version, and hash. + * Each `BlockTransaction` stores the category of the transaction, its version, and a unique hash. + */ @jsonObject export class BlockTransaction { + /** + * The category of the transaction, indicating the type of transaction. + * This could be one of the predefined categories such as Mint, Auction, InstallUpgrade, etc. + */ @jsonMember({ name: 'category', constructor: Number }) public category: TransactionCategory; + /** + * The version of the transaction, specifying the version of the transaction protocol. + */ @jsonMember({ name: 'version', constructor: Number }) public version: TransactionVersion; + /** + * The unique hash identifying the transaction. + * This hash serves as a reference to the transaction. + */ @jsonMember(() => ({ name: 'hash', constructor: Hash, @@ -274,6 +398,12 @@ export class BlockTransaction { })) public hash: Hash; + /** + * Constructs a new `BlockTransaction` instance. + * @param category - The category of the transaction (e.g., Mint, Auction). + * @param version - The version of the transaction protocol. + * @param hash - The unique hash identifying the transaction. + */ constructor( category: TransactionCategory, version: TransactionVersion, @@ -284,8 +414,19 @@ export class BlockTransaction { this.hash = hash; } + /** + * Deserializes a JSON object into an array of `BlockTransaction` instances. + * The input `data` is expected to contain transaction hashes categorized by their types. + * + * @param data - The serialized data representing transactions categorized by type. + * @returns An array of `BlockTransaction` instances. + * + * @example + * const jsonData = { '0': ['hash1', 'hash2'], '1': ['hash3'] }; + * const transactions = BlockTransaction.fromJSON(jsonData); + * console.log(transactions); // Outputs an array of BlockTransaction instances. + */ public static fromJSON(data: any): BlockTransaction[] { - // TODO custom serialization const source = { Mint: data['0'] || [], Auction: data['1'] || [], @@ -327,6 +468,18 @@ export class BlockTransaction { } } +/** + * Converts an array of `TransactionHash` objects into an array of `BlockTransaction` instances. + * Each `TransactionHash` is associated with a specific category, and the resulting `BlockTransaction` includes the category, + * version, and the hash of the transaction. + * + * @param hashes - An array of `TransactionHash` objects, each representing a transaction hash. + * @param category - The category of the transaction (e.g., Mint, Auction). + * @returns An array of `BlockTransaction` instances, each representing a transaction. + * + * @throws {Error} If any of the `TransactionHash` objects does not contain a valid `transactionV1`. + * + */ function getBlockTransactionsFromTransactionHashes( hashes: TransactionHash[], category: TransactionCategory @@ -350,6 +503,21 @@ function getBlockTransactionsFromTransactionHashes( }); } +/** + * Parses a JSON string representing block transactions and converts them into an array of `BlockTransaction` instances. + * The input data is expected to be a JSON object with categories (e.g., '0', '1', etc.) mapping to arrays of `TransactionHash` objects. + * Each category corresponds to a specific type of transaction, such as Mint, Auction, etc. + * + * @param data - A JSON string containing transaction categories as keys ('0', '1', etc.), with each key pointing to an array of `TransactionHash` objects. + * @returns An array of `BlockTransaction` instances representing the transactions in the block. + * + * @throws {Error} If the input `data` is not valid JSON or does not conform to the expected structure. + * + * @example + * const jsonData = '{"0": [{"transactionV1": "hash1"}], "1": [{"transactionV1": "hash2"}]}'; + * const transactions = parseBlockTransactions(jsonData); + * console.log(transactions); // Outputs an array of BlockTransaction instances for Mint and Auction transactions. + */ export function parseBlockTransactions(data: string): BlockTransaction[] { const source = JSON.parse(data) as { '0'?: TransactionHash[]; @@ -361,6 +529,7 @@ export function parseBlockTransactions(data: string): BlockTransaction[] { }; const result: BlockTransaction[] = []; + if (source['0']) result.push( ...getBlockTransactionsFromTransactionHashes( @@ -407,8 +576,16 @@ export function parseBlockTransactions(data: string): BlockTransaction[] { return result; } +/** + * Represents a version 1 block in the blockchain, including the block's metadata (header), body, and proofs. + * A `BlockV1` contains the block's unique hash, header (which includes metadata like height and era ID), body (which includes transactions), + * and an array of proofs related to the block. + */ @jsonObject export class BlockV1 { + /** + * The unique hash of the block, used to identify and verify the block in the blockchain. + */ @jsonMember(() => ({ name: 'hash', constructor: Hash, @@ -417,18 +594,35 @@ export class BlockV1 { })) public hash: Hash; + /** + * The header of the block, containing metadata such as block height, era ID, and timestamp. + */ @jsonMember({ name: 'header', constructor: () => BlockHeaderV1 }) public header: BlockHeaderV1; + /** + * The body of the block, which contains the transactions and related data for the block. + */ @jsonMember({ name: 'body', constructor: () => BlockBodyV1 }) public body: BlockBodyV1; + /** + * An array of proofs associated with the block, used to verify the authenticity of the block. + */ @jsonArrayMember(Proof, { name: 'proofs' }) public proofs: Proof[]; } +/** + * Represents the body of a version 1 block in the blockchain. + * The body contains essential data related to transactions, deploys, and other actions within the block. + */ @jsonObject export class BlockBodyV1 { + /** + * The list of deploy hashes included in the block. + * Deploys represent the transactions that are being executed within this block. + */ @jsonArrayMember(() => Hash, { name: 'deploy_hashes', serializer: (value: Hash[]) => value.map(it => it.toJSON()), @@ -436,6 +630,9 @@ export class BlockBodyV1 { }) public deployHashes: Hash[]; + /** + * The proposer of the block, which represents the entity that created or proposed the block. + */ @jsonMember(() => ({ name: 'proposer', constructor: Proposer, @@ -444,6 +641,10 @@ export class BlockBodyV1 { })) public proposer: Proposer; + /** + * The list of transfer hashes included in the block. + * Transfers represent the transactions related to the movement of tokens within the blockchain. + */ @jsonArrayMember(() => Hash, { name: 'transfer_hashes', serializer: (value: Hash[]) => value.map(it => it.toJSON()), @@ -452,8 +653,15 @@ export class BlockBodyV1 { public transferHashes: Hash[]; } +/** + * Represents a version 2 block in the blockchain. + * A `BlockV2` includes a hash, a header containing metadata, and the body containing the block's transactions and related data. + */ @jsonObject export class BlockV2 { + /** + * The unique hash of the block, used to identify and verify the block in the blockchain. + */ @jsonMember(() => ({ name: 'hash', constructor: Hash, @@ -462,15 +670,29 @@ export class BlockV2 { })) public hash: Hash; + /** + * The header of the block, which contains metadata such as the block's height, parent hash, and protocol version. + */ @jsonMember({ name: 'header', constructor: () => BlockHeaderV2 }) public header: BlockHeaderV2; + /** + * The body of the block, which contains the transactions, deploys, and other data related to the block's content. + */ @jsonMember({ name: 'body', constructor: () => BlockBodyV2 }) public body: BlockBodyV2; } +/** + * Represents the header of a version 1 block in the blockchain. + * The header contains metadata about the block, such as its height, parent hash, protocol version, and timestamps. + */ @jsonObject export class BlockHeaderV1 { + /** + * The accumulated seed used for randomness in block generation. + * This seed is generated from previous blocks and influences the consensus. + */ @jsonMember(() => ({ name: 'accumulated_seed', constructor: Hash, @@ -485,6 +707,10 @@ export class BlockHeaderV1 { })) public accumulatedSeed?: Hash; + /** + * The hash of the block's body, which contains the transactions and other block data. + * This is used to verify the integrity of the block's contents. + */ @jsonMember(() => ({ name: 'body_hash', constructor: Hash, @@ -493,12 +719,24 @@ export class BlockHeaderV1 { })) public bodyHash: Hash; + /** + * The era ID in which this block was created. + * The era ID represents the block's position within a specific era in the blockchain. + */ @jsonMember({ name: 'era_id', constructor: Number }) public eraID: number; + /** + * The height of the block in the blockchain. + * The block height indicates its position relative to the first block in the chain (genesis block). + */ @jsonMember({ name: 'height', constructor: Number }) public height: number; + /** + * The hash of the parent block, linking this block to its predecessor in the chain. + * The parent hash is used to verify the continuity of the blockchain. + */ @jsonMember(() => ({ name: 'parent_hash', constructor: Hash, @@ -507,12 +745,22 @@ export class BlockHeaderV1 { })) public parentHash: Hash; + /** + * The protocol version used for this block, indicating the version of the consensus rules. + */ @jsonMember({ name: 'protocol_version', constructor: String }) public protocolVersion?: string; + /** + * A random bit used for consensus, which may play a role in the block's selection or generation. + */ @jsonMember({ name: 'random_bit', constructor: Boolean }) public randomBit: boolean; + /** + * The hash of the state root, representing the state of the blockchain after this block is applied. + * The state root hash is used to verify the consistency of the blockchain's state. + */ @jsonMember(() => ({ name: 'state_root_hash', constructor: Hash, @@ -521,6 +769,10 @@ export class BlockHeaderV1 { })) public stateRootHash: Hash; + /** + * The timestamp indicating when the block was created. + * This timestamp helps to determine the block's position in time within the blockchain. + */ @jsonMember(() => ({ name: 'timestamp', constructor: Timestamp, @@ -529,12 +781,24 @@ export class BlockHeaderV1 { })) public timestamp: Timestamp; + /** + * The era end details for this block's era, if available. + * The `eraEnd` may include information about the transition from one era to another. + */ @jsonMember(() => ({ name: 'era_end', constructor: EraEndV1 })) public eraEnd?: EraEndV1; } +/** + * Represents the header of a version 2 block in the blockchain. + * Contains metadata such as the block's height, parent hash, timestamp, gas price, and more. + */ @jsonObject export class BlockHeaderV2 { + /** + * The accumulated seed used for randomness in block generation. + * This seed is generated from previous blocks and influences the consensus. + */ @jsonMember(() => ({ name: 'accumulated_seed', constructor: Hash, @@ -549,6 +813,10 @@ export class BlockHeaderV2 { })) public accumulatedSeed?: Hash; + /** + * The hash of the block's body, which contains the transactions and other data. + * This is used to verify the integrity of the block's contents. + */ @jsonMember(() => ({ name: 'body_hash', constructor: Hash, @@ -557,15 +825,27 @@ export class BlockHeaderV2 { })) public bodyHash: Hash; + /** + * The era ID in which the block was created, indicating its position within a blockchain era. + */ @jsonMember({ name: 'era_id', constructor: Number }) public eraID: number; + /** + * The current gas price for transactions within this block. + */ @jsonMember({ name: 'current_gas_price', constructor: Number }) public currentGasPrice: number; + /** + * The height of the block in the blockchain, representing its position in the chain. + */ @jsonMember({ name: 'height', constructor: Number }) public height: number; + /** + * The hash of the parent block, linking this block to its predecessor in the chain. + */ @jsonMember(() => ({ name: 'parent_hash', constructor: Hash, @@ -574,6 +854,9 @@ export class BlockHeaderV2 { })) public parentHash: Hash; + /** + * The proposer who created this block. + */ @jsonMember(() => ({ name: 'proposer', constructor: Proposer, @@ -582,12 +865,21 @@ export class BlockHeaderV2 { })) public proposer: Proposer; + /** + * The protocol version used for this block. + */ @jsonMember({ name: 'protocol_version', constructor: String }) public protocolVersion?: string; + /** + * A random bit used for consensus, which may play a role in block selection or generation. + */ @jsonMember({ name: 'random_bit', constructor: Boolean }) public randomBit: boolean; + /** + * The hash of the state root, representing the state of the blockchain after this block is applied. + */ @jsonMember(() => ({ name: 'state_root_hash', constructor: Hash, @@ -596,6 +888,9 @@ export class BlockHeaderV2 { })) public stateRootHash: Hash; + /** + * The hash of the block that switched the state, marking the end of an era or other significant event. + */ @jsonMember(() => ({ name: 'last_switch_block_hash', constructor: Hash, @@ -604,6 +899,9 @@ export class BlockHeaderV2 { })) public lastSwitchBlockHash: Hash; + /** + * The timestamp when the block was created. + */ @jsonMember(() => ({ name: 'timestamp', constructor: Timestamp, @@ -612,12 +910,21 @@ export class BlockHeaderV2 { })) public timestamp: Timestamp; + /** + * The era end details for this block's era, if available. + */ @jsonMember(() => ({ name: 'era_end', constructor: EraEndV2 })) public eraEnd?: EraEndV2; } +/** + * Represents the body of a version 2 block, including the transactions and rewarded signatures. + */ @jsonObject export class BlockBodyV2 { + /** + * The list of transactions included in the block. + */ @jsonArrayMember(BlockTransaction, { name: 'transactions', deserializer: (json: any) => @@ -625,39 +932,75 @@ export class BlockBodyV2 { }) public transactions: BlockTransaction[]; + /** + * The list of signature IDs that were rewarded in this block. + */ @jsonArrayMember(Number, { name: 'rewarded_signatures' }) public rewardedSignatures: number[]; } +/** + * A wrapper for blocks that can contain either a version 1 or version 2 block. + */ @jsonObject export class BlockWrapper { + /** + * A version 1 block, if available. + */ @jsonMember({ name: 'Version1', constructor: BlockV1 }) public blockV1?: BlockV1; + /** + * A version 2 block, if available. + */ @jsonMember({ name: 'Version2', constructor: BlockV2 }) public blockV2?: BlockV2; } +/** + * A block with associated proofs, which include cryptographic signatures for verification. + */ @jsonObject export class BlockWithSignatures { + /** + * The block object containing either a version 1 or version 2 block. + */ @jsonMember({ name: 'block', constructor: BlockWrapper }) public block: BlockWrapper; + /** + * The list of proofs associated with the block, used for validating its authenticity. + */ @jsonArrayMember(Proof, { name: 'proofs' }) public proofs: Proof[]; } +/** + * A wrapper for block headers, which can contain either a version 1 or version 2 block header. + */ @jsonObject export class BlockHeaderWrapper { + /** + * A version 1 block header, if available. + */ @jsonMember({ name: 'Version1', constructor: BlockHeaderV1 }) public blockHeaderV1?: BlockHeaderV1; + /** + * A version 2 block header, if available. + */ @jsonMember({ name: 'Version2', constructor: BlockHeaderV2 }) public blockHeaderV2?: BlockHeaderV2; } +/** + * Represents a block header that can be either version 1 or version 2, with various metadata about the block. + */ @jsonObject export class BlockHeader { + /** + * The accumulated seed used for randomness in block generation. + */ @jsonMember(() => ({ name: 'accumulated_seed', constructor: Hash, @@ -672,6 +1015,9 @@ export class BlockHeader { })) public accumulatedSeed?: Hash; + /** + * The hash of the block's body, used to verify the block's contents. + */ @jsonMember(() => ({ name: 'body_hash', constructor: Hash, @@ -680,15 +1026,27 @@ export class BlockHeader { })) public bodyHash: Hash; + /** + * The era ID in which the block was created. + */ @jsonMember({ name: 'era_id', constructor: Number }) public eraID: number; + /** + * The current gas price for transactions within this block. + */ @jsonMember({ name: 'current_gas_price', constructor: Number }) public currentGasPrice: number; + /** + * The height of the block in the blockchain. + */ @jsonMember({ name: 'height', constructor: Number }) public height: number; + /** + * The hash of the parent block. + */ @jsonMember(() => ({ name: 'parent_hash', constructor: Hash, @@ -697,6 +1055,9 @@ export class BlockHeader { })) public parentHash: Hash; + /** + * The proposer who created this block. + */ @jsonMember(() => ({ name: 'proposer', constructor: Proposer, @@ -705,12 +1066,21 @@ export class BlockHeader { })) public proposer: Proposer; + /** + * The protocol version used for this block. + */ @jsonMember({ name: 'protocol_version', constructor: String }) public protocolVersion?: string; + /** + * A random bit used for consensus. + */ @jsonMember({ name: 'random_bit', constructor: Boolean }) public randomBit: boolean; + /** + * The hash of the state root. + */ @jsonMember(() => ({ name: 'state_root_hash', constructor: Hash, @@ -719,6 +1089,9 @@ export class BlockHeader { })) public stateRootHash: Hash; + /** + * The timestamp indicating when the block was created. + */ @jsonMember(() => ({ name: 'timestamp', constructor: Timestamp, @@ -727,20 +1100,36 @@ export class BlockHeader { })) public timestamp: Timestamp; + /** + * The era end details, if available, for this block's era. + */ @jsonMember(() => ({ name: 'era_end', constructor: EraEnd })) public eraEnd?: EraEnd | null; private originBlockHeaderV1?: BlockHeaderV1; private originBlockHeaderV2?: BlockHeaderV2; + /** + * Retrieves the version 1 block header, if available. + * @returns The version 1 block header, or `undefined` if not available. + */ public getBlockHeaderV1(): BlockHeaderV1 | undefined { return this.originBlockHeaderV1; } + /** + * Retrieves the version 2 block header, if available. + * @returns The version 2 block header, or `undefined` if not available. + */ public getBlockHeaderV2(): BlockHeaderV2 | undefined { return this.originBlockHeaderV2; } + /** + * Creates a new `BlockHeader` instance from a version 1 block header. + * @param header - The version 1 block header. + * @returns A new `BlockHeader` instance. + */ static newBlockHeaderFromV1(header: BlockHeaderV1): BlockHeader { const blockHeader = new BlockHeader(); blockHeader.accumulatedSeed = header.accumulatedSeed; @@ -760,6 +1149,11 @@ export class BlockHeader { return blockHeader; } + /** + * Creates a new `BlockHeader` instance from a version 2 block header. + * @param header - The version 2 block header. + * @returns A new `BlockHeader` instance. + */ static newBlockHeaderFromV2(header: BlockHeaderV2): BlockHeader { const blockHeader = new BlockHeader(); blockHeader.accumulatedSeed = header.accumulatedSeed; diff --git a/src/types/BlockProposer.ts b/src/types/BlockProposer.ts index 456d4709b..8d0b96dd9 100644 --- a/src/types/BlockProposer.ts +++ b/src/types/BlockProposer.ts @@ -1,17 +1,27 @@ import { jsonObject, jsonMember } from 'typedjson'; import * as keypair from './keypair'; +/** + * Represents a proposer in the blockchain context. + * A proposer is an entity that proposes new blocks, identified by a public key + * and an optional system status. + */ @jsonObject export class Proposer { + /** + * Indicates if the proposer is a system-level entity (without a public key). + */ @jsonMember({ name: 'isSystem', constructor: Boolean }) isSystem: boolean; + /** + * Public key of the proposer, defined if the proposer is not a system entity. + */ @jsonMember({ name: 'publicKey', constructor: keypair.PublicKey, deserializer: json => { if (!json) return; - return keypair.PublicKey.fromJSON(json); }, serializer: value => { @@ -21,11 +31,21 @@ export class Proposer { }) publicKey?: keypair.PublicKey; + /** + * Constructs a new `Proposer` instance. + * @param isSystem - Indicates if the proposer is a system-level proposer. + * @param publicKey - Optional public key if the proposer is not a system entity. + */ constructor(isSystem = false, publicKey?: keypair.PublicKey) { this.isSystem = isSystem; this.publicKey = publicKey; } + /** + * Creates a `Proposer` instance from a string representation. + * @param src - A string representing the proposer. '00' indicates a system proposer. + * @returns A new `Proposer` instance. + */ static fromString(src: string): Proposer { if (src === '00') { return new Proposer(true); @@ -34,10 +54,20 @@ export class Proposer { return new Proposer(false, pubKey); } + /** + * Checks if the proposer is a system-level entity. + * @returns `true` if the proposer is a system entity, otherwise `false`. + */ isSystemProposer(): boolean { return this.isSystem; } + /** + * Retrieves the public key of the proposer. + * Throws an error if the proposer is a system entity without a public key. + * @returns The public key of the proposer. + * @throws Will throw an error if the proposer is a system proposer. + */ getPublicKey(): keypair.PublicKey { if (this.isSystem) { throw new Error("System proposer doesn't have a public key"); @@ -45,14 +75,28 @@ export class Proposer { return this.publicKey!; } + /** + * Retrieves the public key of the proposer, if available. + * @returns The public key if defined; otherwise, `undefined`. + */ getPublicKeyOptional(): keypair.PublicKey | undefined { return this.publicKey; } + /** + * Serializes the proposer instance to JSON. + * System proposers are represented as '00'; otherwise, the public key is serialized. + * @returns A JSON string representing the proposer. + */ toJSON(): string { return this.isSystem ? '00' : JSON.stringify(this.publicKey); } + /** + * Deserializes a JSON string to create a `Proposer` instance. + * @param json - A JSON string representing the proposer. + * @returns A new `Proposer` instance. + */ static fromJSON(json: string): Proposer { if (json === '00') { return new Proposer(true); diff --git a/src/types/ByteConverters.ts b/src/types/ByteConverters.ts index e108c7372..ad81c1102 100644 --- a/src/types/ByteConverters.ts +++ b/src/types/ByteConverters.ts @@ -4,21 +4,22 @@ import { arrayify, concat } from '@ethersproject/bytes'; import { blake2b } from '@noble/hashes/blake2b'; /** - * Convert number to bytes - * @param bitSize The bit size of the integer - * @param signed `true` if the integer is signed, `false` if not - * @returns `Uint8Array` buffer representation of the integer + * Converts a BigNumberish value to bytes with specified bit size and signedness. + * @param bitSize - The bit size of the integer. + * @param signed - `true` if the integer is signed; `false` otherwise. + * @returns A function that converts a BigNumberish value into a `Uint8Array` byte representation. */ export const toBytesNumber = (bitSize: number, signed: boolean) => ( value: BigNumberish ): Uint8Array => { const val = BigNumber.from(value); - // Check bounds are safe for encoding + // Calculate the maximum allowed unsigned value for the given bit size const maxUintValue = MaxUint256.mask(bitSize); if (signed) { - const bounds = maxUintValue.mask(bitSize - 1); // 1 bit for signed + // Calculate signed bounds for the given bit size + const bounds = maxUintValue.mask(bitSize - 1); if (val.gt(bounds) || val.lt(bounds.add(One).mul(NegativeOne))) { throw new Error('value out-of-bounds, value: ' + value); } @@ -31,18 +32,14 @@ export const toBytesNumber = (bitSize: number, signed: boolean) => ( const bytes = arrayify(valTwos); if (valTwos.gte(0)) { - // for positive number, we had to deal with paddings if (bitSize > 64) { - // if zero just return zero if (valTwos.eq(0)) { return bytes; } - // for u128, u256, u512, we have to and append extra byte for length return concat([bytes, Uint8Array.from([bytes.length])]) .slice() .reverse(); } else { - // for other types, we have to add padding 0s const byteLength = bitSize / 8; return concat([ bytes.slice().reverse(), @@ -55,56 +52,59 @@ export const toBytesNumber = (bitSize: number, signed: boolean) => ( }; /** - * Converts `u8` to little endian. + * Converts an 8-bit unsigned integer (`u8`) to little-endian byte format. */ export const toBytesU8 = toBytesNumber(8, false); /** - * Converts `i32` to little endian. + * Converts a 32-bit signed integer (`i32`) to little-endian byte format. */ export const toBytesI32 = toBytesNumber(32, true); /** - * Converts `u32` to little endian. + * Converts a 32-bit unsigned integer (`u32`) to little-endian byte format. */ export const toBytesU32 = toBytesNumber(32, false); /** - * Converts `u64` to little endian. + * Converts a 64-bit unsigned integer (`u64`) to little-endian byte format. */ export const toBytesU64 = toBytesNumber(64, false); /** - * Converts `i64` to little endian. + * Converts a 64-bit signed integer (`i64`) to little-endian byte format. */ export const toBytesI64 = toBytesNumber(64, true); /** - * Converts `u128` to little endian. + * Converts a 128-bit unsigned integer (`u128`) to little-endian byte format. */ export const toBytesU128 = toBytesNumber(128, false); /** - * Converts `u256` to little endian. + * Converts a 256-bit unsigned integer (`u256`) to little-endian byte format. */ export const toBytesU256 = toBytesNumber(256, false); /** - * Converts `u512` to little endian. + * Converts a 512-bit unsigned integer (`u512`) to little-endian byte format. */ export const toBytesU512 = toBytesNumber(512, false); /** - * @deprecated + * Converts a deploy hash to bytes. + * @param deployHash - A `Uint8Array` representing the deploy hash. + * @returns The `Uint8Array` representation of the deploy hash. + * @deprecated This function will be removed in future versions. */ -export const toBytesDeployHash = (deployHash: Uint8Array) => { +export const toBytesDeployHash = (deployHash: Uint8Array): Uint8Array => { return deployHash; }; /** - * Serializes a string into an array of bytes - * @param str The string to be converted - * @returns A `Uint8Array` representation of the string + * Serializes a string into a byte array. + * @param str - The string to be converted. + * @returns A `Uint8Array` representation of the string, including its length as a `u32` prefix. */ export function toBytesString(str: string): Uint8Array { const arr = Uint8Array.from(Buffer.from(str)); @@ -112,30 +112,28 @@ export function toBytesString(str: string): Uint8Array { } /** - * Deserializes an array of bytes into a string - * @param byte `Uint8Array` buffer of bytes to be deserialized - * @returns The serialized string + * Deserializes a byte array into a string. + * @param byte - `Uint8Array` representing the serialized string. + * @returns The deserialized string. */ export const fromBytesString = (byte: Uint8Array): string => { return Buffer.from(byte).toString(); }; /** - * Serializes an array of u8, equal to Vec in rust. - * @param arr `Uint8Array` buffer of u8 integers - * @returns Serialized `Uint8Array` buffer + * Serializes an array of `u8` values, equivalent to `Vec` in Rust. + * @param arr - A `Uint8Array` buffer of `u8` integers. + * @returns A serialized `Uint8Array` with the array's length as a `u32` prefix. */ export function toBytesArrayU8(arr: Uint8Array): Uint8Array { return concat([toBytesU32(arr.length), arr]); } /** - * Use blake2b to compute hash of ByteArray - * @param x Byte array of type `Uint8Array` to compute the blake2b hash on - * @returns `Uint8Array` buffer of the blake2b hash + * Computes the Blake2b hash of a byte array. + * @param x - A `Uint8Array` byte array to compute the Blake2b hash on. + * @returns A `Uint8Array` buffer containing the 32-byte Blake2b hash. */ export function byteHash(x: Uint8Array): Uint8Array { - return blake2b(x, { - dkLen: 32 - }); + return blake2b(x, { dkLen: 32 }); } diff --git a/src/types/Contract.ts b/src/types/Contract.ts index 2f5b8ecd7..afe1c5cc6 100644 --- a/src/types/Contract.ts +++ b/src/types/Contract.ts @@ -1,11 +1,16 @@ import { jsonArrayMember, jsonMember, jsonObject } from 'typedjson'; - import { ContractHash, ContractPackageHash } from './key'; import { EntryPointV1 } from './EntryPoint'; import { NamedKeys } from './NamedKey'; +/** + * Represents a smart contract on the blockchain, including its unique identifiers, entry points, named keys, and protocol version. + */ @jsonObject export class Contract { + /** + * The unique hash representing the contract package. + */ @jsonMember({ name: 'contract_package_hash', constructor: ContractPackageHash, @@ -14,6 +19,9 @@ export class Contract { }) contractPackageHash: ContractPackageHash; + /** + * The unique hash representing the WebAssembly (Wasm) code of the contract. + */ @jsonMember({ name: 'contract_wasm_hash', constructor: ContractHash, @@ -22,15 +30,32 @@ export class Contract { }) contractWasmHash: ContractHash; + /** + * The list of entry points (functions) that can be called on this contract. + */ @jsonArrayMember(EntryPointV1, { name: 'entry_points' }) entryPoints: EntryPointV1[]; + /** + * The named keys associated with the contract, providing access to specific values or data stored by the contract. + */ @jsonMember({ name: 'named_keys', constructor: NamedKeys }) namedKeys: NamedKeys; + /** + * The protocol version of the contract, indicating compatibility with specific blockchain protocol versions. + */ @jsonMember({ name: 'protocol_version', constructor: String }) protocolVersion: string; + /** + * Constructs a new `Contract` instance. + * @param contractPackageHash - The unique hash for the contract package. + * @param contractWasmHash - The unique hash for the Wasm code of the contract. + * @param entryPoints - An array of entry points defining functions available in the contract. + * @param namedKeys - Named keys providing access to specific stored data within the contract. + * @param protocolVersion - The protocol version for this contract. + */ constructor( contractPackageHash: ContractPackageHash, contractWasmHash: ContractHash, diff --git a/src/types/ContractPackage.ts b/src/types/ContractPackage.ts index 89d3007e1..d8a6698da 100644 --- a/src/types/ContractPackage.ts +++ b/src/types/ContractPackage.ts @@ -1,25 +1,48 @@ import { jsonArrayMember, jsonMember, jsonObject } from 'typedjson'; import { ContractHash, URef } from './key'; +/** + * Represents a disabled contract version, marking specific versions as incompatible with the current protocol. + */ @jsonObject class DisabledContractVersion { + /** + * The version number of the contract. + */ @jsonMember({ name: 'contract_version', constructor: Number }) contractVersion: number; + /** + * Major version of the protocol that disables this contract version. + */ @jsonMember({ name: 'protocol_version_major', constructor: Number }) protocolVersionMajor: number; + /** + * Constructs a new `DisabledContractVersion` instance. + * @param contractVersion - The version of the contract. + * @param protocolVersionMajor - The major protocol version disabling this contract version. + */ constructor(contractVersion: number, protocolVersionMajor: number) { this.contractVersion = contractVersion; this.protocolVersionMajor = protocolVersionMajor; } } +/** + * Represents a group of keys associated with a contract, allowing access control and permissions management. + */ @jsonObject export class ContractGroup { + /** + * The name of the group. + */ @jsonMember({ name: 'group', constructor: String }) group: string; + /** + * The list of URef keys associated with this group, defining permissions for contract interaction. + */ @jsonArrayMember(URef, { name: 'keys', serializer: (value: URef[]) => value.map(it => it.toJSON()), @@ -27,14 +50,25 @@ export class ContractGroup { }) keys: URef[]; + /** + * Constructs a new `ContractGroup` instance. + * @param group - The name of the group. + * @param keys - An array of URef keys associated with the group. + */ constructor(group: string, keys: URef[]) { this.group = group; this.keys = keys; } } +/** + * Represents a specific version of a contract, identified by a unique hash and protocol compatibility. + */ @jsonObject export class ContractVersion { + /** + * The unique hash identifying this version of the contract. + */ @jsonMember({ name: 'contract_hash', constructor: ContractHash, @@ -43,12 +77,24 @@ export class ContractVersion { }) contractHash: ContractHash; + /** + * The version number of the contract. + */ @jsonMember({ name: 'contract_version', constructor: Number }) contractVersion: number; + /** + * Major version of the protocol that this contract version is compatible with. + */ @jsonMember({ name: 'protocol_version_major', constructor: Number }) protocolVersionMajor: number; + /** + * Constructs a new `ContractVersion` instance. + * @param contractHash - The unique hash for this version of the contract. + * @param contractVersion - The version number of the contract. + * @param protocolVersionMajor - The major protocol version compatible with this contract. + */ constructor( contractHash: ContractHash, contractVersion: number, @@ -60,8 +106,14 @@ export class ContractVersion { } } +/** + * Represents a package containing different versions and groups of a contract, including access control and lock status. + */ @jsonObject export class ContractPackage { + /** + * Access key (URef) for the contract package, controlling permissions. + */ @jsonMember({ name: 'access_key', constructor: URef, @@ -70,18 +122,38 @@ export class ContractPackage { }) accessKey: URef; + /** + * Array of disabled contract versions, marking incompatible versions. + */ @jsonArrayMember(DisabledContractVersion, { name: 'disabled_versions' }) disabledVersions: DisabledContractVersion[]; + /** + * Array of contract groups, managing access control with sets of URef keys. + */ @jsonArrayMember(ContractGroup, { name: 'groups' }) groups: ContractGroup[]; + /** + * Array of contract versions, each compatible with a specific protocol version. + */ @jsonArrayMember(ContractVersion, { name: 'versions' }) versions: ContractVersion[]; + /** + * Lock status of the contract package, indicating whether the package is locked or unlocked. + */ @jsonMember({ name: 'lock_status', constructor: String }) lockStatus: string; + /** + * Constructs a new `ContractPackage` instance. + * @param accessKey - The URef access key for controlling the contract package. + * @param disabledVersions - Array of disabled contract versions. + * @param groups - Array of contract groups for access management. + * @param versions - Array of contract versions within this package. + * @param lockStatus - The lock status of the contract package. + */ constructor( accessKey: URef, disabledVersions: DisabledContractVersion[], diff --git a/src/types/Conversions.ts b/src/types/Conversions.ts index b6dc0018c..a9ef6b503 100644 --- a/src/types/Conversions.ts +++ b/src/types/Conversions.ts @@ -1,13 +1,14 @@ import { BigNumber, BigNumberish } from '@ethersproject/bignumber'; /** - * A utility class for various data conversions used in the CasperLabs ecosystem. + * A utility class for various data conversions used in the Casper ecosystem. + * Provides methods to convert between different encodings (Base64, Base16) and to perform conversions between CSPR and motes. */ export class Conversions { /** - * Encodes a Uint8Array into a string using Base-64 encoding. + * Encodes a `Uint8Array` into a string using Base-64 encoding. * - * @param bytes - The Uint8Array to be encoded. + * @param bytes - The `Uint8Array` to be encoded. * @returns A Base-64 encoded string representation of the input bytes. * * @example @@ -20,10 +21,10 @@ export class Conversions { } /** - * Decodes a Base-64 encoded string and returns a Uint8Array of bytes. + * Decodes a Base-64 encoded string and returns a `Uint8Array` of bytes. * * @param base64String - The Base-64 encoded string to be decoded. - * @returns A Uint8Array containing the decoded bytes. + * @returns A `Uint8Array` containing the decoded bytes. * * @example * const base64 = "SGVsbG8="; @@ -50,9 +51,9 @@ export class Conversions { } /** - * Encodes a Uint8Array into a string using Base-16 (hexadecimal) encoding. + * Encodes a `Uint8Array` into a string using Base-16 (hexadecimal) encoding. * - * @param bytes - The Uint8Array to be encoded. + * @param bytes - The `Uint8Array` to be encoded. * @returns A Base-16 encoded string representation of the input bytes. * * @example @@ -65,10 +66,10 @@ export class Conversions { } /** - * Decodes a Base-16 (hexadecimal) encoded string and returns a Uint8Array of bytes. + * Decodes a Base-16 (hexadecimal) encoded string and returns a `Uint8Array` of bytes. * * @param base16String - The Base-16 encoded string to be decoded. - * @returns A Uint8Array containing the decoded bytes. + * @returns A `Uint8Array` containing the decoded bytes. * * @example * const base16 = "48656c6c6f"; diff --git a/src/types/Deploy.ts b/src/types/Deploy.ts index c90807512..e9d7c27c6 100644 --- a/src/types/Deploy.ts +++ b/src/types/Deploy.ts @@ -23,8 +23,16 @@ import { ExecutableDeployItem } from './ExecutableDeployItem'; import { byteHash, toBytesU32 } from './ByteConverters'; import { Conversions } from './Conversions'; +/** + * Represents the header of a deploy in the blockchain. + * The header contains metadata such as the account initiating the deploy, the body hash, gas price, timestamp, TTL, and dependencies. + */ @jsonObject export class DeployHeader { + /** + * The public key of the account initiating the deploy. + * This key is used to verify the identity of the account making the deploy request. + */ @jsonMember({ constructor: PublicKey, deserializer: json => { @@ -38,6 +46,10 @@ export class DeployHeader { }) public account?: PublicKey; + /** + * The hash of the body of the deploy, which is used to verify the contents of the deploy. + * The body contains the session logic and payment logic of the deploy. + */ @jsonMember({ constructor: Hash, deserializer: json => { @@ -51,9 +63,17 @@ export class DeployHeader { }) public bodyHash?: Hash; + /** + * The name of the blockchain chain that the deploy is associated with. + * This helps prevent the deploy from being accidentally or maliciously included in a different chain. + */ @jsonMember({ name: 'chain_name', constructor: String }) public chainName = ''; + /** + * A list of other deploys that must be executed before this one. + * This ensures dependencies are executed in the correct order. + */ @jsonArrayMember(Hash, { name: 'dependencies', serializer: (value: Hash[]) => value.map(it => it.toJSON()), @@ -61,9 +81,17 @@ export class DeployHeader { }) public dependencies: Hash[] = []; + /** + * The price of gas for executing the deploy. + * Gas is used to pay for the computational resources required to process the deploy. + */ @jsonMember({ name: 'gas_price', constructor: Number }) public gasPrice = 1; + /** + * The timestamp when the deploy was created. + * This timestamp is used to determine the deploy's position in time. + */ @jsonMember({ constructor: Timestamp, deserializer: json => Timestamp.fromJSON(json), @@ -71,6 +99,10 @@ export class DeployHeader { }) public timestamp: Timestamp = new Timestamp(new Date()); + /** + * The time-to-live (TTL) for the deploy, after which it will expire if not executed. + * The default TTL is 30 minutes. + */ @jsonMember({ constructor: Duration, deserializer: json => Duration.fromJSON(json), @@ -78,6 +110,16 @@ export class DeployHeader { }) public ttl: Duration = new Duration(30 * 60 * 1000); + /** + * Constructs a `DeployHeader` instance with the specified parameters. + * @param chainName The name of the blockchain chain. + * @param dependencies A list of deploys that must be executed before this one. + * @param gasPrice The gas price for the deploy. + * @param timestamp The timestamp when the deploy is created. + * @param ttl The TTL for the deploy. + * @param account The public key of the account initiating the deploy (optional). + * @param bodyHash The hash of the body of the deploy (optional). + */ constructor( chainName = '', dependencies: Hash[] = [], @@ -96,6 +138,10 @@ export class DeployHeader { this.bodyHash = bodyHash; } + /** + * Converts the deploy header to a byte array for transmission or storage. + * @returns A `Uint8Array` representing the deploy header in byte format. + */ public toBytes(): Uint8Array { const accountBytes = this.account?.bytes() ?? new Uint8Array(); const timestampBytes = new Uint8Array( @@ -145,38 +191,62 @@ export class DeployHeader { return result; } + /** + * Returns a default `DeployHeader` instance with default values. + * @returns A `DeployHeader` instance with default values. + */ public static default(): DeployHeader { return new DeployHeader(); } } +/** + * Represents a deploy in the blockchain, including the header, payment, session, and approvals. + * A `Deploy` object is used to package the logic for executing a contract, payment, or transfer on the blockchain. + */ @jsonObject export class Deploy { + /** + * A list of approvals, including signatures from accounts that have approved the deploy. + */ @jsonArrayMember(() => Approval) public approvals: Approval[] = []; + /** + * The unique hash that identifies this deploy. This hash is used to verify the integrity of the deploy. + */ @jsonMember({ deserializer: json => Hash.fromJSON(json), serializer: value => value.toJSON() }) public hash: Hash; + /** + * The header of the deploy, which contains metadata such as the account, gas price, timestamp, and TTL. + */ @jsonMember({ constructor: DeployHeader }) public header: DeployHeader; + /** + * The executable item representing the payment logic of the deploy. + */ @jsonMember({ constructor: ExecutableDeployItem }) public payment: ExecutableDeployItem; + /** + * The executable item representing the session logic of the deploy. + */ @jsonMember({ constructor: ExecutableDeployItem }) public session: ExecutableDeployItem; /** - * Constructs a `Deploy` object - * @param hash The DeployHash identifying this Deploy - * @param header The deploy header - * @param payment An ExecutableDeployItem representing the payment logic - * @param session An ExecutableDeployItem representing the session logic - * @param approvals An array of signatures and associated accounts who have approved this deploy + * Constructs a `Deploy` object. + * + * @param hash The deploy hash identifying this deploy. + * @param header The deploy header containing metadata. + * @param payment The executable deploy item representing the payment logic. + * @param session The executable deploy item representing the session logic. + * @param approvals An array of signatures and accounts who have approved this deploy. */ constructor( hash: Hash, @@ -192,6 +262,11 @@ export class Deploy { this.hash = hash; } + /** + * Validates the deploy by checking its body hash, deploy hash, and approval signatures. + * + * @returns `true` if the deploy is valid, otherwise throws an error. + */ public validate(): boolean { const paymentBytes = this.payment.bytes(); const sessionBytes = this.session.bytes(); @@ -222,12 +297,22 @@ export class Deploy { return true; } + /** + * Signs the deploy with a given private key and adds the signature to the approvals list. + * + * @param keys The private key used to sign the deploy. + */ public async sign(keys: PrivateKey): Promise { const signatureBytes = await keys.sign(this.hash.toBytes()); const signature = new HexBytes(signatureBytes); this.approvals.push(new Approval(keys.publicKey, signature)); } + /** + * Converts the deploy object into a byte array for transmission or storage. + * + * @returns A `Uint8Array` representing the deploy in byte format. + */ toBytes(): Uint8Array { return concat([ this.header.toBytes(), @@ -238,11 +323,12 @@ export class Deploy { } /** - * Sets already generated signature + * Sets an already generated signature for the deploy. * - * @param deploy the Deploy instance - * @param signature the Ed25519 or Secp256K1 signature - * @param publicKey the public key used to generate the signature + * @param deploy The deploy instance. + * @param signature The Ed25519 or Secp256K1 signature. + * @param publicKey The public key used to generate the signature. + * @returns A new `Deploy` instance with the added signature. */ public static setSignature( deploy: Deploy, @@ -254,6 +340,16 @@ export class Deploy { return deploy; } + /** + * Creates a new `Deploy` instance with the provided parameters. + * + * @param hash The deploy hash identifying this deploy. + * @param header The deploy header. + * @param payment The executable deploy item for the payment logic. + * @param session The executable deploy item for the session logic. + * @param approvals An array of approvals for the deploy. + * @returns A new `Deploy` object. + */ public static createNew( hash: Hash, header: DeployHeader, @@ -264,6 +360,14 @@ export class Deploy { return new Deploy(hash, header, payment, session, approvals); } + /** + * Creates a `Deploy` instance from the deploy header and session/payment logic. + * + * @param deployHeader The deploy header. + * @param payment The payment logic of the deploy. + * @param session The session logic of the deploy. + * @returns A new `Deploy` object. + */ public static fromHeaderAndItems( deployHeader: DeployHeader, payment: ExecutableDeployItem, @@ -277,6 +381,13 @@ export class Deploy { return Deploy.createNew(deployHash, deployHeader, payment, session); } + /** + * Converts the `Deploy` into a `Transaction` object. + * This method creates a transaction based on the deploy, including its payment and session logic. + * + * @param deploy The deploy object. + * @returns A new `Transaction` object created from the deploy. + */ static newTransactionFromDeploy(deploy: Deploy): Transaction { let paymentAmount = 0; const transactionEntryPoint: TransactionEntryPoint = new TransactionEntryPoint(); @@ -341,10 +452,10 @@ export class Deploy { } /** - * Convert a JSON representation of a deploy to a `Deploy` object + * Converts a JSON representation of a deploy to a `Deploy` object. * - * @param json A JSON representation of a `Deploy` - * @returns A `Deploy` object if successful, or throws an error if parsing fails + * @param json The JSON representation of a `Deploy`. + * @returns A `Deploy` object if successful, or throws an error if parsing fails. */ public static fromJSON(json: any): Deploy { let deploy: Deploy | undefined; @@ -380,28 +491,29 @@ export class Deploy { } /** - * Convert the deploy object to a JSON representation + * Converts the `Deploy` object into a JSON representation. * - * @param deploy The `Deploy` object to convert to JSON - * @returns A JSON version of the `Deploy`, which can be converted back later + * @param deploy The deploy object to convert to JSON. + * @returns A JSON representation of the deploy. */ public static toJson = (deploy: Deploy) => { const serializer = new TypedJSON(Deploy); - return { deploy: serializer.toPlainJson(deploy) }; }; /** - * Identifies whether this `Deploy` represents a transfer of CSPR - * @returns `true` if the `Deploy` is a `Transfer`, and `false` otherwise + * Identifies whether this `Deploy` represents a transfer of CSPR. + * + * @returns `true` if the deploy is a transfer, otherwise `false`. */ public isTransfer(): boolean { return this.session.isTransfer(); } /** - * Identifies whether this `Deploy` represents a standard payment, like that of gas payment - * @returns `true` if the `Deploy` is a standard payment, and `false` otherwise + * Identifies whether this `Deploy` represents a standard payment, like a gas payment. + * + * @returns `true` if the deploy is a standard payment, otherwise `false`. */ public isStandardPayment(): boolean { if (this.payment.isModuleBytes()) { @@ -412,23 +524,31 @@ export class Deploy { } /** - * Creates an instance of standard payment logic + * Creates an instance of standard payment logic for use in a `Deploy` object. + * This method is deprecated. It is recommended to use the `ExecutableDeployItem.standardPayment` method instead. + * * @deprecated Use {ExecutableDeployItem.standardPayment} instead + * @param paymentAmount The amount of motes to be used to pay for gas. This value should be expressed in motes, where 1 mote = 1 * 10^-9 CSPR. + * @returns An `ExecutableDeployItem` representing the standard payment logic, to be attached to a `Deploy`. * - * @param paymentAmount The amount of motes to be used to pay for gas - * @returns A standard payment, as an `ExecutableDeployItem` to be attached to a `Deploy` + * @example + * const paymentAmount = BigNumber.from('1000000'); + * const paymentItem = standardPayment(paymentAmount); */ export const standardPayment = (paymentAmount: BigNumber) => { return ExecutableDeployItem.standardPayment(paymentAmount); }; /** - * @deprecated Use Deploy.fromHeaderAndItems - * Builds a `Deploy` object from `DeployParams`, session logic, and payment logic - * @param deployParam The parameters of the deploy, see [DeployParams](#L1323) - * @param session The session logic of the deploy - * @param payment The payment logic of the deploy - * @returns A new `Deploy` object + * Builds a `Deploy` object from the given parameters, session logic, and payment logic. + * This method is deprecated. It is recommended to use `Deploy.fromHeaderAndItems` instead. + * + * @deprecated Use `Deploy.fromHeaderAndItems` instead + * @param deployParam The parameters used for creating the deploy. See [DeployParams](#L1323). + * @param session The session logic of the deploy, represented as an `ExecutableDeployItem`. + * @param payment The payment logic of the deploy, represented as an `ExecutableDeployItem`. + * @returns A new `Deploy` object that represents the entire deploy. + * */ export function makeDeploy( deployParam: DeployParams, @@ -456,9 +576,15 @@ export function makeDeploy( } /** - * Serializes an array of `Approval`s into a `Uint8Array` typed byte array - * @param approvals An array of `Approval`s to be serialized - * @returns `Uint8Array` typed byte array that can be deserialized to an array of `Approval`s + * Serializes an array of `Approval`s into a `Uint8Array` typed byte array. + * This is used to store or transmit the approvals associated with a deploy. + * + * @param approvals An array of `Approval` objects that represent signatures from accounts that have approved the deploy. + * @returns A `Uint8Array` typed byte array that can be deserialized back into an array of `Approval` objects. + * + * @example + * const approvals = [new Approval(publicKey, signature)]; + * const serializedApprovals = serializeApprovals(approvals); */ export const serializeApprovals = (approvals: Approval[]): Uint8Array => { const len = toBytesU32(approvals.length); @@ -473,16 +599,24 @@ export const serializeApprovals = (approvals: Approval[]): Uint8Array => { return concat([len, bytes]); }; -/** @deprecated The parameters of a `Deploy` object. Use Deploy.fromHeaderAndItems */ +/** + * The parameters of a `Deploy` object. + * This class is deprecated. Use `Deploy.fromHeaderAndItems` instead. + * + * It is used to configure the construction of a `Deploy` object. + * + * @deprecated The parameters of a `Deploy` object. Use Deploy.fromHeaderAndItems + */ export class DeployParams { /** - * Container for `Deploy` construction options. - * @param accountPublicKey The public key of the deploying account as a `PublicKey` - * @param chainName Name of the chain, to avoid the `Deploy` from being accidentally or maliciously included in a different chain. - * @param gasPrice Conversion rate between the cost of Wasm opcodes and the motes sent by the payment code, where 1 mote = 1 * 10^-9 CSPR - * @param ttl Time that the `Deploy` will remain valid for, in milliseconds. The default value is 1800000, which is 30 minutes - * @param dependencies Hex-encoded `Deploy` hashes of deploys which must be executed before this one. - * @param timestamp Note that timestamp is UTC, not local. + * Constructor for `DeployParams`. + * + * @param accountPublicKey The public key of the deploying account as a `PublicKey`. + * @param chainName The name of the blockchain chain to avoid the `Deploy` from being accidentally or maliciously included in another chain. + * @param gasPrice The conversion rate between the cost of Wasm opcodes and the motes sent by the payment code. 1 mote = 1 * 10^-9 CSPR. + * @param ttl The time-to-live (TTL) for the deploy, in milliseconds. The default value is 30 minutes (1800000 milliseconds). + * @param dependencies Hex-encoded `Deploy` hashes of deploys that must be executed before this one. + * @param timestamp The timestamp when the deploy is created, in UTC. */ constructor( public accountPublicKey: PublicKey, @@ -501,4 +635,7 @@ export class DeployParams { } } +/** + * Default TTL value used for deploys (30 minutes). + */ export const DEFAULT_DEPLOY_TTL = 1800000; diff --git a/src/types/DeployInfo.ts b/src/types/DeployInfo.ts index 87977dc34..a53d6a3a0 100644 --- a/src/types/DeployInfo.ts +++ b/src/types/DeployInfo.ts @@ -1,8 +1,15 @@ import { jsonObject, jsonMember, jsonArrayMember } from 'typedjson'; import { Hash, AccountHash, URef, TransferHash } from './key'; +/** + * Represents information about a deploy in the blockchain. + * This class encapsulates details such as the deploy hash, the account making the deploy, gas usage, source URef, and associated transfers. + */ @jsonObject export class DeployInfo { + /** + * The unique hash identifying the deploy. This hash is used to verify the integrity and authenticity of the deploy. + */ @jsonMember({ name: 'deploy_hash', constructor: Hash, @@ -11,6 +18,9 @@ export class DeployInfo { }) deployHash: Hash; + /** + * The account hash of the account initiating the deploy. This is used to identify the account responsible for the deploy. + */ @jsonMember({ name: 'from', constructor: AccountHash, @@ -19,9 +29,15 @@ export class DeployInfo { }) from: AccountHash; + /** + * The amount of gas used for the deploy. This value is typically in motes, a subunit of CSPR. + */ @jsonMember({ name: 'gas', constructor: String }) gas: string; + /** + * The source URef from which the deploy is triggered. URefs are used to identify a reference to a contract or resource in the blockchain. + */ @jsonMember({ name: 'source', constructor: URef, @@ -30,6 +46,9 @@ export class DeployInfo { }) source: URef; + /** + * A list of transfer hashes associated with the deploy. These are hashes that identify transfers (e.g., of CSPR or other assets) associated with the deploy. + */ @jsonArrayMember(TransferHash, { name: 'transfers', serializer: (value: TransferHash[]) => value.map(it => it.toJSON()), diff --git a/src/types/EntryPoint.ts b/src/types/EntryPoint.ts index 0e87c4115..57e8c13a6 100644 --- a/src/types/EntryPoint.ts +++ b/src/types/EntryPoint.ts @@ -1,7 +1,9 @@ import { jsonObject, jsonMember, jsonArrayMember, AnyT } from 'typedjson'; - import { CLTypeRaw } from './clvalue'; +/** + * Enum representing the type of entry point. + */ export enum EntryPointType { Session = 'Session', Contract = 'Contract', @@ -10,68 +12,125 @@ export enum EntryPointType { Factory = 'Factory' } +/** + * Enum representing the payment options for an entry point. + */ export enum EntryPointPayment { Caller = 'Caller', SelfOnly = 'SelfOnly', SelfOnward = 'SelfOnward' } +/** + * Class representing an argument for an entry point. Each argument has a name and a corresponding `CLTypeRaw`. + */ @jsonObject export class EntryPointArg { + /** + * The name of the entry point argument. + */ @jsonMember({ name: 'name', constructor: String }) name: string; + /** + * The type of the argument, represented by `CLTypeRaw`. + */ @jsonMember({ name: 'cl_type', constructor: CLTypeRaw }) clType: CLTypeRaw; + /** + * Constructs an `EntryPointArg` instance. + * @param name The name of the argument. + * @param clType The type of the argument. + */ constructor(name: string, clType: CLTypeRaw) { this.name = name; this.clType = clType; } } -// TODO: Match with Go code when ready +/** + * Class representing access control options for an entry point. + * This class is used for controlling the permissions required to call the entry point. + * + * TODO: Match with Go code when ready + */ @jsonObject export class EntryPointAccess { + /** + * The access control options for this entry point. + */ @jsonMember({ name: 'access_control_options', constructor: AnyT }) accessControlOptions: any; } +/** + * Class representing version 1 of an entry point in the Casper VM. + * It contains the entry point's access, arguments, type, payment type, name, and return type. + */ @jsonObject export class EntryPointV1 { + /** + * The access control for the entry point. + */ @jsonMember({ name: 'access', constructor: EntryPointAccess }) access: EntryPointAccess; + /** + * A list of arguments for the entry point. + */ @jsonArrayMember(EntryPointArg, { name: 'args' }) args: EntryPointArg[]; + /** + * The type of entry point (e.g., session, contract, etc.). + */ @jsonMember({ name: 'entry_point_type', constructor: String }) entryPointType: EntryPointType; + /** + * The payment method required to access this entry point. + */ @jsonMember({ name: 'entry_point_payment', constructor: String }) entryPointPayment: EntryPointPayment; + /** + * The name of the entry point. + */ @jsonMember({ name: 'name', constructor: String }) name: string; + /** + * The return type of the entry point. + */ @jsonMember({ name: 'ret', constructor: CLTypeRaw }) ret: CLTypeRaw; + /** + * Constructs an `EntryPointV1` instance. + * + * @param access The access control for this entry point. + * @param args A list of arguments for the entry point. + * @param entryPointType The type of entry point. + * @param entryPointPayment The payment method for the entry point. + * @param name The name of the entry point. + * @param ret The return type of the entry point. + */ constructor( access: EntryPointAccess, args: EntryPointArg[], @@ -89,34 +148,65 @@ export class EntryPointV1 { } } +/** + * Class representing version 2 of an entry point in the Casper VM. + * This version includes flags and a function index. + */ @jsonObject export class EntryPointV2 { + /** + * Flags associated with this entry point. + */ @jsonMember({ name: 'flags', constructor: Number }) flags: number; + /** + * The function index for the entry point. + */ @jsonMember({ name: 'functionIndex', constructor: Number }) functionIndex: number; + /** + * Constructs an `EntryPointV2` instance. + * + * @param flags The flags for the entry point. + * @param functionIndex The function index for the entry point. + */ constructor(flags = 0, functionIndex = 0) { this.flags = flags; this.functionIndex = functionIndex; } } +/** + * A wrapper class that can hold either version 1 or version 2 of an entry point. + */ @jsonObject export class EntryPointValue { + /** + * Version 1 of the entry point, if available. + */ @jsonMember({ name: 'V1CasperVm', constructor: EntryPointV1 }) v1CasperVm?: EntryPointV1; + /** + * Version 2 of the entry point, if available. + */ @jsonMember({ name: 'V2CasperVm', constructor: EntryPointV2 }) v2CasperVm?: EntryPointV2; + /** + * Constructs an `EntryPointValue` instance. + * + * @param v1CasperVm Version 1 of the entry point, if available. + * @param v2CasperVm Version 2 of the entry point, if available. + */ constructor(v1CasperVm?: EntryPointV1, v2CasperVm?: EntryPointV2) { this.v1CasperVm = v1CasperVm; this.v2CasperVm = v2CasperVm; diff --git a/src/types/EraEnd.ts b/src/types/EraEnd.ts index 51b920fbf..adeb74c5c 100644 --- a/src/types/EraEnd.ts +++ b/src/types/EraEnd.ts @@ -12,8 +12,14 @@ import { serializeRewards } from './clvalue'; +/** + * Class representing the rewards associated with a validator in a given era. + */ @jsonObject export class EraReward { + /** + * The public key of the validator receiving the reward. + */ @jsonMember({ name: 'validator', constructor: PublicKey, @@ -22,6 +28,9 @@ export class EraReward { }) public validator: PublicKey; + /** + * The amount of reward given to the validator. + */ @jsonMember({ name: 'amount', constructor: CLValueUInt512, @@ -30,14 +39,26 @@ export class EraReward { }) public amount: CLValueUInt512; + /** + * Constructs an `EraReward` instance. + * + * @param validator The public key of the validator. + * @param amount The reward amount. + */ constructor(validator: PublicKey, amount: CLValueUInt512) { this.validator = validator; this.amount = amount; } } +/** + * Class representing the era report containing information about equivocators, inactive validators, and rewards. + */ @jsonObject export class EraReport { + /** + * List of validators that have been found to equivocate during the era. + */ @jsonArrayMember(PublicKey, { name: 'equivocators', serializer: (value: PublicKey[]) => value.map(it => it.toJSON()), @@ -46,6 +67,9 @@ export class EraReport { }) public equivocators: PublicKey[]; + /** + * List of inactive validators during the era. + */ @jsonArrayMember(PublicKey, { name: 'inactive_validators', serializer: (value: PublicKey[]) => value.map(it => it.toJSON()), @@ -54,9 +78,19 @@ export class EraReport { }) public inactiveValidators: PublicKey[]; + /** + * List of rewards distributed to validators during the era. + */ @jsonArrayMember(EraReward, { name: 'rewards' }) public rewards: EraReward[]; + /** + * Constructs an `EraReport` instance. + * + * @param equivocators The list of equivocators. + * @param inactiveValidators The list of inactive validators. + * @param rewards The list of rewards distributed to validators. + */ constructor( equivocators: PublicKey[] = [], inactiveValidators: PublicKey[] = [], @@ -68,8 +102,14 @@ export class EraReport { } } +/** + * Class representing the details of an era's end, version 2. It includes information like equivocations, inactive validators, and rewards. + */ @jsonObject export class EraEndV2 { + /** + * List of validators that have been found to equivocate during the era. + */ @jsonArrayMember(PublicKey, { name: 'equivocators', serializer: (value: PublicKey[]) => value.map(it => it.toJSON()), @@ -78,6 +118,9 @@ export class EraEndV2 { }) public equivocators: PublicKey[]; + /** + * List of inactive validators during the era. + */ @jsonArrayMember(PublicKey, { name: 'inactive_validators', serializer: (value: PublicKey[]) => value.map(it => it.toJSON()), @@ -86,11 +129,17 @@ export class EraEndV2 { }) public inactiveValidators: PublicKey[]; + /** + * List of validator weights for the next era. + */ @jsonArrayMember(ValidatorWeightEraEnd, { name: 'next_era_validator_weights' }) public nextEraValidatorWeights: ValidatorWeightEraEnd[]; + /** + * A map of rewards for each validator, identified by their public key, in the next era. + */ @jsonMapMember(String, Array, { name: 'rewards', serializer: serializeRewards, @@ -98,9 +147,21 @@ export class EraEndV2 { }) public rewards: Map; + /** + * The gas price for the next era. + */ @jsonMember({ name: 'next_era_gas_price', constructor: Number }) public nextEraGasPrice: number; + /** + * Constructs an `EraEndV2` instance. + * + * @param equivocators The list of equivocators. + * @param inactiveValidators The list of inactive validators. + * @param nextEraValidatorWeights The validator weights for the next era. + * @param rewards The map of rewards for each validator in the next era. + * @param nextEraGasPrice The gas price for the next era. + */ constructor( equivocators: PublicKey[], inactiveValidators: PublicKey[], @@ -116,16 +177,31 @@ export class EraEndV2 { } } +/** + * Class representing the details of an era's end, version 1. + */ @jsonObject export class EraEndV1 { + /** + * The era report containing equivocators, inactive validators, and rewards. + */ @jsonMember({ name: 'era_report', constructor: EraReport }) public eraReport: EraReport; + /** + * The list of validator weights for the next era. + */ @jsonArrayMember(ValidatorWeightEraEnd, { name: 'next_era_validator_weights' }) public nextEraValidatorWeights: ValidatorWeightEraEnd[]; + /** + * Constructs an `EraEndV1` instance. + * + * @param eraReport The era report. + * @param nextEraValidatorWeights The validator weights for the next era. + */ constructor( eraReport: EraReport, nextEraValidatorWeights: ValidatorWeightEraEnd[] @@ -135,8 +211,14 @@ export class EraEndV1 { } } +/** + * A class that represents the end of an era with a unified structure. + */ @jsonObject export class EraEnd { + /** + * List of validators that have been found to equivocate during the era. + */ @jsonArrayMember(PublicKey, { name: 'equivocators', serializer: (value: PublicKey[]) => value.map(it => it.toJSON()), @@ -145,6 +227,9 @@ export class EraEnd { }) public equivocators: PublicKey[]; + /** + * List of inactive validators during the era. + */ @jsonArrayMember(PublicKey, { name: 'inactive_validators', serializer: (value: PublicKey[]) => value.map(it => it.toJSON()), @@ -153,11 +238,17 @@ export class EraEnd { }) public inactiveValidators: PublicKey[]; + /** + * List of validator weights for the next era. + */ @jsonArrayMember(ValidatorWeightEraEnd, { name: 'next_era_validator_weights' }) public nextEraValidatorWeights: ValidatorWeightEraEnd[]; + /** + * A map of rewards for each validator, identified by their public key. + */ @jsonMapMember(String, CLValueUInt512, { name: 'rewards', deserializer: deserializeRewards, @@ -165,9 +256,21 @@ export class EraEnd { }) public rewards: Map; + /** + * The gas price for the next era. + */ @jsonMember({ name: 'next_era_gas_price', constructor: Number }) public nextEraGasPrice: number; + /** + * Constructs an `EraEnd` instance. + * + * @param equivocators The list of equivocators. + * @param inactiveValidators The list of inactive validators. + * @param nextEraValidatorWeights The validator weights for the next era. + * @param rewards The map of rewards for each validator. + * @param nextEraGasPrice The gas price for the next era. + */ constructor( equivocators: PublicKey[] = [], inactiveValidators: PublicKey[] = [], @@ -182,6 +285,12 @@ export class EraEnd { this.nextEraGasPrice = nextEraGasPrice; } + /** + * Converts an `EraEndV2` instance to `EraEnd`. + * + * @param eraEnd The `EraEndV2` instance. + * @returns A new `EraEnd` instance, or `null` if the `EraEndV2` is `null`. + */ static fromV2(eraEnd: EraEndV2 | null): EraEnd | null { if (!eraEnd) return null; const result = new EraEnd(); @@ -193,6 +302,12 @@ export class EraEnd { return result; } + /** + * Converts an `EraEndV1` instance to `EraEnd`. + * + * @param eraEnd The `EraEndV1` instance. + * @returns A new `EraEnd` instance, or `null` if the `EraEndV1` is `null`. + */ static fromV1(eraEnd: EraEndV1 | null): EraEnd | null { if (!eraEnd) return null; diff --git a/src/types/EraInfo.ts b/src/types/EraInfo.ts index df3c89da2..2ebc94475 100644 --- a/src/types/EraInfo.ts +++ b/src/types/EraInfo.ts @@ -2,8 +2,14 @@ import { jsonArrayMember, jsonMember, jsonObject } from 'typedjson'; import { PublicKey } from './keypair'; import { CLValueUInt512 } from './clvalue'; +/** + * Class representing the allocation of seigniorage to a delegator. + */ @jsonObject export class DelegatorAllocation { + /** + * The public key of the delegator receiving the allocation. + */ @jsonMember({ name: 'delegator_public_key', constructor: PublicKey, @@ -12,6 +18,9 @@ export class DelegatorAllocation { }) delegatorPublicKey: PublicKey; + /** + * The public key of the validator associated with the delegator's allocation. + */ @jsonMember({ name: 'validator_public_key', constructor: PublicKey, @@ -20,6 +29,9 @@ export class DelegatorAllocation { }) validatorPublicKey: PublicKey; + /** + * The amount of seigniorage allocated to the delegator. + */ @jsonMember({ name: 'amount', constructor: CLValueUInt512, @@ -28,6 +40,13 @@ export class DelegatorAllocation { }) amount: CLValueUInt512; + /** + * Constructs a `DelegatorAllocation` instance. + * + * @param delegatorPublicKey The public key of the delegator. + * @param validatorPublicKey The public key of the associated validator. + * @param amount The amount of seigniorage allocated to the delegator. + */ constructor( delegatorPublicKey: PublicKey, validatorPublicKey: PublicKey, @@ -39,8 +58,14 @@ export class DelegatorAllocation { } } +/** + * Class representing the allocation of seigniorage to a validator. + */ @jsonObject export class ValidatorAllocation { + /** + * The public key of the validator receiving the allocation. + */ @jsonMember({ name: 'validator_public_key', constructor: PublicKey, @@ -49,6 +74,9 @@ export class ValidatorAllocation { }) validatorPublicKey: PublicKey; + /** + * The amount of seigniorage allocated to the validator. + */ @jsonMember({ name: 'amount', constructor: CLValueUInt512, @@ -57,20 +85,41 @@ export class ValidatorAllocation { }) amount: CLValueUInt512; + /** + * Constructs a `ValidatorAllocation` instance. + * + * @param validatorPublicKey The public key of the validator. + * @param amount The amount of seigniorage allocated to the validator. + */ constructor(validatorPublicKey: PublicKey, amount: CLValueUInt512) { this.validatorPublicKey = validatorPublicKey; this.amount = amount; } } +/** + * Class representing the seigniorage allocation for a validator and delegator. + */ @jsonObject export class SeigniorageAllocation { + /** + * The allocation for a validator. + */ @jsonMember({ name: 'Validator', constructor: ValidatorAllocation }) validator?: ValidatorAllocation; + /** + * The allocation for a delegator. + */ @jsonMember({ name: 'Delegator', constructor: DelegatorAllocation }) delegator?: DelegatorAllocation; + /** + * Constructs a `SeigniorageAllocation` instance. + * + * @param validator The validator allocation. + * @param delegator The delegator allocation. + */ constructor( validator?: ValidatorAllocation, delegator?: DelegatorAllocation @@ -80,11 +129,22 @@ export class SeigniorageAllocation { } } +/** + * Class representing information about an era, including seigniorage allocations. + */ @jsonObject export class EraInfo { + /** + * A list of seigniorage allocations for validators and delegators in the era. + */ @jsonArrayMember(SeigniorageAllocation, { name: 'seigniorage_allocations' }) seigniorageAllocations: SeigniorageAllocation[]; + /** + * Constructs an `EraInfo` instance. + * + * @param seigniorageAllocations The list of seigniorage allocations for validators and delegators. + */ constructor(seigniorageAllocations: SeigniorageAllocation[] = []) { this.seigniorageAllocations = seigniorageAllocations; } diff --git a/src/types/EraSummary.ts b/src/types/EraSummary.ts index cf4da4000..16ee1d3eb 100644 --- a/src/types/EraSummary.ts +++ b/src/types/EraSummary.ts @@ -2,8 +2,15 @@ import { jsonObject, jsonMember } from 'typedjson'; import { Hash } from './key'; import { StoredValue } from './StoredValue'; +/** + * Class representing a summary of an era, including the block hash, era ID, + * stored value, state root hash, and the associated Merkle proof. + */ @jsonObject export class EraSummary { + /** + * The hash of the block for this era. + */ @jsonMember({ name: 'block_hash', constructor: Hash, @@ -12,12 +19,21 @@ export class EraSummary { }) public blockHash: Hash; + /** + * The unique identifier for the era. + */ @jsonMember({ name: 'era_id', constructor: Number }) public eraID: number; + /** + * The stored value for this era, representing data related to the state at the end of the era. + */ @jsonMember({ name: 'stored_value', constructor: StoredValue }) public storedValue: StoredValue; + /** + * The hash of the state root, which represents the state at the end of the era. + */ @jsonMember({ name: 'state_root_hash', constructor: Hash, @@ -26,9 +42,22 @@ export class EraSummary { }) public stateRootHash: Hash; + /** + * The Merkle proof associated with the block in this era, used to verify the integrity + * of the data stored in the block. + */ @jsonMember({ name: 'merkle_proof', constructor: String }) public merkleProof: string; + /** + * Constructs an `EraSummary` instance. + * + * @param blockHash The hash of the block for this era. + * @param eraID The unique identifier for the era. + * @param storedValue The stored value representing data associated with the era. + * @param stateRootHash The hash of the state root at the end of the era. + * @param merkleProof The Merkle proof for the block in the era. + */ constructor( blockHash: Hash, eraID: number, diff --git a/src/types/ExecutableDeployItem.ts b/src/types/ExecutableDeployItem.ts index 85a945f02..bd1730d44 100644 --- a/src/types/ExecutableDeployItem.ts +++ b/src/types/ExecutableDeployItem.ts @@ -16,6 +16,9 @@ import { ContractHash, URef } from './key'; import { deserializeArgs, serializeArgs } from './SerializationUtils'; import { PublicKey } from './keypair'; +/** + * Enum representing the different types of executable deploy items. + */ enum ExecutableDeployItemType { ModuleBytes, StoredContractByHash, @@ -25,11 +28,20 @@ enum ExecutableDeployItemType { Transfer } +/** + * Represents a deploy item containing module bytes and associated arguments. + */ @jsonObject export class ModuleBytes { + /** + * The module bytes in hexadecimal format. + */ @jsonMember({ name: 'module_bytes', constructor: String }) moduleBytes: string; + /** + * The arguments passed to the module. + */ @jsonMember({ constructor: Args, name: 'args', @@ -38,11 +50,20 @@ export class ModuleBytes { }) args: Args; + /** + * Constructs a `ModuleBytes` instance with module bytes and arguments. + * @param moduleBytes The module bytes in hexadecimal format. + * @param args The arguments for the module. + */ constructor(moduleBytes: string, args: Args) { this.moduleBytes = moduleBytes; this.args = args; } + /** + * Serializes the `ModuleBytes` instance to a byte array. + * @returns The serialized byte array. + */ bytes(): Uint8Array { const moduleBytes = new Uint8Array(Buffer.from(this.moduleBytes, 'hex')); const lengthBytes = CLValueUInt32.newCLUInt32( @@ -63,8 +84,14 @@ export class ModuleBytes { } } +/** + * Represents a deploy item with a stored contract referenced by its hash. + */ @jsonObject export class StoredContractByHash { + /** + * The hash of the stored contract. + */ @jsonMember({ name: 'hash', constructor: ContractHash, @@ -72,7 +99,16 @@ export class StoredContractByHash { serializer: value => value.toJSON() }) hash: ContractHash; - @jsonMember({ name: 'entry_point', constructor: String }) entryPoint: string; + + /** + * The entry point of the contract to invoke. + */ + @jsonMember({ name: 'entry_point', constructor: String }) + entryPoint: string; + + /** + * The arguments for the contract call. + */ @jsonMember({ constructor: Args, name: 'args', @@ -81,12 +117,22 @@ export class StoredContractByHash { }) args: Args; + /** + * Constructs a `StoredContractByHash` instance with the contract hash, entry point, and arguments. + * @param hash The contract hash. + * @param entryPoint The contract entry point. + * @param args The arguments for the contract. + */ constructor(hash: ContractHash, entryPoint: string, args: Args) { this.hash = hash; this.entryPoint = entryPoint; this.args = args; } + /** + * Serializes the `StoredContractByHash` instance to a byte array. + * @returns The serialized byte array. + */ bytes(): Uint8Array { const hashBytes = this.hash.hash.toBytes(); const entryPointBytes = CLValueString.newCLString(this.entryPoint).bytes(); @@ -96,10 +142,26 @@ export class StoredContractByHash { } } +/** + * Represents a deploy item with a stored contract referenced by its name. + */ @jsonObject export class StoredContractByName { - @jsonMember({ name: 'name', constructor: String }) name: string; - @jsonMember({ name: 'entry_point', constructor: String }) entryPoint: string; + /** + * The name of the stored contract. + */ + @jsonMember({ name: 'name', constructor: String }) + name: string; + + /** + * The entry point of the contract to invoke. + */ + @jsonMember({ name: 'entry_point', constructor: String }) + entryPoint: string; + + /** + * The arguments for the contract call. + */ @jsonMember({ constructor: Args, name: 'args', @@ -108,12 +170,22 @@ export class StoredContractByName { }) args: Args; + /** + * Constructs a `StoredContractByName` instance with the contract name, entry point, and arguments. + * @param name The contract name. + * @param entryPoint The contract entry point. + * @param args The arguments for the contract. + */ constructor(name: string, entryPoint: string, args: Args) { this.name = name; this.entryPoint = entryPoint; this.args = args; } + /** + * Serializes the `StoredContractByName` instance to a byte array. + * @returns The serialized byte array. + */ bytes(): Uint8Array { const nameBytes = CLValueString.newCLString(this.name).bytes(); const entryPointBytes = CLValueString.newCLString(this.entryPoint).bytes(); @@ -123,8 +195,14 @@ export class StoredContractByName { } } +/** + * Represents a deploy item with a stored versioned contract referenced by its hash. + */ @jsonObject export class StoredVersionedContractByHash { + /** + * The hash of the stored contract. + */ @jsonMember({ name: 'hash', constructor: ContractHash, @@ -132,7 +210,16 @@ export class StoredVersionedContractByHash { serializer: value => value.toJSON() }) hash: ContractHash; - @jsonMember({ name: 'entry_point', constructor: String }) entryPoint: string; + + /** + * The entry point of the contract to invoke. + */ + @jsonMember({ name: 'entry_point', constructor: String }) + entryPoint: string; + + /** + * The arguments for the contract call. + */ @jsonMember({ constructor: Args, name: 'args', @@ -140,8 +227,20 @@ export class StoredVersionedContractByHash { serializer: serializeArgs }) args: Args; - @jsonMember({ name: 'version', constructor: Number }) version?: number; + /** + * The version of the contract. + */ + @jsonMember({ name: 'version', constructor: Number }) + version?: number; + + /** + * Constructs a `StoredVersionedContractByHash` instance with the contract hash, entry point, arguments, and version. + * @param hash The contract hash. + * @param entryPoint The contract entry point. + * @param args The arguments for the contract. + * @param version The contract version. + */ constructor( hash: ContractHash, entryPoint: string, @@ -154,6 +253,10 @@ export class StoredVersionedContractByHash { this.args = args; } + /** + * Serializes the `StoredVersionedContractByHash` instance to a byte array. + * @returns The serialized byte array. + */ bytes(): Uint8Array { const hashBytes = this.hash.hash.toBytes(); const optionBytes = new CLValueOption( @@ -168,11 +271,32 @@ export class StoredVersionedContractByHash { } } +/** + * Represents a deploy item with a stored versioned contract referenced by its name. + */ @jsonObject export class StoredVersionedContractByName { - @jsonMember({ name: 'name', constructor: String }) name: string; - @jsonMember({ name: 'entry_point', constructor: String }) entryPoint: string; - @jsonMember({ name: 'version', constructor: Number }) version?: number; + /** + * The name of the stored contract. + */ + @jsonMember({ name: 'name', constructor: String }) + name: string; + + /** + * The entry point of the contract to invoke. + */ + @jsonMember({ name: 'entry_point', constructor: String }) + entryPoint: string; + + /** + * The version of the contract. + */ + @jsonMember({ name: 'version', constructor: Number }) + version?: number; + + /** + * The arguments for the contract call. + */ @jsonMember({ constructor: Args, name: 'args', @@ -181,6 +305,13 @@ export class StoredVersionedContractByName { }) args: Args; + /** + * Constructs a `StoredVersionedContractByName` instance with the contract name, entry point, arguments, and version. + * @param name The contract name. + * @param entryPoint The contract entry point. + * @param args The arguments for the contract. + * @param version The contract version. + */ constructor(name: string, entryPoint: string, args: Args, version?: number) { this.name = name; this.entryPoint = entryPoint; @@ -188,6 +319,10 @@ export class StoredVersionedContractByName { this.args = args; } + /** + * Serializes the `StoredVersionedContractByName` instance to a byte array. + * @returns The serialized byte array. + */ bytes(): Uint8Array { const nameBytes = CLValueString.newCLString(this.name).bytes(); const optionBytes = new CLValueOption( @@ -202,8 +337,14 @@ export class StoredVersionedContractByName { } } +/** + * Represents a deploy item with a transfer of funds and associated arguments. + */ @jsonObject export class TransferDeployItem { + /** + * The arguments for the transfer. + */ @jsonMember({ constructor: Args, name: 'args', @@ -212,10 +353,23 @@ export class TransferDeployItem { }) args: Args; + /** + * Constructs a `TransferDeployItem` instance with arguments. + * @param args The arguments for the transfer. + */ constructor(args: Args) { this.args = args; } + /** + * Creates a new transfer deploy item with the specified amount, target, source purse, and transfer ID. + * @param amount The amount to transfer. + * @param target The target address (either a URef or a PublicKey). + * @param sourcePurse The source purse (optional). + * @param id The transfer ID. + * @returns A new `TransferDeployItem` instance. + * @throws Error if the target is not specified or the transfer ID is missing. + */ public static newTransfer( amount: BigNumber | string, target: URef | PublicKey, @@ -245,48 +399,92 @@ export class TransferDeployItem { return new TransferDeployItem(runtimeArgs); } + /** + * Serializes the `TransferDeployItem` instance to a byte array. + * @returns The serialized byte array. + */ bytes(): Uint8Array { return this.args.toBytes(); } } +/** + * Represents an executable deploy item, which can be one of several types such as `ModuleBytes`, `StoredContractByHash`, etc. + */ @jsonObject export class ExecutableDeployItem { + /** + * A module bytes deploy item. + */ @jsonMember({ name: 'ModuleBytes', constructor: ModuleBytes }) moduleBytes?: ModuleBytes; + + /** + * A stored contract deploy item referenced by hash. + */ @jsonMember({ name: 'StoredContractByHash', constructor: StoredContractByHash }) storedContractByHash?: StoredContractByHash; + + /** + * A stored contract deploy item referenced by name. + */ @jsonMember({ name: 'StoredContractByName', constructor: StoredContractByName }) storedContractByName?: StoredContractByName; + + /** + * A stored versioned contract deploy item referenced by hash. + */ @jsonMember({ name: 'StoredVersionedContractByHash', constructor: StoredVersionedContractByHash }) storedVersionedContractByHash?: StoredVersionedContractByHash; + + /** + * A stored versioned contract deploy item referenced by name. + */ @jsonMember({ name: 'StoredVersionedContractByName', constructor: StoredVersionedContractByName }) storedVersionedContractByName?: StoredVersionedContractByName; + + /** + * A transfer deploy item. + */ @jsonMember({ name: 'Transfer', constructor: TransferDeployItem }) transfer?: TransferDeployItem; + /** + * Retrieves an argument by name from the deploy item. + * @param name The name of the argument. + * @returns The argument value, or `undefined` if not found. + */ public getArgByName(name: string): CLValue | undefined { const deployItemArgs = this.getArgs(); return deployItemArgs.args.get(name); } + /** + * Sets an argument by name for the deploy item. + * @param name The name of the argument. + * @param value The value of the argument. + */ public setArg(name: string, value: CLValue) { const deployItemArgs = this.getArgs(); deployItemArgs.insert(name, value); } + /** + * Retrieves the arguments for the deploy item. + * @returns The arguments for the deploy item. + */ getArgs(): Args { if (this.moduleBytes) return this.moduleBytes.args; if (this.storedContractByHash) return this.storedContractByHash.args; @@ -299,6 +497,10 @@ export class ExecutableDeployItem { throw new Error('failed to serialize ExecutableDeployItemJsonWrapper'); } + /** + * Serializes the `ExecutableDeployItem` to a byte array. + * @returns The serialized byte array. + */ bytes(): Uint8Array { let bytes: Uint8Array; @@ -340,6 +542,11 @@ export class ExecutableDeployItem { return new Uint8Array(); } + /** + * Creates a standard payment `ExecutableDeployItem` with the specified amount. + * @param amount The amount to be transferred. + * @returns A new `ExecutableDeployItem` instance with the payment. + */ public static standardPayment( amount: BigNumber | string ): ExecutableDeployItem { @@ -352,56 +559,56 @@ export class ExecutableDeployItem { } /** - * Casts the `ExecutableDeployItem` to `ModuleBytes` if possible - * @returns `ModuleBytes` representation of `ExecutableDeployItem`, or `undefined` if the `ExecutableDeployItem` cannot be cast + * Casts the `ExecutableDeployItem` to `ModuleBytes` if possible. + * @returns The `ModuleBytes` representation of the `ExecutableDeployItem`, or `undefined` if not possible. */ public asModuleBytes(): ModuleBytes | undefined { return this.moduleBytes; } /** - * Identifies whether the `ExecutableDeployItem` is of the original type `Transfer` - * @returns `true` is the `ExecutableDeployItem` conforms to `Transfer`, and `false` otherwise. + * Checks if the `ExecutableDeployItem` is of type `Transfer`. + * @returns `true` if the `ExecutableDeployItem` is a transfer item, `false` otherwise. */ public isTransfer() { return !!this.transfer; } /** - * Identifies whether the `ExecutableDeployItem` is of the original type `StoredVersionedContractByHash` - * @returns `true` is the `ExecutableDeployItem` conforms to `StoredVersionedContractByHash`, and `false` otherwise. + * Checks if the `ExecutableDeployItem` is of type `StoredVersionedContractByHash`. + * @returns `true` if the `ExecutableDeployItem` is a stored versioned contract by hash, `false` otherwise. */ public isStoredVersionContractByHash(): boolean { return !!this.storedVersionedContractByHash; } /** - * Identifies whether the `ExecutableDeployItem` is of the original type `StoredVersionedContractByName` - * @returns `true` is the `ExecutableDeployItem` conforms to `StoredVersionedContractByName`, and `false` otherwise. + * Checks if the `ExecutableDeployItem` is of type `StoredVersionedContractByName`. + * @returns `true` if the `ExecutableDeployItem` is a stored versioned contract by name, `false` otherwise. */ public isStoredVersionContractByName(): boolean { return !!this.storedVersionedContractByName; } /** - * Identifies whether the `ExecutableDeployItem` is of the original type `StoredContractByName` - * @returns `true` is the `ExecutableDeployItem` conforms to `StoredContractByName`, and `false` otherwise. + * Checks if the `ExecutableDeployItem` is of type `StoredContractByName`. + * @returns `true` if the `ExecutableDeployItem` is a stored contract by name, `false` otherwise. */ public isStoredContractByName(): boolean { return !!this.storedContractByName; } /** - * Identifies whether the `ExecutableDeployItem` is of the original type `StoredContractByHash` - * @returns `true` is the `ExecutableDeployItem` conforms to `StoredContractByHash`, and `false` otherwise. + * Checks if the `ExecutableDeployItem` is of type `StoredContractByHash`. + * @returns `true` if the `ExecutableDeployItem` is a stored contract by hash, `false` otherwise. */ public isStoredContractByHash(): boolean { return !!this.storedContractByHash; } /** - * Identifies whether the `ExecutableDeployItem` is of the original type `ModuleBytes` - * @returns `true` is the `ExecutableDeployItem` conforms to `ModuleBytes`, and `false` otherwise. + * Checks if the `ExecutableDeployItem` is of type `ModuleBytes`. + * @returns `true` if the `ExecutableDeployItem` is of type `ModuleBytes`, `false` otherwise. */ public isModuleBytes(): boolean { return !!this.moduleBytes; diff --git a/src/types/ExecutionResult.ts b/src/types/ExecutionResult.ts index 8507859ce..358172f18 100644 --- a/src/types/ExecutionResult.ts +++ b/src/types/ExecutionResult.ts @@ -11,8 +11,14 @@ import { Transfer } from './Transfer'; import { Transform, TransformKey } from './Transform'; import { TransactionHash } from './Transaction'; +/** + * Represents an operation performed during a transaction. + */ @jsonObject export class Operation { + /** + * The key associated with the operation. + */ @jsonMember({ name: 'key', constructor: Key, @@ -21,27 +27,51 @@ export class Operation { }) public key: Key; + /** + * The type of the operation (e.g., "Write", "Transfer"). + */ @jsonMember({ name: 'kind', constructor: String }) public kind: string; } +/** + * A collection of transformations applied during a transaction. + */ @jsonObject export class Effects extends Array {} +/** + * Represents the effect of a transaction, including the operations and transformations. + */ @jsonObject export class Effect { + /** + * The operations performed as part of this effect. + */ @jsonArrayMember(Operation, { name: 'operations' }) public operations: Operation[] = []; + /** + * The transformations applied as part of this effect. + */ @jsonArrayMember(TransformKey, { name: 'transforms' }) public transforms: TransformKey[] = []; } +/** + * Contains the result of a transaction's execution, including the effect and related transfers. + */ @jsonObject export class ExecutionResultStatusData { + /** + * The effect of the transaction execution, including operations and transformations. + */ @jsonMember({ name: 'effect', constructor: Effect }) public effect: Effect; + /** + * The transfers that were part of the transaction execution. + */ @jsonArrayMember(TransferHash, { name: 'transfers', serializer: (value: TransferHash[]) => value.map(it => it.toJSON()), @@ -50,15 +80,27 @@ export class ExecutionResultStatusData { }) public transfers: TransferHash[] = []; + /** + * The cost of the transaction execution. + */ @jsonMember({ name: 'cost', constructor: Number }) public cost: number; + /** + * The error message, if any, generated during the transaction execution. + */ @jsonMember({ name: 'error_message', constructor: String }) public errorMessage: string; } +/** + * Represents version 2 of the execution result, containing more detailed information. + */ @jsonObject export class ExecutionResultV2 { + /** + * The address of the initiator of the execution. + */ @jsonMember({ name: 'initiator', constructor: InitiatorAddr, @@ -67,45 +109,84 @@ export class ExecutionResultV2 { }) public initiator: InitiatorAddr; + /** + * The error message, if any, generated during the execution. + */ @jsonMember({ name: 'error_message', constructor: String }) public errorMessage?: string; + /** + * The execution limit for the transaction. + */ @jsonMember({ name: 'limit', constructor: Number }) public limit: number; + /** + * The amount of resources consumed during the transaction execution. + */ @jsonMember({ name: 'consumed', constructor: Number }) public consumed: number; + /** + * The cost associated with the transaction execution. + */ @jsonMember({ name: 'cost', constructor: Number }) public cost: number; + /** + * The payment made for the transaction, if any. + */ @jsonMember({ name: 'payment', constructor: AnyT }) public payment?: any; + /** + * The transfers included in the transaction execution. + */ @jsonArrayMember(Transfer, { name: 'transfers', deserializer: (json: any) => json.map((it: string) => Transfer.fromJSON(it)) }) public transfers: Transfer[] = []; + /** + * The estimated size of the transaction execution. + */ @jsonMember({ name: 'size_estimate', constructor: Number }) public sizeEstimate: number; + /** + * The effects applied during the transaction execution. + */ @jsonArrayMember(Transform, { name: 'effects' }) public effects: Transform[] = []; } +/** + * Represents version 1 of the execution result, containing basic information on success or failure. + */ @jsonObject export class ExecutionResultV1 { + /** + * The status data for a successful execution. + */ @jsonMember({ name: 'Success', constructor: ExecutionResultStatusData }) public success?: ExecutionResultStatusData; + /** + * The status data for a failed execution. + */ @jsonMember({ name: 'Failure', constructor: ExecutionResultStatusData }) public failure?: ExecutionResultStatusData; } +/** + * Contains the block hash and execution result of a deploy execution. + */ @jsonObject export class DeployExecutionResult { + /** + * The block hash where the deploy was executed. + */ @jsonMember({ name: 'block_hash', constructor: Hash, @@ -114,12 +195,21 @@ export class DeployExecutionResult { }) public blockHash: Hash; + /** + * The execution result for the deploy. + */ @jsonMember({ name: 'result', constructor: ExecutionResultV1 }) public result: ExecutionResultV1; } +/** + * Represents the result of a transaction execution, which includes the initiator, cost, transfers, and effects. + */ @jsonObject export class ExecutionResult { + /** + * The address of the initiator of the execution. + */ @jsonMember({ constructor: InitiatorAddr, deserializer: json => InitiatorAddr.fromJSON(json), @@ -127,35 +217,74 @@ export class ExecutionResult { }) public initiator: InitiatorAddr; + /** + * The error message, if any, generated during the execution. + */ @jsonMember({ name: 'error_message', constructor: String }) public errorMessage?: string; + /** + * The execution limit for the transaction. + */ @jsonMember({ constructor: Number }) public limit: number; + /** + * The amount of resources consumed during the transaction execution. + */ @jsonMember({ constructor: Number }) public consumed: number; + /** + * The cost associated with the transaction execution. + */ @jsonMember({ constructor: Number }) public cost: number; + /** + * The payment made for the transaction, if any. + */ @jsonMember({ constructor: AnyT }) public payment?: any; + /** + * The transfers included in the transaction execution. + */ @jsonArrayMember(Transfer, { deserializer: (json: any) => json.map((it: string) => Transfer.fromJSON(it)) }) public transfers: Transfer[] = []; + /** + * The estimated size of the transaction execution. + */ @jsonMember({ constructor: Number }) public sizeEstimate: number; + /** + * The effects applied during the transaction execution. + */ @jsonArrayMember(Transform) public effects: Transform[] = []; + /** + * The original execution result in version 1 format, if applicable. + */ public originExecutionResultV1?: ExecutionResultV1; + + /** + * The original execution result in version 2 format, if applicable. + */ public originExecutionResultV2?: ExecutionResultV2; + /** + * Deserializes an `ExecutionResult` from JSON data. + * Supports both version 1 and version 2 formats. + * + * @param data The JSON data representing the execution result. + * @returns The deserialized `ExecutionResult`. + * @throws Error if the data format is invalid or unknown. + */ public static fromJSON(data: any): ExecutionResult { const rawObject = JSON.parse(data); @@ -191,6 +320,12 @@ export class ExecutionResult { throw new Error('Incorrect RPC response structure'); } + /** + * Creates an `ExecutionResult` from version 1 of the execution result. + * + * @param v1 The version 1 execution result. + * @returns The `ExecutionResult` created from version 1 data. + */ public static fromV1(v1: ExecutionResultV1): ExecutionResult { const result = new ExecutionResult(); const transforms: Transform[] = []; @@ -255,8 +390,14 @@ export class ExecutionResult { } } +/** + * Represents execution information about a deploy, including the block hash, height, and execution result. + */ @jsonObject export class ExecutionInfo { + /** + * The block hash where the deploy was executed. + */ @jsonMember({ name: 'block_hash', constructor: Hash, @@ -265,12 +406,26 @@ export class ExecutionInfo { }) public blockHash: Hash; + /** + * The block height at the time the deploy was executed. + */ @jsonMember({ name: 'block_height', constructor: Number }) public blockHeight: number; + /** + * The execution result associated with the deploy. + */ @jsonMember({ name: 'execution_result', constructor: ExecutionResult }) public executionResult: ExecutionResult; + /** + * Creates an `ExecutionInfo` instance from version 1 data. + * + * @param results The results of the deploy execution. + * @param height The block height, if available. + * @returns The `ExecutionInfo` instance created from version 1 data. + * @throws Error if the results are empty or missing. + */ constructor( blockHash: Hash, blockHeight: number, @@ -300,8 +455,14 @@ export class ExecutionInfo { } } +/** + * Represents execution information for a deploy, including the block hash, height, and execution result. + */ @jsonObject export class DeployExecutionInfo { + /** + * The block hash where the deploy was executed. + */ @jsonMember({ name: 'block_hash', constructor: Hash, @@ -310,12 +471,25 @@ export class DeployExecutionInfo { }) public blockHash: Hash; + /** + * The block height at the time the deploy was executed. + */ @jsonMember({ name: 'block_height', constructor: Number }) public blockHeight: number; + /** + * The execution result associated with the deploy. + */ @jsonMember({ name: 'execution_result', constructor: ExecutionResult }) public executionResult: ExecutionResult; + /** + * Creates a `DeployExecutionInfo` instance from version 1 data. + * + * @param results The results of the deploy execution. + * @param height The block height, if available. + * @returns The `DeployExecutionInfo` instance created from version 1 data. + */ public static fromV1( results: DeployExecutionResult[], height?: number diff --git a/src/types/HexBytes.ts b/src/types/HexBytes.ts index a3711fe1d..0736fda35 100644 --- a/src/types/HexBytes.ts +++ b/src/types/HexBytes.ts @@ -1,24 +1,53 @@ import { jsonObject, jsonMember } from 'typedjson'; +/** + * Represents a collection of bytes stored as a `Uint8Array` with methods + * to convert to/from hexadecimal and JSON. + */ @jsonObject export class HexBytes { + /** + * The raw byte data stored in a `Uint8Array`. + */ @jsonMember(Uint8Array) bytes: Uint8Array; + /** + * Creates a new instance of `HexBytes`. + * + * @param bytes The byte data as a `Uint8Array`. + */ constructor(bytes: Uint8Array) { this.bytes = bytes; } + /** + * Converts the stored bytes into a hexadecimal string. + * + * @returns The hexadecimal string representation of the byte data. + */ toHex(): string { return Array.from(this.bytes) .map(byte => byte.toString(16).padStart(2, '0')) .join(''); } + /** + * Converts the stored bytes to a JSON string representation. + * This method returns the hexadecimal string of the byte data. + * + * @returns The hexadecimal string as a JSON string. + */ toJSON(): string { return this.toHex(); } + /** + * Creates a `HexBytes` instance from a hexadecimal string. + * + * @param hexString The hexadecimal string to convert. + * @returns A new `HexBytes` instance. + */ static fromHex(hexString: string): HexBytes { const bytes = new Uint8Array( hexString.match(/.{1,2}/g)!.map(byte => parseInt(byte, 16)) @@ -26,10 +55,22 @@ export class HexBytes { return new HexBytes(bytes); } + /** + * Creates a `HexBytes` instance from a JSON string. + * The JSON string should be a hexadecimal string. + * + * @param json The JSON string to convert. + * @returns A new `HexBytes` instance. + */ static fromJSON(json: string): HexBytes { return HexBytes.fromHex(json); } + /** + * Returns a string representation of the byte data as hexadecimal. + * + * @returns A string representing the byte data in hexadecimal format. + */ toString(): string { return this.toHex(); } diff --git a/src/types/InitiatorAddr.ts b/src/types/InitiatorAddr.ts index 4ace40cc2..891beebb2 100644 --- a/src/types/InitiatorAddr.ts +++ b/src/types/InitiatorAddr.ts @@ -4,25 +4,46 @@ import { concat } from '@ethersproject/bytes'; import { PublicKey } from './keypair'; import { AccountHash } from './key'; +/** + * Represents an address for an initiator, which can either be a public key or an account hash. + */ @jsonObject export class InitiatorAddr { + /** + * The public key of the initiator, if available. + */ @jsonMember({ name: 'PublicKey', constructor: PublicKey }) public publicKey?: PublicKey; + /** + * The account hash of the initiator, if available. + */ @jsonMember({ name: 'AccountHash', constructor: AccountHash }) public accountHash?: AccountHash; + /** + * Creates an instance of `InitiatorAddr` with an optional public key and account hash. + * + * @param publicKey The public key of the initiator. + * @param accountHash The account hash of the initiator. + */ constructor(publicKey?: PublicKey, accountHash?: AccountHash) { this.publicKey = publicKey; this.accountHash = accountHash; } + /** + * Converts the `InitiatorAddr` instance to a byte array representation. + * The result depends on whether the address is a public key or an account hash. + * + * @returns A `Uint8Array` representing the initiator address. + */ public toBytes(): Uint8Array { let result: Uint8Array; @@ -40,6 +61,13 @@ export class InitiatorAddr { return result; } + /** + * Creates an `InitiatorAddr` instance from a JSON object. + * The JSON object can contain either a `publicKey` or an `accountHash` string. + * + * @param json The JSON object containing the address data. + * @returns A new `InitiatorAddr` instance. + */ static fromJSON(json: any): InitiatorAddr { const initiatorAddr = new InitiatorAddr(); @@ -52,6 +80,12 @@ export class InitiatorAddr { return initiatorAddr; } + /** + * Converts the `InitiatorAddr` instance to a JSON object. + * The JSON object will contain either a `publicKey` or an `accountHash` depending on which is available. + * + * @returns A JSON object representing the initiator address. + */ public toJSON(): unknown { if (this.accountHash) { return { diff --git a/src/types/MessageTopic.ts b/src/types/MessageTopic.ts index 6d496142f..02105ce45 100644 --- a/src/types/MessageTopic.ts +++ b/src/types/MessageTopic.ts @@ -2,22 +2,43 @@ import { jsonObject, jsonMember } from 'typedjson'; import { EntityAddr, Hash } from './key'; import { ModuleBytes } from './ExecutableDeployItem'; +/** + * Represents a summary of a message topic, including the number of messages and block time. + */ @jsonObject export class MessageTopicSummary { + /** + * The total number of messages in this topic. + */ @jsonMember({ name: 'message_count', constructor: Number }) messageCount: number; + /** + * The block time associated with the topic. + */ @jsonMember({ name: 'blocktime', constructor: Number }) blockTime: number; } +/** + * Represents a checksum for a message, stored as a string. + */ export type MessageChecksum = string; +/** + * Represents a message topic, including the topic name and its hash. + */ @jsonObject export class MessageTopic { + /** + * The name of the message topic. + */ @jsonMember({ name: 'topic_name', constructor: String }) topicName: string; + /** + * The hash of the message topic name. + */ @jsonMember({ name: 'topic_name_hash', constructor: Hash, @@ -27,11 +48,20 @@ export class MessageTopic { topicNameHash: Hash; } +/** + * Represents the payload of a message, which can either be a string or bytes. + */ @jsonObject export class MessagePayload { + /** + * The string payload of the message, if available. + */ @jsonMember({ name: 'String', constructor: String }) string?: string; + /** + * The bytes payload of the message, if available. + */ @jsonMember({ name: 'Bytes', constructor: ModuleBytes @@ -39,17 +69,29 @@ export class MessagePayload { bytes?: ModuleBytes; } +/** + * Represents a message with a payload, topic, and related metadata. + */ @jsonObject export class Message { + /** + * The payload of the message, which can either be a string or bytes. + */ @jsonMember({ name: 'message', constructor: MessagePayload }) message: MessagePayload; + /** + * The name of the topic associated with this message. + */ @jsonMember({ name: 'topic_name', constructor: String }) topicName: string; + /** + * The hash of the topic name, which is used to identify the topic. + */ @jsonMember({ name: 'topic_name_hash', constructor: Hash, @@ -58,6 +100,9 @@ export class Message { }) topicNameHash: Hash; + /** + * The entity address associated with the message, often the sender or origin. + */ @jsonMember({ name: 'entity_hash', constructor: EntityAddr, @@ -66,9 +111,15 @@ export class Message { }) entityHash: EntityAddr; + /** + * The index of the block where the message was included. + */ @jsonMember({ name: 'block_index', constructor: Number }) blockIndex: number; + /** + * The index of the topic within the block. + */ @jsonMember({ name: 'topic_index', constructor: Number }) topicIndex: number; } diff --git a/src/types/MinimalBlockInfo.ts b/src/types/MinimalBlockInfo.ts index a81a1b729..f1bfc6dbb 100644 --- a/src/types/MinimalBlockInfo.ts +++ b/src/types/MinimalBlockInfo.ts @@ -3,8 +3,16 @@ import { PublicKey } from './keypair'; import { Hash } from './key'; import { Timestamp } from './Time'; +/** + * Represents minimal block information, including metadata such as the creator, + * era ID, block hash, height, state root hash, and timestamp. + */ @jsonObject export class MinimalBlockInfo { + /** + * The public key of the creator of the block. + * This represents the entity that created the block. + */ @jsonMember({ name: 'creator', constructor: PublicKey, @@ -13,9 +21,15 @@ export class MinimalBlockInfo { }) creator: PublicKey; + /** + * The era ID of the block, representing the era in which this block was created. + */ @jsonMember({ name: 'era_id', constructor: Number }) eraID: number; + /** + * The hash of the block, used to uniquely identify it. + */ @jsonMember({ name: 'hash', constructor: Hash, @@ -24,9 +38,16 @@ export class MinimalBlockInfo { }) hash: Hash; + /** + * The height of the block, indicating its position in the blockchain. + */ @jsonMember({ name: 'height', constructor: Number }) height: number; + /** + * The state root hash of the block, representing the state of the blockchain + * after processing the block. + */ @jsonMember({ name: 'state_root_hash', constructor: Hash, @@ -35,6 +56,10 @@ export class MinimalBlockInfo { }) stateRootHash: Hash; + /** + * The timestamp when the block was created. + * This is typically the time when the block was finalized or validated. + */ @jsonMember({ name: 'timestamp', constructor: Timestamp, diff --git a/src/types/NamedKey.ts b/src/types/NamedKey.ts index 281a2137a..1abe62146 100644 --- a/src/types/NamedKey.ts +++ b/src/types/NamedKey.ts @@ -4,11 +4,20 @@ import { CLValue, CLValueParser } from './clvalue'; const ErrNamedKeyNotFound = new Error('NamedKey not found'); +/** + * Represents a named key, consisting of a name and an associated key. + */ @jsonObject export class NamedKey { + /** + * The name of the named key. + */ @jsonMember({ name: 'name', constructor: String }) name: string; + /** + * The key associated with the named key. + */ @jsonMember({ name: 'key', constructor: Key, @@ -17,14 +26,26 @@ export class NamedKey { }) key: Key; + /** + * Creates a new instance of `NamedKey` with a name and key. + * + * @param name The name of the key. + * @param key The associated key. + */ constructor(name: string, key: Key) { this.name = name; this.key = key; } } +/** + * Represents a value of a named key, where both the name and key value are `CLValue` types. + */ @jsonObject export class NamedKeyValue { + /** + * The name of the named key represented as a `CLValue`. + */ @jsonMember({ name: 'name', constructor: CLValue, @@ -39,6 +60,9 @@ export class NamedKeyValue { }) name: CLValue; + /** + * The value of the named key represented as a `CLValue`. + */ @jsonMember({ name: 'named_key', constructor: CLValue, @@ -53,19 +77,41 @@ export class NamedKeyValue { }) namedKey: CLValue; + /** + * Creates a new `NamedKeyValue` instance with a name and named key value. + * + * @param name The name of the named key as a `CLValue`. + * @param namedKey The value of the named key as a `CLValue`. + */ constructor(name: CLValue, namedKey: CLValue) { this.name = name; this.namedKey = namedKey; } } +/** + * Represents a collection of named keys. Provides methods for mapping and finding named keys. + */ export class NamedKeys { + /** + * A list of `NamedKey` objects that are part of this collection. + */ keys: NamedKey[]; + /** + * Creates a new `NamedKeys` instance with an array of `NamedKey` objects. + * + * @param keys An array of `NamedKey` objects. + */ constructor(keys: NamedKey[]) { this.keys = keys; } + /** + * Converts the collection of named keys into a `Map`, where the key is the named key's name and the value is the associated key as a string. + * + * @returns A `Map` with the named key's name as the key and the associated key as the value. + */ toMap(): Map { const result = new Map(); this.keys.forEach(namedKey => { @@ -74,6 +120,13 @@ export class NamedKeys { return result; } + /** + * Finds a `Key` by its name within the collection of named keys. + * + * @param target The name of the named key to find. + * @returns The `Key` associated with the named key if found. + * @throws {Error} If no named key with the specified name is found, throws `ErrNamedKeyNotFound`. + */ find(target: string): Key { for (const nk of this.keys) { if (nk.name === target) { diff --git a/src/types/Package.ts b/src/types/Package.ts index a4858cd75..2ae0ebef6 100644 --- a/src/types/Package.ts +++ b/src/types/Package.ts @@ -1,8 +1,15 @@ import { jsonObject, jsonMember, jsonArrayMember } from 'typedjson'; import { AddressableEntityHash, URef } from './key'; +/** + * Represents an entity version and its associated addressable entity hash. + */ @jsonObject export class EntityVersionAndHash { + /** + * The addressable entity hash associated with the entity. + * This is used to uniquely identify an entity in a decentralized environment. + */ @jsonMember({ name: 'addressable_entity_hash', constructor: AddressableEntityHash, @@ -11,12 +18,21 @@ export class EntityVersionAndHash { }) addressableEntityHash: AddressableEntityHash; + /** + * The key representing the version of the entity. + */ @jsonMember({ name: 'entity_version_key', constructor: () => EntityVersionKey }) entityVersionKey: EntityVersionKey; + /** + * Creates a new instance of `EntityVersionAndHash` with an addressable entity hash and an entity version key. + * + * @param addressableEntityHash The addressable entity hash for the entity. + * @param entityVersionKey The version key of the entity. + */ constructor( addressableEntityHash: AddressableEntityHash, entityVersionKey: EntityVersionKey @@ -26,40 +42,79 @@ export class EntityVersionAndHash { } } +/** + * Represents a package with its versions and disabled versions, along with its lock status and associated groups. + */ @jsonObject export class Package { + /** + * A list of versions associated with this package. + */ @jsonArrayMember(EntityVersionAndHash, { name: 'versions' }) versions: EntityVersionAndHash[]; + /** + * A list of disabled versions of this package. + */ @jsonArrayMember(EntityVersionAndHash, { name: 'disabled_versions' }) disabledVersions: EntityVersionAndHash[]; + /** + * The lock status of the package (e.g., whether it's locked or unlocked). + */ @jsonMember({ name: 'lock_status', constructor: String }) lockStatus: string; + /** + * The groups associated with the package. + */ @jsonArrayMember(String, { name: 'groups' }) groups: string[]; } +/** + * Represents a key that uniquely identifies the version of an entity, including both the entity version and the protocol version. + */ @jsonObject export class EntityVersionKey { + /** + * The version of the entity. + */ @jsonMember({ name: 'entity_version', constructor: Number }) entityVersion: number; + /** + * The major version of the protocol used by the entity. + */ @jsonMember({ name: 'protocol_version_major', constructor: Number }) protocolVersionMajor: number; + /** + * Creates a new instance of `EntityVersionKey` with an entity version and protocol version major. + * + * @param entityVersion The version of the entity. + * @param protocolVersionMajor The major version of the protocol used by the entity. + */ constructor(entityVersion: number, protocolVersionMajor: number) { this.entityVersion = entityVersion; this.protocolVersionMajor = protocolVersionMajor; } } +/** + * Represents a user group with its associated name and users (identified by their URefs). + */ @jsonObject export class NamedUserGroup { + /** + * The name of the user group. + */ @jsonMember({ name: 'group_name', constructor: String }) groupName: string; + /** + * A list of users in the group, represented by their URefs (Universal References). + */ @jsonArrayMember(URef, { name: 'group_users', serializer: (value: URef[]) => value.map(it => it.toJSON()), @@ -67,6 +122,12 @@ export class NamedUserGroup { }) groupUsers: URef[]; + /** + * Creates a new `NamedUserGroup` instance with a group name and a list of group users (URefs). + * + * @param groupName The name of the user group. + * @param groupUsers The list of users in the group, identified by their URefs. + */ constructor(groupName: string, groupUsers: URef[]) { this.groupName = groupName; this.groupUsers = groupUsers; diff --git a/src/types/PricingMode.ts b/src/types/PricingMode.ts index 30a562f35..19ecbfe1c 100644 --- a/src/types/PricingMode.ts +++ b/src/types/PricingMode.ts @@ -4,32 +4,63 @@ import { jsonObject, jsonMember } from 'typedjson'; import { Hash } from './key'; import { CLValueUInt64 } from './clvalue'; +/** + * Enum representing the different pricing modes available. + */ export enum PricingModeTag { + /** Classic pricing mode */ Classic = 0, + /** Fixed pricing mode */ Fixed = 1, + /** Reserved pricing mode */ Reserved = 2 } +/** + * Represents the classic pricing mode, including parameters for gas price tolerance, + * payment amount, and standard payment. + */ @jsonObject export class ClassicMode { + /** + * The tolerance for gas price fluctuations in classic pricing mode. + */ @jsonMember({ name: 'gas_price_tolerance', constructor: Number }) gasPriceTolerance: number; + /** + * The payment amount associated with classic pricing mode. + */ @jsonMember({ name: 'payment_amount', constructor: Number }) paymentAmount: number; + /** + * Whether the payment is a standard payment. + */ @jsonMember({ name: 'standard_payment', constructor: Boolean }) standardPayment: boolean; } +/** + * Represents the fixed pricing mode, including a parameter for gas price tolerance. + */ @jsonObject export class FixedMode { + /** + * The tolerance for gas price fluctuations in fixed pricing mode. + */ @jsonMember({ name: 'gas_price_tolerance', constructor: Number }) gasPriceTolerance: number; } +/** + * Represents the reserved pricing mode, which includes a receipt hash. + */ @jsonObject export class ReservedMode { + /** + * The receipt associated with the reserved pricing mode. + */ @jsonMember({ name: 'receipt', constructor: Hash, @@ -39,17 +70,35 @@ export class ReservedMode { receipt: Hash; } +/** + * Represents the pricing mode, which can be one of the following: Classic, Fixed, or Reserved. + */ @jsonObject export class PricingMode { + /** + * The classic pricing mode, if applicable. + */ @jsonMember({ name: 'Classic', constructor: ClassicMode }) classic?: ClassicMode; + /** + * The fixed pricing mode, if applicable. + */ @jsonMember({ name: 'Fixed', constructor: FixedMode }) fixed?: FixedMode; + /** + * The reserved pricing mode, if applicable. + */ @jsonMember({ name: 'reserved', constructor: ReservedMode }) reserved?: ReservedMode; + /** + * Converts the pricing mode instance into a byte array representation. + * This method serializes the current pricing mode into bytes that can be used for transactions. + * + * @returns A `Uint8Array` representing the serialized pricing mode. + */ toBytes(): Uint8Array { let result: Uint8Array; diff --git a/src/types/Reservation.ts b/src/types/Reservation.ts index b606d2ecb..09e7b9e41 100644 --- a/src/types/Reservation.ts +++ b/src/types/Reservation.ts @@ -2,8 +2,15 @@ import { jsonMember, jsonObject } from 'typedjson'; import { HexBytes } from './HexBytes'; import { Hash } from './key'; +/** + * Represents a reservation, including a receipt, reservation data, and the type of reservation. + */ @jsonObject export class ReservationKind { + /** + * The receipt associated with the reservation. + * This is typically a unique identifier for the reservation. + */ @jsonMember({ name: 'receipt', constructor: Hash, @@ -12,6 +19,10 @@ export class ReservationKind { }) receipt: Hash; + /** + * The reservation data, represented as a `HexBytes` object. + * This can contain specific details regarding the reservation, encoded as hex. + */ @jsonMember({ name: 'reservation_data', constructor: HexBytes, @@ -20,9 +31,20 @@ export class ReservationKind { }) reservationData: HexBytes; + /** + * The kind of reservation, represented as a number. + * This field can be used to distinguish different types of reservations. + */ @jsonMember({ name: 'reservation_kind', constructor: Number }) reservationKind: number; + /** + * Creates a new instance of `ReservationKind`. + * + * @param receipt The receipt associated with the reservation. + * @param reservationData The reservation data encoded as hex. + * @param reservationKind The type of the reservation, represented by a number. + */ constructor( receipt: Hash, reservationData: HexBytes, diff --git a/src/types/SerializationUtils.ts b/src/types/SerializationUtils.ts index 5bd7a7159..a1b72eb78 100644 --- a/src/types/SerializationUtils.ts +++ b/src/types/SerializationUtils.ts @@ -4,9 +4,10 @@ import { Args } from './Args'; import { Conversions } from './Conversions'; /** - * Deserializes a `Uint8Array` into a hexadecimal string - * @param bytes A `Uint8Array` to be deserialized - * @returns A base-16 encoded string of the provided byte array + * Serializes a `Uint8Array` into a hexadecimal string. + * + * @param bytes The `Uint8Array` to be serialized. + * @returns A base-16 encoded string of the provided byte array. */ export const byteArrayJsonSerializer: (bytes: Uint8Array) => string = ( bytes: Uint8Array @@ -15,9 +16,12 @@ export const byteArrayJsonSerializer: (bytes: Uint8Array) => string = ( }; /** - * Deserializes a `Uint8Array` into a hexadecimal string - * @param bytes A `Uint8Array` to be deserialized - * @returns A base-16 encoded string of the provided byte array + * Serializes a `Uint8Array` into a hexadecimal string, but only if the value is not `undefined`. + * + * @param bytes The `Uint8Array` to be serialized (or `undefined`). + * @returns A base-16 encoded string of the provided byte array, or `undefined` if input is `undefined`. + * + * @note It's suggested to swap the names of this function with `byteArrayJsonSerializer` for better clarity. This function handles `undefined` inputs, while `byteArrayJsonSerializer` should handle only `Uint8Array` directly. */ export const undefinedSafeByteArrayJsonSerializer: ( bytes: Uint8Array | undefined @@ -28,12 +32,11 @@ export const undefinedSafeByteArrayJsonSerializer: ( return Conversions.encodeBase16(bytes); }; -//Shouldn't the above and below function names be swapped? - /** - * Serializes a hexadecimal string to a `Uint8Array` - * @param bytes A hexadecimal string to be serialized - * @returns A base-16 encoded string of the provided byte array + * Deserializes a hexadecimal string into a `Uint8Array`. + * + * @param str The base-16 encoded string to be deserialized. + * @returns The decoded `Uint8Array` corresponding to the hexadecimal string. */ export const byteArrayJsonDeserializer: (str: string) => Uint8Array = ( str: string @@ -42,9 +45,10 @@ export const byteArrayJsonDeserializer: (str: string) => Uint8Array = ( }; /** - * Serializes a hexadecimal string to a `Uint8Array` - * @param bytes A hexadecimal string to be serialized - * @returns A base-16 encoded string of the provided byte array + * Deserializes a hexadecimal string into a `Uint8Array`, but only if the value is not `undefined`. + * + * @param str The base-16 encoded string to be deserialized (or `undefined`). + * @returns The decoded `Uint8Array` corresponding to the hexadecimal string, or `undefined` if input is `undefined`. */ export const undefinedSafeByteArrayJsonDeserializer: ( str: string | undefined @@ -55,6 +59,9 @@ export const undefinedSafeByteArrayJsonDeserializer: ( return Conversions.decodeBase16(str); }; +/** + * A humanizer configuration for time durations in short English format (days, hours, minutes, seconds, milliseconds). + */ const shortEnglishHumanizer = humanizeDuration.humanizer({ spacer: '', serialComma: false, @@ -62,7 +69,7 @@ const shortEnglishHumanizer = humanizeDuration.humanizer({ delimiter: ' ', language: 'shortEn', languages: { - // https://docs.rs/humantime/2.0.1/humantime/fn.parse_duration.html + // Mapping of duration units to shorter names shortEn: { d: () => 'day', h: () => 'h', @@ -74,18 +81,21 @@ const shortEnglishHumanizer = humanizeDuration.humanizer({ }); /** - * Returns a humanizer duration - * @param ttl in milliseconds - * @returns A human-readable time in days, hours, minutes, seconds, then milliseconds + * Returns a human-readable time duration for a given time-to-live (TTL) in milliseconds. + * + * @param ttl The TTL in milliseconds. + * @returns A human-readable string representation of the TTL, such as "1d 2h 3m 4s". */ export const humanizerTTL = (ttl: number) => { return shortEnglishHumanizer(ttl); }; /** - * Returns duration in milliseconds - * @param ttl Human-readable string generated by [humanizerTTL](#L91) - * @returns The time-to-live in milliseconds + * Converts a human-readable time duration (e.g., "1d 2h 3m 4s") back to a time-to-live (TTL) in milliseconds. + * + * @param ttl The human-readable string representing the time duration. + * @returns The TTL in milliseconds. + * @throws Error if an unsupported TTL unit is encountered. */ export const dehumanizerTTL = (ttl: string): number => { const dehumanizeUnit = (s: string): number => { @@ -104,7 +114,7 @@ export const dehumanizerTTL = (ttl: string): number => { if (s.includes('day')) { return Number(s.replace('day', '')) * 24 * 60 * 60 * 1000; } - throw Error('Unsuported TTL unit'); + throw Error('Unsupported TTL unit'); }; return ttl @@ -114,9 +124,10 @@ export const dehumanizerTTL = (ttl: string): number => { }; /** - * Deserializes an array of runtime arguments to a `RuntimeArgs` object - * @param arr An array of type `any` containing valid serialized runtime arguments. Can be generated from [serRA](#L338) - * @returns `RuntimeArgs` object + * Deserializes an array of runtime arguments to a `RuntimeArgs` object. + * + * @param arr The array of serialized runtime arguments. + * @returns A `RuntimeArgs` object containing the deserialized arguments. */ export const deserializeArgs = (arr: any) => { const raSerializer = new TypedJSON(Args); @@ -127,9 +138,10 @@ export const deserializeArgs = (arr: any) => { }; /** - * Serializes a `RuntimeArgs` object to a byte array - * @param ra `RuntimeArgs` object to be serialized - * @returns A serialized byte array of runtime arguments, which can be deserialized by [desRA](#L326) + * Serializes a `RuntimeArgs` object to a byte array. + * + * @param ra The `RuntimeArgs` object to be serialized. + * @returns A byte array representing the serialized runtime arguments. */ export const serializeArgs = (ra: Args) => { const raSerializer = new TypedJSON(Args); diff --git a/src/types/StoredValue.ts b/src/types/StoredValue.ts index c9ae3782d..1fa26a0f2 100644 --- a/src/types/StoredValue.ts +++ b/src/types/StoredValue.ts @@ -18,8 +18,16 @@ import { Contract } from './Contract'; import { ContractPackage } from './ContractPackage'; import { CLValue, CLValueParser } from './clvalue'; +/** + * Represents a stored value in a decentralized system. The value can be of different types + * like `Account`, `Contract`, `Transfer`, etc. Each field corresponds to a specific type of + * stored data in the system. + */ @jsonObject export class StoredValue { + /** + * The stored `CLValue`, which is a general-purpose value that can represent various types of data. + */ @jsonMember({ name: 'CLValue', constructor: CLValue, @@ -34,45 +42,87 @@ export class StoredValue { }) clValue?: CLValue; + /** + * The stored account information. + */ @jsonMember({ name: 'Account', constructor: Account }) account?: Account; + /** + * The stored contract information. + */ @jsonMember({ name: 'Contract', constructor: Contract }) contract?: Contract; + /** + * The WebAssembly (WASM) bytecode for the contract, represented as `AnyT`. + */ @jsonMember({ name: 'ContractWASM', constructor: AnyT }) contractWASM?: any; + /** + * The stored contract package information. + */ @jsonMember({ name: 'ContractPackage', constructor: ContractPackage }) contractPackage?: ContractPackage; + /** + * The legacy transfer information, representing a historical transfer. + */ @jsonMember({ name: 'LegacyTransfer', constructor: TransferV1 }) legacyTransfer?: TransferV1; + /** + * The information related to a deploy operation. + */ @jsonMember({ name: 'DeployInfo', constructor: DeployInfo }) deployInfo?: DeployInfo; + /** + * The information related to an era. + */ @jsonMember({ name: 'EraInfo', constructor: EraInfo }) eraInfo?: EraInfo; + /** + * The stored bid information, typically related to a staking or auction process. + */ @jsonMember({ name: 'Bid', constructor: Bid }) bid?: Bid; + /** + * An array of unbonding purses, which represent assets being unbonded. + */ @jsonArrayMember(UnbondingPurse, { name: 'Withdraw' }) withdraw?: UnbondingPurse[]; + /** + * The stored unbonding purse, representing assets being unbonded. + */ @jsonMember({ name: 'Unbonding', constructor: UnbondingPurse }) unbonding?: UnbondingPurse; + /** + * The stored addressable entity information, which is a reference to a contract or other addressable entity. + */ @jsonMember({ name: 'AddressableEntity', constructor: AddressableEntity }) addressableEntity?: AddressableEntity; + /** + * The stored bid kind, representing the type or class of a bid. + */ @jsonMember({ name: 'BidKind', constructor: BidKind }) bidKind?: BidKind; + /** + * The stored package information, typically a contract or executable package. + */ @jsonMember({ name: 'Package', constructor: Package }) package?: Package; + /** + * The stored bytecode, representing compiled contract or executable code. + */ @jsonMember({ name: 'ByteCode', constructor: ByteCode, @@ -87,18 +137,33 @@ export class StoredValue { }) byteCode?: ByteCode; + /** + * The stored message topic summary, containing a summary of the message topic. + */ @jsonMember({ name: 'MessageTopic', constructor: MessageTopicSummary }) messageTopic?: MessageTopicSummary; + /** + * A checksum of the stored message, typically used for validation purposes. + */ @jsonMember({ name: 'Message', constructor: String }) message?: MessageChecksum; + /** + * The stored named key value, representing a key-value pair within a contract or other entity. + */ @jsonMember({ name: 'NamedKey', constructor: NamedKeyValue }) namedKey?: NamedKeyValue; + /** + * The reservation information related to this stored value. + */ @jsonMember({ name: 'Reservation', constructor: ReservationKind }) reservation?: ReservationKind; + /** + * The stored entry point value, typically representing an entry point in a smart contract. + */ @jsonMember({ name: 'EntryPoint', constructor: EntryPointValue }) entryPoint?: EntryPointValue; } diff --git a/src/types/Time.ts b/src/types/Time.ts index 8844ec660..057097f9b 100644 --- a/src/types/Time.ts +++ b/src/types/Time.ts @@ -1,56 +1,121 @@ import { jsonObject, jsonMember } from 'typedjson'; import { dehumanizerTTL, humanizerTTL } from './SerializationUtils'; +/** + * Represents a timestamp as a specific point in time (Date). + */ @jsonObject export class Timestamp { + /** + * The Date object representing the timestamp. + */ @jsonMember({ constructor: Date }) date: Date; + /** + * Creates a new instance of `Timestamp` with the specified Date. + * + * @param date The `Date` object representing the timestamp. + */ constructor(date: Date) { this.date = date; } + /** + * Converts the timestamp to milliseconds (Unix timestamp). + * + * @returns The timestamp in milliseconds. + */ toMilliseconds(): number { - //unixMilli return this.date.getTime(); } + /** + * Converts the timestamp to a JSON string (ISO 8601 format). + * + * @returns A JSON string representing the timestamp. + */ toJSON(): string { return this.date.toISOString(); } + /** + * Creates a `Timestamp` instance from a JSON string. + * + * @param data The JSON string representing the timestamp in ISO 8601 format. + * @returns A `Timestamp` object. + */ static fromJSON(data: string): Timestamp { return new Timestamp(new Date(data)); } + /** + * Returns the underlying `Date` object of the timestamp. + * + * @returns The `Date` object representing the timestamp. + */ toDate(): Date { return this.date; } } +/** + * Represents a duration, typically in milliseconds, with utility methods for parsing and formatting. + */ @jsonObject export class Duration { + /** + * The duration in milliseconds. + */ @jsonMember({ constructor: Number }) duration: number; + /** + * Creates a new instance of `Duration` with the specified duration in milliseconds. + * + * @param duration The duration in milliseconds. + */ constructor(duration: number) { this.duration = duration; } + /** + * Converts the duration to a human-readable string. + * + * @returns A string representing the duration in a human-readable format (e.g., "1d 2h 3m 4s"). + */ toJSON(): string { return humanizerTTL(this.duration); } + /** + * Creates a `Duration` instance from a human-readable string representing the duration. + * + * @param data The human-readable string representing the duration (e.g., "1d 2h 3m 4s"). + * @returns A `Duration` object. + */ static fromJSON(data: string): Duration { const duration = dehumanizerTTL(data); return new Duration(duration); } + /** + * Converts the duration to a string in the format `hh:mm:ss`. + * + * @returns A string representing the duration in `hh:mm:ss` format. + */ toDurationString(): string { return new Date(this.duration).toISOString().substring(11, 19); } + /** + * Parses a duration string (e.g., "1d 2h 3m") and converts it to milliseconds. + * + * @param durationStr The string representing the duration in a human-readable format. + * @returns The duration in milliseconds. + * @throws Error if the duration format is invalid. + */ static parseDurationString(durationStr: string): number { const parts = durationStr.match(/(\d+)([smhd])/g); if (!parts) throw new Error('Invalid duration format'); @@ -77,6 +142,11 @@ export class Duration { return totalMs; } + /** + * Returns the duration in milliseconds. + * + * @returns The duration in milliseconds. + */ toMilliseconds(): number { return this.duration; } diff --git a/src/types/Transaction.ts b/src/types/Transaction.ts index 8371b928f..eac7cf89c 100644 --- a/src/types/Transaction.ts +++ b/src/types/Transaction.ts @@ -17,18 +17,40 @@ import { Args } from './Args'; import { deserializeArgs, serializeArgs } from './SerializationUtils'; import { byteHash } from './ByteConverters'; +/** + * Custom error class for handling transaction-related errors. + */ export class TransactionError extends Error {} + +/** + * Error to indicate an invalid body hash in a transaction. + */ export const ErrInvalidBodyHash = new TransactionError('invalid body hash'); + +/** + * Error to indicate an invalid transaction hash. + */ export const ErrInvalidTransactionHash = new TransactionError( 'invalid transaction hash' ); + +/** + * Error to indicate an invalid approval signature in a transaction. + */ export const ErrInvalidApprovalSignature = new TransactionError( 'invalid approval signature' ); + +/** + * Error to indicate an issue parsing JSON as a TransactionV1. + */ export const ErrTransactionV1FromJson = new TransactionError( "The JSON can't be parsed as a TransactionV1." ); +/** + * Enum representing the categories of transactions. + */ export enum TransactionCategory { Mint = 0, Auction, @@ -38,13 +60,22 @@ export enum TransactionCategory { Small } +/** + * Enum representing the versions of transactions. + */ export enum TransactionVersion { V1 = 0, Deploy } +/** + * Represents an approval for a transaction with a signer and signature. + */ @jsonObject export class Approval { + /** + * The public key of the signer. + */ @jsonMember({ name: 'signer', constructor: PublicKey, @@ -53,6 +84,9 @@ export class Approval { }) public signer: PublicKey; + /** + * The signature of the transaction signed by the signer. + */ @jsonMember({ name: 'signature', constructor: HexBytes, @@ -61,17 +95,31 @@ export class Approval { }) public signature: HexBytes; + /** + * Constructs an `Approval` instance with a signer and signature. + * @param signer The public key of the signer. + * @param signature The signature of the transaction. + */ constructor(signer: PublicKey, signature: HexBytes) { this.signer = signer; this.signature = signature; } } +/** + * Represents the header of a TransactionV1. + */ @jsonObject export class TransactionV1Header { + /** + * The name of the blockchain. + */ @jsonMember({ name: 'chain_name', constructor: String }) public chainName: string; + /** + * The timestamp of the transaction. + */ @jsonMember({ name: 'timestamp', constructor: Timestamp, @@ -80,6 +128,9 @@ export class TransactionV1Header { }) public timestamp: Timestamp; + /** + * The time-to-live (TTL) duration of the transaction. + */ @jsonMember({ name: 'ttl', constructor: Duration, @@ -88,6 +139,9 @@ export class TransactionV1Header { }) public ttl: Duration; + /** + * The address of the transaction initiator. + */ @jsonMember({ name: 'initiator_addr', constructor: InitiatorAddr, @@ -96,9 +150,15 @@ export class TransactionV1Header { }) public initiatorAddr: InitiatorAddr; + /** + * The pricing mode used for the transaction. + */ @jsonMember({ name: 'pricing_mode', constructor: PricingMode }) public pricingMode: PricingMode; + /** + * The hash of the transaction body. + */ @jsonMember({ name: 'body_hash', constructor: Hash, @@ -107,6 +167,15 @@ export class TransactionV1Header { }) public bodyHash: Hash; + /** + * Builds a `TransactionV1Header` from the provided properties. + * @param initiatorAddr The initiator's address. + * @param timestamp The timestamp of the transaction. + * @param ttl The TTL of the transaction. + * @param chainName The chain name. + * @param pricingMode The pricing mode for the transaction. + * @returns The constructed `TransactionV1Header`. + */ static build({ initiatorAddr, timestamp, @@ -130,6 +199,10 @@ export class TransactionV1Header { return header; } + /** + * Serializes the header to a byte array. + * @returns The serialized byte array representing the header. + */ public toBytes(): Uint8Array { const chainNameBytes = CLValueString.newCLString(this.chainName).bytes(); const timestampMillis = this.timestamp.toMilliseconds(); @@ -154,8 +227,14 @@ export class TransactionV1Header { } } +/** + * Represents the body of a TransactionV1. + */ @jsonObject export class TransactionV1Body { + /** + * The arguments for the transaction. + */ @jsonMember({ name: 'args', constructor: Args, @@ -164,6 +243,9 @@ export class TransactionV1Body { }) public args: Args; + /** + * The target of the transaction. + */ @jsonMember({ name: 'target', constructor: TransactionTarget, @@ -172,6 +254,9 @@ export class TransactionV1Body { }) public target: TransactionTarget; + /** + * The entry point for the transaction. + */ @jsonMember({ name: 'entry_point', constructor: TransactionEntryPoint, @@ -180,9 +265,15 @@ export class TransactionV1Body { }) public entryPoint: TransactionEntryPoint; + /** + * The category of the transaction. + */ @jsonMember({ name: 'transaction_category', constructor: Number }) public category: number; + /** + * The scheduling information for the transaction. + */ @jsonMember({ name: 'scheduling', constructor: TransactionScheduling, @@ -191,6 +282,15 @@ export class TransactionV1Body { }) public scheduling: TransactionScheduling; + /** + * Builds a `TransactionV1Body` from the provided properties. + * @param args The arguments for the transaction. + * @param target The target of the transaction. + * @param transactionEntryPoint The entry point for the transaction. + * @param transactionScheduling The scheduling for the transaction. + * @param transactionCategory The category of the transaction. + * @returns The constructed `TransactionV1Body`. + */ static build({ args, target, @@ -213,6 +313,10 @@ export class TransactionV1Body { return body; } + /** + * Serializes the body to a byte array. + * @returns The serialized byte array representing the body. + */ toBytes(): Uint8Array { const argsBytes = this.args?.toBytes() || new Uint8Array(); const targetBytes = this.target.toBytes(); @@ -230,8 +334,14 @@ export class TransactionV1Body { } } +/** + * Represents a TransactionV1 object, including its header, body, and approvals. + */ @jsonObject export class TransactionV1 { + /** + * The hash of the transaction. + */ @jsonMember({ name: 'hash', constructor: Hash, @@ -240,12 +350,21 @@ export class TransactionV1 { }) public hash: Hash; + /** + * The header of the transaction. + */ @jsonMember({ name: 'header', constructor: TransactionV1Header }) public header: TransactionV1Header; + /** + * The body of the transaction. + */ @jsonMember({ name: 'body', constructor: TransactionV1Body }) public body: TransactionV1Body; + /** + * The approvals for the transaction. + */ @jsonArrayMember(() => Approval) public approvals: Approval[]; @@ -261,6 +380,10 @@ export class TransactionV1 { this.approvals = approvals; } + /** + * Validates the transaction by checking the body hash and the approval signatures. + * @throws {TransactionError} Throws errors if validation fails. + */ public validate(): void { const bodyBytes = this.body.toBytes(); @@ -284,6 +407,12 @@ export class TransactionV1 { } } + /** + * Compares two arrays for equality. + * @param a The first array. + * @param b The second array. + * @returns `true` if the arrays are equal, `false` otherwise. + */ private arrayEquals(a: Uint8Array, b: Uint8Array): boolean { if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) { @@ -292,6 +421,10 @@ export class TransactionV1 { return true; } + /** + * Signs the transaction using the provided private key. + * @param keys The private key to sign the transaction. + */ async sign(keys: PrivateKey): Promise { const signatureBytes = await keys.sign(this.hash.toBytes()); const signature = new HexBytes(signatureBytes); @@ -304,11 +437,11 @@ export class TransactionV1 { } /** - * Sets already generated signature - * - * @param transaction the TransactionV1 instance - * @param signature the Ed25519 or Secp256K1 signature - * @param publicKey the public key used to generate the signature + * Sets an already generated signature to the transaction. + * @param transaction The `TransactionV1` instance. + * @param signature The Ed25519 or Secp256K1 signature. + * @param publicKey The public key used to generate the signature. + * @returns The updated `TransactionV1`. */ static setSignature( transaction: TransactionV1, @@ -321,6 +454,14 @@ export class TransactionV1 { return transaction; } + /** + * Creates a new `TransactionV1` instance. + * @param hash The hash of the transaction. + * @param header The header of the transaction. + * @param body The body of the transaction. + * @param approvals The approvals for the transaction. + * @returns A new `TransactionV1` instance. + */ static newTransactionV1( hash: Hash, header: TransactionV1Header, @@ -330,6 +471,12 @@ export class TransactionV1 { return new TransactionV1(hash, header, body, approvals); } + /** + * Creates a new `TransactionV1` instance with a header and body. + * @param transactionHeader The header of the transaction. + * @param transactionBody The body of the transaction. + * @returns A new `TransactionV1` instance. + */ static makeTransactionV1( transactionHeader: TransactionV1Header, transactionBody: TransactionV1Body @@ -348,10 +495,10 @@ export class TransactionV1 { } /** - * Convert a JSON representation of a transactionV1 to a `TransactionV1` object - * - * @param json A JSON representation of a `TransactionV1` - * @returns A `TransactionV1` object if successful, or throws an error if parsing fails + * Converts a JSON representation of a `TransactionV1` to a `TransactionV1` object. + * @param json A JSON representation of a `TransactionV1`. + * @returns A `TransactionV1` object. + * @throws {TransactionError} If parsing fails. */ public static fromJSON(json: any): TransactionV1 { let tx: TransactionV1 | undefined; @@ -382,10 +529,9 @@ export class TransactionV1 { } /** - * Convert the transactionV1 object to a JSON representation - * - * @param transaction The `TransactionV1` object to convert to JSON - * @returns A JSON version of the `TransactionV1`, which can be converted back later + * Converts the `TransactionV1` object to a JSON representation. + * @param transaction The `TransactionV1` object. + * @returns A JSON version of the `TransactionV1`. */ public static toJson = (transaction: TransactionV1) => { const serializer = new TypedJSON(TransactionV1); @@ -394,11 +540,21 @@ export class TransactionV1 { }; } +/** + * Represents the header of a transaction, including details like chain name, timestamp, + * time-to-live (TTL), initiator address, and pricing mode. + */ @jsonObject export class TransactionHeader { + /** + * The name of the blockchain chain associated with this transaction. + */ @jsonMember({ name: 'chain_name', constructor: String }) public chainName: string; + /** + * The timestamp when the transaction was created. + */ @jsonMember({ name: 'timestamp', constructor: Timestamp, @@ -407,6 +563,9 @@ export class TransactionHeader { }) public timestamp: Timestamp; + /** + * The time-to-live (TTL) duration of the transaction. It defines the expiration time for the transaction. + */ @jsonMember({ name: 'ttl', constructor: Duration, @@ -415,6 +574,9 @@ export class TransactionHeader { }) public ttl: Duration; + /** + * The address of the initiator of the transaction. + */ @jsonMember({ name: 'initiator_addr', constructor: InitiatorAddr, @@ -423,9 +585,20 @@ export class TransactionHeader { }) public initiatorAddr: InitiatorAddr; + /** + * The pricing mode used for the transaction, which may involve different cost mechanisms. + */ @jsonMember({ name: 'pricing_mode', constructor: PricingMode }) public pricingMode: PricingMode; + /** + * Creates a new `TransactionHeader` instance with the given properties. + * @param chainName The name of the blockchain chain. + * @param timestamp The timestamp of the transaction. + * @param ttl The TTL (Time-To-Live) for the transaction. + * @param initiatorAddr The address of the transaction initiator. + * @param pricingMode The pricing mode for the transaction. + */ constructor( chainName: string, timestamp: Timestamp, @@ -441,8 +614,15 @@ export class TransactionHeader { } } +/** + * Represents the body of a transaction, containing the arguments, target, + * entry point, scheduling information, and transaction category. + */ @jsonObject export class TransactionBody { + /** + * The arguments for the transaction, which can be a map of values required by the entry point. + */ @jsonMember({ constructor: Args, name: 'args', @@ -451,6 +631,9 @@ export class TransactionBody { }) public args: Args; + /** + * The target of the transaction, which specifies where the transaction is directed (e.g., a contract or account). + */ @jsonMember({ name: 'target', constructor: TransactionTarget, @@ -459,6 +642,9 @@ export class TransactionBody { }) public target: TransactionTarget; + /** + * The entry point of the transaction, specifying the method or action to be executed. + */ @jsonMember({ name: 'entry_point', constructor: TransactionEntryPoint, @@ -467,6 +653,9 @@ export class TransactionBody { }) public entryPoint: TransactionEntryPoint; + /** + * The scheduling information for when the transaction should be executed. + */ @jsonMember({ name: 'scheduling', constructor: TransactionScheduling, @@ -475,9 +664,20 @@ export class TransactionBody { }) public scheduling: TransactionScheduling; + /** + * The category of the transaction, indicating its type (e.g., minting, auction). + */ @jsonMember({ name: 'transaction_category', constructor: Number }) public category: number; + /** + * Constructs a `TransactionBody` with the given arguments, target, entry point, scheduling, and category. + * @param args The arguments for the transaction. + * @param target The target of the transaction (e.g., a contract or account). + * @param entryPoint The entry point to specify the method or action of the transaction. + * @param scheduling The scheduling information for the transaction's execution. + * @param category The category/type of the transaction (e.g., mint, auction). + */ constructor( args: Args, target: TransactionTarget, @@ -493,8 +693,15 @@ export class TransactionBody { } } +/** + * Represents a transaction in the system, containing information such as its hash, + * header, body, approvals, and optionally its associated deployment and transaction details. + */ @jsonObject export class Transaction { + /** + * The hash of the transaction. + */ @jsonMember({ name: 'hash', constructor: Hash, @@ -503,18 +710,45 @@ export class Transaction { }) public hash: Hash; + /** + * The header of the transaction, which includes metadata about the transaction. + */ @jsonMember({ name: 'header', constructor: TransactionHeader }) public header: TransactionHeader; + /** + * The body of the transaction, containing details such as the target, entry point, and arguments. + */ @jsonMember({ name: 'body', constructor: TransactionBody }) public body: TransactionBody; + /** + * The list of approvals for this transaction. + */ @jsonArrayMember(Approval) public approvals: Approval[]; + /** + * The original deployment associated with this transaction, if applicable. + * This is optional and only populated if the transaction originated from a deploy. + */ private originDeployV1?: Deploy; + + /** + * The original TransactionV1 associated with this transaction, if applicable. + * This is optional and only populated if the transaction is based on a TransactionV1. + */ private originTransactionV1?: TransactionV1; + /** + * Creates a new `Transaction` instance with the specified values. + * @param hash The hash of the transaction. + * @param header The header of the transaction. + * @param body The body of the transaction. + * @param approvals The list of approvals for this transaction. + * @param originTransactionV1 The original TransactionV1, if applicable. + * @param originDeployV1 The original deploy, if applicable. + */ constructor( hash: Hash, header: TransactionHeader, @@ -531,14 +765,27 @@ export class Transaction { this.originTransactionV1 = originTransactionV1; } + /** + * Gets the original deployment associated with this transaction, if available. + * @returns The original deploy or `undefined` if not available. + */ public getDeploy(): Deploy | undefined { return this.originDeployV1; } + /** + * Gets the original TransactionV1 associated with this transaction, if available. + * @returns The original TransactionV1 or `undefined` if not available. + */ public getTransactionV1(): TransactionV1 | undefined { return this.originTransactionV1; } + /** + * Converts a `TransactionV1` to a `Transaction` object. + * @param v1 The `TransactionV1` to convert. + * @returns A new `Transaction` instance created from the given `TransactionV1`. + */ static fromTransactionV1(v1: TransactionV1): Transaction { return new Transaction( v1.hash, @@ -562,22 +809,47 @@ export class Transaction { } } +/** + * Wrapper class for transactions, allowing for both `Deploy` and `TransactionV1` to be stored + * in the same object. This can be useful when working with multiple versions of transactions. + */ @jsonObject export class TransactionWrapper { - @jsonMember({ name: 'Deploy', constructor: Deploy }) + /** + * The deployment object associated with the transaction, if applicable. + * This will contain the details of the deploy transaction. + */ + @jsonMember({ name: 'Deploy', constructor: () => Deploy }) deploy?: Deploy; + /** + * The version 1 transaction object, if applicable. + * This will contain the details of a TransactionV1, which represents the first version of a transaction. + */ @jsonMember({ name: 'Version1', constructor: TransactionV1 }) transactionV1?: TransactionV1; + /** + * Constructs a new `TransactionWrapper` instance with the provided `Deploy` and `TransactionV1` values. + * @param deploy The `Deploy` object, if applicable. + * @param transactionV1 The `TransactionV1` object, if applicable. + */ constructor(deploy?: Deploy, transactionV1?: TransactionV1) { this.deploy = deploy; this.transactionV1 = transactionV1; } } +/** + * Represents a transaction hash, which can either be associated with a `Deploy` or a `TransactionV1`. + * This class helps in wrapping transaction hashes from different transaction types. + */ @jsonObject export class TransactionHash { + /** + * The hash associated with the deploy transaction, if applicable. + * This will contain the hash of the `Deploy` transaction. + */ @jsonMember({ name: 'Deploy', constructor: Hash, @@ -592,6 +864,10 @@ export class TransactionHash { }) public deploy?: Hash; + /** + * The hash associated with the version 1 transaction, if applicable. + * This will contain the hash of the `TransactionV1`. + */ @jsonMember({ name: 'Version1', constructor: Hash, @@ -603,6 +879,11 @@ export class TransactionHash { }) public transactionV1?: Hash; + /** + * Constructs a new `TransactionHash` instance, which can hold either a `Deploy` hash or a `TransactionV1` hash. + * @param deploy The hash of the deploy transaction, if applicable. + * @param transactionV1 The hash of the version 1 transaction, if applicable. + */ constructor(deploy?: Hash, transactionV1?: Hash) { this.deploy = deploy; this.transactionV1 = transactionV1; diff --git a/src/types/TransactionEntryPoint.ts b/src/types/TransactionEntryPoint.ts index 1db2e9f7b..e41931d33 100644 --- a/src/types/TransactionEntryPoint.ts +++ b/src/types/TransactionEntryPoint.ts @@ -3,6 +3,9 @@ import { concat } from '@ethersproject/bytes'; import { CLValueString } from './clvalue'; +/** + * Enum representing the available transaction entry points, each representing a different operation in the system. + */ export enum TransactionEntryPointEnum { Custom = 'Custom', Transfer = 'Transfer', @@ -16,6 +19,9 @@ export enum TransactionEntryPointEnum { Call = 'Call' } +/** + * Enum representing the tags for different transaction entry points. This is used for efficient storage and comparison. + */ export enum TransactionEntryPointTag { Custom = 0, Transfer, @@ -29,39 +35,86 @@ export enum TransactionEntryPointTag { Call } +/** + * Represents a transaction entry point, which can be one of several predefined actions or a custom action. + * This class contains multiple fields that correspond to different transaction actions. + */ @jsonObject export class TransactionEntryPoint { + /** + * Custom entry point, where the value can be a string representing a custom action. + */ @jsonMember({ constructor: String }) custom?: string; - // Use Record for generic empty objects + /** + * The transfer action as a generic object. + */ @jsonMember({ constructor: Object }) transfer?: Record; + /** + * The add bid action as a generic object. + */ @jsonMember({ constructor: Object }) addBid?: Record; + /** + * The withdraw bid action as a generic object. + */ @jsonMember({ constructor: Object }) withdrawBid?: Record; + /** + * The delegate action as a generic object. + */ @jsonMember({ constructor: Object }) delegate?: Record; + /** + * The undelegate action as a generic object. + */ @jsonMember({ constructor: Object }) undelegate?: Record; + /** + * The redelegate action as a generic object. + */ @jsonMember({ constructor: Object }) redelegate?: Record; + /** + * The activate bid action as a generic object. + */ @jsonMember({ constructor: Object }) activateBid?: Record; + /** + * The change bid public key action as a generic object. + */ @jsonMember({ constructor: Object }) changeBidPublicKey?: Record; + /** + * The call action as a generic object. + */ @jsonMember({ constructor: Object }) call?: Record; + /** + * Creates a new `TransactionEntryPoint` instance, where each parameter corresponds to a specific entry point action. + * + * @param custom A custom entry point action represented as a string. + * @param transfer The transfer action, represented as a generic object. + * @param addBid The add bid action, represented as a generic object. + * @param withdrawBid The withdraw bid action, represented as a generic object. + * @param delegate The delegate action, represented as a generic object. + * @param undelegate The undelegate action, represented as a generic object. + * @param redelegate The redelegate action, represented as a generic object. + * @param activateBid The activate bid action, represented as a generic object. + * @param changeBidPublicKey The change bid public key action, represented as a generic object. + * @param call The call action, represented as a generic object. + */ constructor( custom?: string, transfer?: Record, @@ -86,6 +139,11 @@ export class TransactionEntryPoint { this.call = call; } + /** + * Returns the tag corresponding to the transaction entry point. This helps identify the entry point in a compact manner. + * + * @returns The tag number associated with the entry point. + */ private tag(): number { if (this.transfer) return TransactionEntryPointTag.Transfer; if (this.addBid) return TransactionEntryPointTag.AddBid; @@ -100,6 +158,11 @@ export class TransactionEntryPoint { return TransactionEntryPointTag.Custom; } + /** + * Serializes the transaction entry point into a byte array. + * + * @returns A `Uint8Array` representing the transaction entry point and any associated data. + */ bytes(): Uint8Array { let result = new Uint8Array([this.tag()]); if (this.custom) { @@ -109,6 +172,12 @@ export class TransactionEntryPoint { return result; } + /** + * Converts the transaction entry point to a JSON-compatible format. + * + * @returns A JSON-compatible representation of the transaction entry point. + * @throws An error if the entry point is unknown. + */ toJSON(): unknown { if (this.custom) { return { Custom: this.custom }; @@ -128,6 +197,13 @@ export class TransactionEntryPoint { throw new Error('Unknown entry point'); } + /** + * Creates a `TransactionEntryPoint` instance from a JSON representation. + * + * @param json The JSON representation of the entry point. + * @returns A `TransactionEntryPoint` instance. + * @throws An error if the entry point is unknown. + */ static fromJSON(json: any): TransactionEntryPoint { const entryPoint = new TransactionEntryPoint(); if (json instanceof Object && json.Custom) { diff --git a/src/types/TransactionScheduling.ts b/src/types/TransactionScheduling.ts index 006935d55..76dda0b3c 100644 --- a/src/types/TransactionScheduling.ts +++ b/src/types/TransactionScheduling.ts @@ -4,24 +4,47 @@ import { concat } from '@ethersproject/bytes'; import { Timestamp } from './Time'; import { CLValueUInt64 } from './clvalue'; +/** + * Enum representing the scheduling tags for transaction scheduling types. + */ export enum TransactionSchedulingTag { + /** Native scheduling, meaning no future scheduling is applied. */ Native = 0, + /** Future scheduling based on the era ID. */ FutureEra, + /** Future scheduling based on a specific timestamp. */ FutureTimestamp } +/** + * Represents the scheduling for a transaction in a future era. + */ @jsonObject class FutureEraScheduling { + /** + * The ID of the future era when the transaction is scheduled to occur. + */ @jsonMember({ constructor: Number }) eraID: number; + /** + * Creates a new instance of `FutureEraScheduling`. + * + * @param eraID The era ID when the transaction is scheduled. + */ constructor(eraID: number) { this.eraID = eraID; } } +/** + * Represents the scheduling for a transaction in a future timestamp. + */ @jsonObject class FutureTimestampScheduling { + /** + * The timestamp when the transaction is scheduled to occur. + */ @jsonMember({ name: 'FutureTimestamp', constructor: Timestamp, @@ -30,25 +53,49 @@ class FutureTimestampScheduling { }) timestamp: Timestamp; + /** + * Creates a new instance of `FutureTimestampScheduling`. + * + * @param timestamp The timestamp when the transaction is scheduled. + */ constructor(timestamp: Timestamp) { this.timestamp = timestamp; } } +/** + * Represents a transaction scheduling, which could be either immediate (standard), scheduled for a future era, or scheduled for a future timestamp. + */ @jsonObject export class TransactionScheduling { + /** + * Represents the standard (immediate) scheduling with no future scheduling. + */ @jsonMember({ name: 'Standard', constructor: Object }) standard?: object; + /** + * Represents scheduling to a future era with a specified `eraID`. + */ @jsonMember({ name: 'FutureEra', constructor: FutureEraScheduling }) futureEra?: FutureEraScheduling; + /** + * Represents scheduling to a future timestamp with a specified `timestamp`. + */ @jsonMember({ name: 'FutureTimestamp', constructor: FutureTimestampScheduling }) futureTimestamp?: FutureTimestampScheduling; + /** + * Creates a new instance of `TransactionScheduling`. + * + * @param standard The standard scheduling with no delay. + * @param futureEra The future era scheduling. + * @param futureTimestamp The future timestamp scheduling. + */ constructor( standard?: object, futureEra?: FutureEraScheduling, @@ -59,6 +106,11 @@ export class TransactionScheduling { this.futureTimestamp = futureTimestamp; } + /** + * Determines the tag that corresponds to the current scheduling type. + * + * @returns The corresponding tag for the scheduling type. + */ tag(): TransactionSchedulingTag { if (this.standard) return TransactionSchedulingTag.Native; if (this.futureEra) return TransactionSchedulingTag.FutureEra; @@ -66,6 +118,11 @@ export class TransactionScheduling { return 0; } + /** + * Serializes the transaction scheduling into a byte array representation. + * + * @returns A `Uint8Array` representing the transaction scheduling. + */ bytes(): Uint8Array { const tagBytes = Uint8Array.of(this.tag()); @@ -82,6 +139,13 @@ export class TransactionScheduling { return tagBytes; } + /** + * Creates a `TransactionScheduling` instance from a JSON object. + * + * @param json The JSON object to deserialize into a `TransactionScheduling` instance. + * @returns The deserialized `TransactionScheduling` object. + * @throws Error if the JSON format is invalid. + */ static fromJSON(json: any): TransactionScheduling { if (json === 'Standard') { return new TransactionScheduling({}); @@ -104,6 +168,12 @@ export class TransactionScheduling { throw new Error('Invalid JSON format for TransactionScheduling'); } + /** + * Converts the transaction scheduling into a JSON-compatible format. + * + * @returns The JSON representation of the transaction scheduling. + * @throws Error if the scheduling type is unknown. + */ toJSON(): unknown { if (this.standard) { return 'Standard'; diff --git a/src/types/TransactionTarget.ts b/src/types/TransactionTarget.ts index cb6899852..d0d62b707 100644 --- a/src/types/TransactionTarget.ts +++ b/src/types/TransactionTarget.ts @@ -7,21 +7,40 @@ import { Hash } from './key'; import { CLValueString } from './clvalue'; import { ExecutableDeployItem } from './ExecutableDeployItem'; +/** + * Enum representing different types of transaction targets. + */ enum TransactionTargetType { + /** Native target type, used for transactions without a specific target. */ Native = 0, + /** Stored target type, used for contracts or stored items. */ Stored = 1, + /** Session target type, used for session-based transactions. */ Session = 2 } +/** + * Enum representing different invocation target tags for identifying transaction target types. + */ enum InvocationTargetTag { + /** Invocation target by hash. */ ByHash = 0, + /** Invocation target by name. */ ByName = 1, + /** Invocation target by package hash. */ ByPackageHash = 2, + /** Invocation target by package name. */ ByPackageName = 3 } +/** + * Represents the invocation target for a transaction identified by a package hash. + */ @jsonObject export class ByPackageHashInvocationTarget { + /** + * The address of the package in the form of a hash. + */ @jsonMember({ name: 'addr', constructor: Hash, @@ -30,21 +49,43 @@ export class ByPackageHashInvocationTarget { }) addr: Hash; + /** + * The version of the package, if specified. + */ @jsonMember({ name: 'version', isRequired: false, constructor: Number }) version?: number; } +/** + * Represents the invocation target for a transaction identified by a package name. + */ @jsonObject export class ByPackageNameInvocationTarget { + /** + * The name of the package. + */ @jsonMember({ name: 'name', constructor: String }) name: string; + /** + * The version of the package, if specified. + */ @jsonMember({ name: 'version', isRequired: false, constructor: Number }) version?: number; } +/** + * Represents a transaction invocation target, which can be one of the following: + * - By hash + * - By name + * - By package hash + * - By package name + */ @jsonObject export class TransactionInvocationTarget { + /** + * Invocation target by hash, if specified. + */ @jsonMember({ name: 'ByHash', isRequired: false, @@ -60,9 +101,15 @@ export class TransactionInvocationTarget { }) byHash?: Hash; + /** + * Invocation target by name, if specified. + */ @jsonMember({ name: 'ByName', isRequired: false, constructor: String }) byName?: string; + /** + * Invocation target by package hash, if specified. + */ @jsonMember({ name: 'ByPackageHash', isRequired: false, @@ -70,6 +117,9 @@ export class TransactionInvocationTarget { }) byPackageHash?: ByPackageHashInvocationTarget; + /** + * Invocation target by package name, if specified. + */ @jsonMember({ name: 'ByPackageName', isRequired: false, @@ -78,51 +128,108 @@ export class TransactionInvocationTarget { byPackageName?: ByPackageNameInvocationTarget; } +/** + * Represents a stored target, which includes both the invocation target and runtime. + */ @jsonObject export class StoredTarget { + /** + * The invocation target for the stored transaction. + */ @jsonMember({ name: 'id', constructor: TransactionInvocationTarget }) id: TransactionInvocationTarget; + /** + * The runtime associated with the stored transaction. + */ @jsonMember({ name: 'runtime', constructor: String }) runtime: TransactionRuntime; } +/** + * Represents a session target, which includes both the module bytes and runtime. + */ @jsonObject export class SessionTarget { + /** + * The module bytes associated with the session target. + */ @jsonMember({ name: 'module_bytes', constructor: String }) moduleBytes: string; + /** + * The runtime associated with the session target. + */ @jsonMember({ name: 'runtime', constructor: String }) runtime: TransactionRuntime; } +/** + * Represents a transaction target, which could be one of the following types: + * - Native (no specific target) + * - Stored (contract or stored item target) + * - Session (session-based target) + */ @jsonObject export class TransactionTarget { + /** + * Native transaction target, representing a transaction with no specific target. + */ @jsonMember({ constructor: Object }) native?: object; + /** + * Stored transaction target, representing a transaction that targets a stored contract or item. + */ @jsonMember({ name: 'Stored', constructor: StoredTarget }) stored?: StoredTarget; + /** + * Session transaction target, representing a session-based transaction. + */ @jsonMember({ name: 'Session', constructor: SessionTarget }) session?: SessionTarget; + /** + * Constructs a `TransactionTarget` instance with the specified values for native, stored, or session targets. + * + * @param native The native transaction target, if applicable. + * @param stored The stored transaction target, if applicable. + * @param session The session transaction target, if applicable. + */ constructor(native?: object, stored?: StoredTarget, session?: SessionTarget) { this.native = native; this.stored = stored; this.session = session; } + /** + * Converts a 32-bit unsigned integer to a byte array. + * + * @param value The 32-bit unsigned integer to convert. + * @returns A `Uint8Array` representing the value. + */ private uint32ToBytes(value: number): Uint8Array { const buffer = new ArrayBuffer(4); new DataView(buffer).setUint32(0, value, true); return new Uint8Array(buffer); } + /** + * Converts a hexadecimal string to a byte array. + * + * @param hexString The hexadecimal string to convert. + * @returns A `Uint8Array` representing the hexadecimal string. + */ private hexStringToBytes(hexString: string): Uint8Array { return Uint8Array.from(Buffer.from(hexString, 'hex')); } + /** + * Serializes the `TransactionTarget` into a byte array. + * + * @returns A `Uint8Array` representing the serialized transaction target. + */ toBytes(): Uint8Array { let result: Uint8Array = new Uint8Array(); @@ -197,6 +304,13 @@ export class TransactionTarget { return result; } + /** + * Deserializes a `TransactionTarget` from a JSON object. + * + * @param json The JSON object to deserialize. + * @returns A `TransactionTarget` instance. + * @throws Error if the JSON object format is invalid. + */ static fromJSON(json: any): TransactionTarget { const target = new TransactionTarget(); @@ -237,6 +351,12 @@ export class TransactionTarget { return target; } + /** + * Converts the `TransactionTarget` into a JSON-compatible format. + * + * @returns The JSON representation of the `TransactionTarget`. + * @throws Error if the target type is unknown. + */ toJSON(): any { if (this.native !== undefined) { return 'Native'; @@ -259,6 +379,12 @@ export class TransactionTarget { } } + /** + * Creates a new `TransactionTarget` from a session-based transaction. + * + * @param session The `ExecutableDeployItem` that defines the session-based transaction. + * @returns A new `TransactionTarget` instance derived from the session. + */ public static newTransactionTargetFromSession( session: ExecutableDeployItem ): TransactionTarget { diff --git a/src/types/Transfer.ts b/src/types/Transfer.ts index 881bf4ac1..fcee32db3 100644 --- a/src/types/Transfer.ts +++ b/src/types/Transfer.ts @@ -4,8 +4,14 @@ import { InitiatorAddr } from './InitiatorAddr'; import { AccountHash, Hash, URef } from './key'; import { CLValueUInt512 } from './clvalue'; +/** + * Represents the details of a version 1 (V1) transfer transaction. + */ @jsonObject export class TransferV1 { + /** + * The amount being transferred in a version 1 transaction. + */ @jsonMember({ constructor: CLValueUInt512, deserializer: json => CLValueUInt512.fromJSON(json), @@ -13,6 +19,9 @@ export class TransferV1 { }) public amount: CLValueUInt512; + /** + * The deploy hash associated with the transfer. + */ @jsonMember({ name: 'deploy_hash', constructor: Hash, @@ -21,6 +30,9 @@ export class TransferV1 { }) public deployHash: Hash; + /** + * The account hash representing the sender of the transfer. + */ @jsonMember({ constructor: AccountHash, deserializer: json => AccountHash.fromJSON(json), @@ -28,12 +40,21 @@ export class TransferV1 { }) public from: AccountHash; + /** + * The gas used for the transfer. + */ @jsonMember({ constructor: Number }) public gas: number; + /** + * The optional ID of the transfer. + */ @jsonMember({ constructor: Number }) public id?: number; + /** + * The source URef (Universal Reference) of the transfer. + */ @jsonMember({ constructor: URef, deserializer: json => URef.fromJSON(json), @@ -41,6 +62,9 @@ export class TransferV1 { }) public source: URef; + /** + * The target URef (Universal Reference) of the transfer. + */ @jsonMember({ constructor: URef, deserializer: json => URef.fromJSON(json), @@ -48,24 +72,31 @@ export class TransferV1 { }) public target: URef; + /** + * The optional account hash representing the recipient of the transfer. + */ @jsonMember({ constructor: AccountHash, deserializer: json => { if (!json) return; - return AccountHash.fromJSON(json); }, serializer: value => { if (!value) return; - return value.toJSON(); } }) public to?: AccountHash; } +/** + * Represents the details of a version 2 (V2) transfer transaction. + */ @jsonObject export class TransferV2 { + /** + * The amount being transferred in a version 2 transaction. + */ @jsonMember({ constructor: CLValueUInt512, deserializer: json => CLValueUInt512.fromJSON(json), @@ -73,9 +104,15 @@ export class TransferV2 { }) public amount: CLValueUInt512; + /** + * The transaction hash associated with the transfer. + */ @jsonMember({ name: 'transaction_hash', constructor: TransactionHash }) public transactionHash: TransactionHash; + /** + * The initiator address of the transfer, containing details about the sender. + */ @jsonMember({ constructor: InitiatorAddr, deserializer: json => InitiatorAddr.fromJSON(json), @@ -83,12 +120,21 @@ export class TransferV2 { }) public from: InitiatorAddr; + /** + * The gas used for the transfer. + */ @jsonMember({ constructor: Number }) public gas: number; + /** + * The optional ID of the transfer. + */ @jsonMember({ constructor: Number }) public id?: number; + /** + * The source URef (Universal Reference) of the transfer. + */ @jsonMember({ constructor: URef, deserializer: json => URef.fromJSON(json), @@ -96,6 +142,9 @@ export class TransferV2 { }) public source: URef; + /** + * The target URef (Universal Reference) of the transfer. + */ @jsonMember({ constructor: URef, deserializer: json => URef.fromJSON(json), @@ -103,6 +152,9 @@ export class TransferV2 { }) public target: URef; + /** + * The optional account hash representing the recipient of the transfer. + */ @jsonMember({ constructor: AccountHash, deserializer: json => { @@ -117,17 +169,32 @@ export class TransferV2 { public to?: AccountHash; } +/** + * Represents a versioned transfer transaction, which can be either version 1 (V1) or version 2 (V2). + */ @jsonObject class TransferVersioned { + /** + * The version 1 transfer details, if applicable. + */ @jsonMember({ name: 'Version1', constructor: TransferV1 }) public Version1?: TransferV1; + /** + * The version 2 transfer details, if applicable. + */ @jsonMember({ name: 'Version2', constructor: TransferV2 }) public Version2?: TransferV2; } +/** + * Represents a transfer transaction, which can be either version 1 (V1) or version 2 (V2). + */ @jsonObject export class Transfer { + /** + * The amount being transferred in the transaction. + */ @jsonMember({ constructor: CLValueUInt512, deserializer: json => CLValueUInt512.fromJSON(json), @@ -135,9 +202,15 @@ export class Transfer { }) public amount: CLValueUInt512; + /** + * The transaction hash associated with the transfer. + */ @jsonMember({ name: 'transaction_hash', constructor: TransactionHash }) public transactionHash: TransactionHash; + /** + * The initiator address of the transfer, containing details about the sender. + */ @jsonMember({ constructor: InitiatorAddr, deserializer: json => InitiatorAddr.fromJSON(json), @@ -145,12 +218,21 @@ export class Transfer { }) public from: InitiatorAddr; + /** + * The gas used for the transfer. + */ @jsonMember({ constructor: Number }) public gas: number; + /** + * The optional ID of the transfer. + */ @jsonMember({ constructor: Number }) public id?: number; + /** + * The source URef (Universal Reference) of the transfer. + */ @jsonMember({ constructor: URef, deserializer: json => URef.fromJSON(json), @@ -158,6 +240,9 @@ export class Transfer { }) public source: URef; + /** + * The target URef (Universal Reference) of the transfer. + */ @jsonMember({ constructor: URef, deserializer: json => URef.fromJSON(json), @@ -165,6 +250,9 @@ export class Transfer { }) public target: URef; + /** + * The optional account hash representing the recipient of the transfer. + */ @jsonMember({ constructor: AccountHash, deserializer: json => { @@ -173,7 +261,6 @@ export class Transfer { }, serializer: (value: AccountHash) => { if (!value) return; - return value.toJSON(); } }) @@ -182,14 +269,32 @@ export class Transfer { private originTransferV1?: TransferV1; private originTransferV2?: TransferV2; + /** + * Gets the version 1 transfer details if available. + * + * @returns The version 1 transfer details, or `undefined` if not present. + */ public getTransferV1(): TransferV1 | undefined { return this.originTransferV1; } + /** + * Gets the version 2 transfer details if available. + * + * @returns The version 2 transfer details, or `undefined` if not present. + */ public getTransferV2(): TransferV2 | undefined { return this.originTransferV2; } + /** + * Deserializes a `Transfer` instance from JSON. + * It can handle both version 1 and version 2 transfer formats. + * + * @param data The JSON data representing the transfer. + * @returns A `Transfer` instance. + * @throws Error if the transfer format is invalid or unrecognized. + */ public static fromJSON(data: any): Transfer { const versioned = TypedJSON.parse(data, TransferVersioned); @@ -220,6 +325,12 @@ export class Transfer { throw new Error('Incorrect RPC response structure'); } + /** + * Creates a `Transfer` instance from version 1 transfer data. + * + * @param transferV1 The version 1 transfer details. + * @returns A `Transfer` instance created from the version 1 data. + */ private static fromTransferV1(transferV1: TransferV1): Transfer { const transfer = new Transfer(); transfer.amount = transferV1.amount; diff --git a/src/types/Transform.ts b/src/types/Transform.ts index 2ecbe2a8c..f47e10bd6 100644 --- a/src/types/Transform.ts +++ b/src/types/Transform.ts @@ -1,6 +1,5 @@ import { jsonObject, jsonMember, TypedJSON } from 'typedjson'; import { AccountHash, Key, Hash, URef } from './key'; - import { UnbondingPurse } from './UnbondingPurse'; import { AddressableEntity } from './AddressableEntity'; import { Package } from './Package'; @@ -11,8 +10,15 @@ import { CLValueUInt512 } from './clvalue'; import { Args } from './Args'; import { deserializeArgs, serializeArgs } from './SerializationUtils'; +/** + * Represents raw write data for a CLValue. + * Used for serializing and deserializing the arguments of a CLValue write operation. + */ @jsonObject export class RawWriteCLValue { + /** + * The write operation on a CLValue represented as `Args`. + */ @jsonMember({ constructor: Args, name: 'WriteCLValue', @@ -28,8 +34,14 @@ export class RawWriteCLValue { writeCLValue?: Args; } +/** + * Represents a write operation in a transaction. + */ @jsonObject class Write { + /** + * The CLValue write operation represented as `Args`. + */ @jsonMember({ constructor: Args, name: 'CLValue', @@ -45,88 +57,194 @@ class Write { clValue?: Args; } +/** + * Represents raw write data for version 2 of a CLValue. + */ @jsonObject export class RawWriteCLValueV2 { + /** + * The write operation represented as `Write`. + */ @jsonMember({ name: 'Write', constructor: Write }) write?: Write; } +/** + * Represents different types of transformation that can be applied. + * Used for parsing and processing transformation data in a transaction. + */ @jsonObject export class TransformKind { private data: string; + /** + * Constructs a new `TransformKind` instance. + * + * @param data The transformation data as a string. + */ constructor(data = '') { this.data = data; } + /** + * Creates a `TransformKind` instance from a JSON string. + * + * @param data The transformation data as a string. + * @returns The `TransformKind` instance. + */ public static fromJSON(data: string): TransformKind { return new TransformKind(data); } + /** + * Converts the transformation data into a JSON string. + * + * @returns The transformation data as a string. + */ public toJSON(): string { return this.data || 'null'; } + /** + * Checks if the transformation is a WriteTransfer. + * + * @returns `true` if the transformation is a WriteTransfer, otherwise `false`. + */ public isWriteTransfer(): boolean { return this.data.includes('WriteTransfer'); } + /** + * Checks if the transformation is a WriteAccount. + * + * @returns `true` if the transformation is a WriteAccount, otherwise `false`. + */ public isWriteAccount(): boolean { return this.data.includes('WriteAccount'); } + /** + * Checks if the transformation is a WriteContract. + * + * @returns `true` if the transformation is a WriteContract, otherwise `false`. + */ public isWriteContract(): boolean { return this.data === '"WriteContract"'; } + /** + * Checks if the transformation is a WriteWithdraw. + * + * @returns `true` if the transformation is a WriteWithdraw, otherwise `false`. + */ public isWriteWithdraw(): boolean { return this.data.includes('WriteWithdraw'); } + /** + * Checks if the transformation is a WriteUnbonding. + * + * @returns `true` if the transformation is a WriteUnbonding, otherwise `false`. + */ public isWriteUnbonding(): boolean { return this.data.includes('WriteUnbonding'); } + /** + * Checks if the transformation is a WriteCLValue. + * + * @returns `true` if the transformation is a WriteCLValue, otherwise `false`. + */ public isWriteCLValue(): boolean { return this.data.includes('CLValue'); } + /** + * Checks if the transformation is a WritePackage. + * + * @returns `true` if the transformation is a WritePackage, otherwise `false`. + */ public isWritePackage(): boolean { return this.data.includes('"Package"'); } + /** + * Checks if the transformation is a WriteAddressableEntity. + * + * @returns `true` if the transformation is a WriteAddressableEntity, otherwise `false`. + */ public isWriteAddressableEntity(): boolean { return this.data.includes('"AddressableEntity"'); } + /** + * Checks if the transformation is a WriteBidKind. + * + * @returns `true` if the transformation is a WriteBidKind, otherwise `false`. + */ public isWriteBidKind(): boolean { return this.data.includes('"BidKind"'); } + /** + * Checks if the transformation is a WriteNamedKey. + * + * @returns `true` if the transformation is a WriteNamedKey, otherwise `false`. + */ public isWriteNamedKey(): boolean { return this.data.includes('"NamedKey"'); } + /** + * Checks if the transformation is a WriteMessage. + * + * @returns `true` if the transformation is a WriteMessage, otherwise `false`. + */ public isWriteMessage(): boolean { return this.data.includes('"Message"'); } + /** + * Checks if the transformation is a WriteMessageTopic. + * + * @returns `true` if the transformation is a WriteMessageTopic, otherwise `false`. + */ public isWriteMessageTopic(): boolean { return this.data.includes('"MessageTopic"'); } + /** + * Checks if the transformation is a WriteBid. + * + * @returns `true` if the transformation is a WriteBid, otherwise `false`. + */ public isWriteBid(): boolean { return this.data.includes('WriteBid'); } + /** + * Checks if the transformation is an AddUInt512. + * + * @returns `true` if the transformation is AddUInt512, otherwise `false`. + */ public isAddUint512(): boolean { return this.data.includes('AddUInt512'); } + /** + * Checks if the transformation is a WriteDeployInfo. + * + * @returns `true` if the transformation is a WriteDeployInfo, otherwise `false`. + */ public isWriteDeployInfo(): boolean { return this.data.includes('WriteDeployInfo'); } + /** + * Attempts to parse the transformation as a WriteTransfer. + * + * @returns A `WriteTransfer` object if the data matches, otherwise `null`. + */ parseAsWriteTransfer(): WriteTransfer | null { try { const jsonObject = JSON.parse(this.data); @@ -143,6 +261,11 @@ export class TransformKind { return null; } + /** + * Attempts to parse the transformation as a WriteWithdraw. + * + * @returns An array of `UnbondingPurse` objects if the data matches, otherwise `null`. + */ public parseAsWriteWithdraws(): UnbondingPurse[] | null { try { const jsonObject = JSON.parse(this.data); @@ -158,6 +281,11 @@ export class TransformKind { return null; } + /** + * Attempts to parse the transformation as a WriteAddressableEntity. + * + * @returns An `AddressableEntity` object if the data matches, otherwise `null`. + */ public parseAsWriteAddressableEntity(): AddressableEntity | null { try { const jsonObject = JSON.parse(this.data); @@ -174,6 +302,11 @@ export class TransformKind { return null; } + /** + * Attempts to parse the transformation as a WritePackage. + * + * @returns A `Package` object if the data matches, otherwise `null`. + */ public parseAsWritePackage(): Package | null { try { const jsonObject = JSON.parse(this.data); @@ -187,6 +320,11 @@ export class TransformKind { return null; } + /** + * Attempts to parse the transformation as a WriteBidKind. + * + * @returns A `BidKind` object if the data matches, otherwise `null`. + */ public parseAsWriteBidKind(): BidKind | null { try { const jsonObject = JSON.parse(this.data); @@ -200,6 +338,11 @@ export class TransformKind { return null; } + /** + * Attempts to parse the transformation as a WriteNamedKey. + * + * @returns A `NamedKeyKind` object if the data matches, otherwise `null`. + */ public parseAsWriteNamedKey(): NamedKeyKind | null { try { const jsonObject = JSON.parse(this.data); @@ -213,6 +356,11 @@ export class TransformKind { return null; } + /** + * Attempts to parse the transformation as a WriteMessage. + * + * @returns A `MessageChecksum` if the data matches, otherwise `null`. + */ public parseAsWriteMessage(): MessageChecksum | null { try { const jsonObject = JSON.parse(this.data); @@ -226,6 +374,11 @@ export class TransformKind { return null; } + /** + * Attempts to parse the transformation as a WriteMessageTopic. + * + * @returns A `MessageTopicSummary` if the data matches, otherwise `null`. + */ public parseAsWriteMessageTopic(): MessageTopicSummary | null { try { const jsonObject = JSON.parse(this.data); @@ -242,6 +395,11 @@ export class TransformKind { return null; } + /** + * Attempts to parse the transformation as a WriteUnbonding. + * + * @returns An array of `UnbondingPurse` objects if the data matches, otherwise `null`. + */ public parseAsWriteUnbondings(): UnbondingPurse[] | null { try { const jsonObject = JSON.parse(this.data); @@ -257,6 +415,11 @@ export class TransformKind { return null; } + /** + * Attempts to parse the transformation as a UInt512. + * + * @returns A `CLValueUInt512` object if the data matches, otherwise `null`. + */ public parseAsUInt512(): CLValueUInt512 | null { try { const jsonObject = JSON.parse(this.data); @@ -270,6 +433,11 @@ export class TransformKind { return null; } + /** + * Attempts to parse the transformation as a WriteDeployInfo. + * + * @returns A `DeployInfo` object if the data matches, otherwise `null`. + */ public parseAsWriteDeployInfo(): DeployInfo | null { try { const jsonObject = JSON.parse(this.data); @@ -283,6 +451,11 @@ export class TransformKind { return null; } + /** + * Attempts to parse the transformation as a WriteCLValue. + * + * @returns The `Args` object if the data matches, otherwise `null`. + */ public parseAsWriteCLValue(): Args | null { try { const parser = new TypedJSON(RawWriteCLValue); @@ -305,8 +478,14 @@ export class TransformKind { } } +/** + * Represents a transformation, which includes a key and a transformation kind. + */ @jsonObject export class Transform { + /** + * The key associated with the transformation. + */ @jsonMember({ name: 'key', constructor: Key, @@ -315,17 +494,32 @@ export class Transform { }) public key: Key; + /** + * The kind of transformation being applied. + */ @jsonMember({ name: 'kind', constructor: TransformKind }) public kind: TransformKind; + /** + * Constructs a new `Transform` instance. + * + * @param key The key associated with the transformation. + * @param kind The kind of transformation. + */ constructor(key: Key, kind: TransformKind) { this.key = key; this.kind = kind; } } +/** + * Represents a key transformation in a transaction. + */ @jsonObject export class TransformKey { + /** + * The key associated with the transformation. + */ @jsonMember({ name: 'key', constructor: Key, @@ -334,12 +528,21 @@ export class TransformKey { }) public key: Key; + /** + * The transformation kind. + */ @jsonMember({ name: 'transform', constructor: TransformKind }) public transform: TransformKind; } +/** + * Represents a named key transformation in a transaction. + */ @jsonObject export class NamedKeyKind { + /** + * The named key transformation data represented as `Args`. + */ @jsonMember({ constructor: Args, name: 'named_key', @@ -348,6 +551,9 @@ export class NamedKeyKind { }) public namedKey: Args; + /** + * The name of the key represented as `Args`. + */ @jsonMember({ constructor: Args, name: 'name', @@ -357,11 +563,20 @@ export class NamedKeyKind { public name: Args; } +/** + * Represents a transfer operation in a transaction. + */ @jsonObject export class WriteTransfer { + /** + * The optional ID of the transfer. + */ @jsonMember({ name: 'id', constructor: Number }) public id?: number; + /** + * The recipient of the transfer, represented as an `AccountHash`. + */ @jsonMember({ name: 'to', constructor: AccountHash, @@ -376,9 +591,15 @@ export class WriteTransfer { }) public to?: AccountHash; + /** + * The deploy hash associated with the transfer. + */ @jsonMember({ name: 'deploy_hash', constructor: Hash }) public deployHash: Hash; + /** + * The sender of the transfer, represented as an `AccountHash`. + */ @jsonMember({ name: 'from', constructor: AccountHash, @@ -387,6 +608,9 @@ export class WriteTransfer { }) public from: AccountHash; + /** + * The amount being transferred, represented as a `CLValueUInt512`. + */ @jsonMember({ name: 'amount', constructor: CLValueUInt512, @@ -395,6 +619,9 @@ export class WriteTransfer { }) public amount: CLValueUInt512; + /** + * The source URef (Universal Reference) of the transfer. + */ @jsonMember({ name: 'source', constructor: URef, @@ -403,6 +630,9 @@ export class WriteTransfer { }) public source: URef; + /** + * The target URef (Universal Reference) of the transfer. + */ @jsonMember({ name: 'target', constructor: URef, @@ -411,6 +641,9 @@ export class WriteTransfer { }) public target: URef; + /** + * The gas used for the transfer. + */ @jsonMember({ name: 'gas', constructor: Number }) public gas: number; } diff --git a/src/types/UnbondingPurse.ts b/src/types/UnbondingPurse.ts index ef4c1858c..c5d07e6b6 100644 --- a/src/types/UnbondingPurse.ts +++ b/src/types/UnbondingPurse.ts @@ -3,8 +3,14 @@ import { URef } from './key'; import { PublicKey } from './keypair'; import { CLValueUInt512 } from './clvalue'; +/** + * Represents an unbonding purse, which contains information about the unbonding process of a bonded amount. + */ @jsonObject export class UnbondingPurse { + /** + * The amount being unbonded, represented as `CLValueUInt512`. + */ @jsonMember({ name: 'amount', constructor: CLValueUInt512, @@ -13,6 +19,9 @@ export class UnbondingPurse { }) amount: CLValueUInt512; + /** + * The bonding purse from which the unbonding is taking place, represented as a `URef`. + */ @jsonMember({ name: 'bonding_purse', constructor: URef, @@ -21,9 +30,15 @@ export class UnbondingPurse { }) bondingPurse: URef; + /** + * The era when the unbonding purse was created. + */ @jsonMember({ name: 'era_of_creation', constructor: Number }) eraOfCreation: number; + /** + * The public key of the unbonder, representing the individual initiating the unbonding process. + */ @jsonMember({ name: 'unbonder_public_key', constructor: PublicKey, @@ -32,6 +47,9 @@ export class UnbondingPurse { }) unbonderPublicKey: PublicKey; + /** + * The public key of the validator associated with the unbonding. + */ @jsonMember({ name: 'validator_public_key', constructor: PublicKey, @@ -40,6 +58,9 @@ export class UnbondingPurse { }) validatorPublicKey: PublicKey; + /** + * The public key of a new validator, if applicable. This may be used for transferring the bonded amount to a new validator. + */ @jsonMember({ name: 'new_validator', constructor: PublicKey, diff --git a/src/types/ValidatorWeight.ts b/src/types/ValidatorWeight.ts index e3b1d62cb..1f14c9ad5 100644 --- a/src/types/ValidatorWeight.ts +++ b/src/types/ValidatorWeight.ts @@ -2,8 +2,14 @@ import { jsonObject, jsonMember } from 'typedjson'; import { PublicKey } from './keypair'; import { CLValueUInt512 } from './clvalue'; +/** + * Represents the weight of a validator at the end of an era. + */ @jsonObject export class ValidatorWeightEraEnd { + /** + * The public key of the validator whose weight is being recorded. + */ @jsonMember({ constructor: PublicKey, deserializer: json => PublicKey.fromJSON(json), @@ -11,6 +17,9 @@ export class ValidatorWeightEraEnd { }) validator: PublicKey; + /** + * The weight of the validator at the end of the era, represented as `CLValueUInt512`. + */ @jsonMember({ constructor: CLValueUInt512, deserializer: json => CLValueUInt512.fromJSON(json), @@ -19,8 +28,14 @@ export class ValidatorWeightEraEnd { weight: CLValueUInt512; } +/** + * Represents the weight of a validator in the auction. + */ @jsonObject export class ValidatorWeightAuction { + /** + * The public key of the validator whose weight is being recorded in the auction. + */ @jsonMember({ name: 'public_key', constructor: PublicKey, @@ -29,6 +44,9 @@ export class ValidatorWeightAuction { }) validator: PublicKey; + /** + * The weight of the validator in the auction, represented as `CLValueUInt512`. + */ @jsonMember({ constructor: CLValueUInt512, deserializer: json => CLValueUInt512.fromJSON(json), diff --git a/src/types/clvalue/Any.ts b/src/types/clvalue/Any.ts index 59bc469cb..1676914d6 100644 --- a/src/types/clvalue/Any.ts +++ b/src/types/clvalue/Any.ts @@ -2,14 +2,14 @@ import { CLTypeAny } from './cltype'; import { CLValue } from './CLValue'; /** - * Represents an 'Any' value in the CasperLabs type system. - * This type can hold any arbitrary data as a byte array. + * Represents an 'Any' value in the Casper type system. + * This type can store any arbitrary data as a byte array, making it highly flexible. */ export class CLValueAny { private data: Uint8Array; /** - * Constructs a new CLValueAny instance. + * Initializes a new instance of the CLValueAny class. * @param data - The Uint8Array to be stored as the 'Any' value. */ constructor(data: Uint8Array) { @@ -17,7 +17,7 @@ export class CLValueAny { } /** - * Returns the byte representation of the 'Any' value. + * Retrieves the byte representation of the 'Any' value. * @returns A Uint8Array representing the stored data. */ public bytes(): Uint8Array { @@ -25,17 +25,18 @@ export class CLValueAny { } /** - * Returns a string representation of the 'Any' value. - * @returns A string decoded from the stored byte array using UTF-8 encoding. + * Provides a string representation of the 'Any' value. + * The byte array is decoded as a UTF-8 string. + * @returns A string decoded from the stored byte array. */ public toString(): string { return new TextDecoder().decode(this.data); } /** - * Creates a new CLValue instance with an 'Any' value. - * @param data - The Uint8Array to be stored in the CLValue. - * @returns A new CLValue instance containing the 'Any' value. + * Creates a new CLValue instance containing an 'Any' value. + * @param data - The Uint8Array to be stored within the CLValue. + * @returns A new CLValue instance encapsulating the 'Any' value. */ public static newCLAny(data: Uint8Array): CLValue { const res = new CLValue(CLTypeAny); diff --git a/src/types/clvalue/Bool.ts b/src/types/clvalue/Bool.ts index ae4c94241..da03a5f86 100644 --- a/src/types/clvalue/Bool.ts +++ b/src/types/clvalue/Bool.ts @@ -2,13 +2,14 @@ import { CLTypeBool } from './cltype'; import { CLValue, IResultWithBytes } from './CLValue'; /** - * Represents a boolean value in the CasperLabs type system. + * Represents a boolean value in the Casper type system. + * This class encapsulates a boolean value and provides methods for byte conversion and CLValue integration. */ export class CLValueBool { private value: boolean; /** - * Constructs a new CLValueBool instance. + * Initializes a new instance of the CLValueBool class. * @param value - The boolean value to be stored. */ constructor(value: boolean) { @@ -16,7 +17,7 @@ export class CLValueBool { } /** - * Returns the byte representation of the boolean value. + * Converts the boolean value to its byte representation. * @returns A Uint8Array with a single byte: 1 for true, 0 for false. */ public bytes(): Uint8Array { @@ -24,7 +25,7 @@ export class CLValueBool { } /** - * Returns a string representation of the boolean value. + * Provides a string representation of the boolean value. * @returns The string 'true' or 'false'. */ public toString(): string { @@ -32,7 +33,7 @@ export class CLValueBool { } /** - * Returns the boolean value. + * Retrieves the boolean value. * @returns The stored boolean value. */ public getValue(): boolean { @@ -40,9 +41,9 @@ export class CLValueBool { } /** - * Creates a new CLValue instance with a boolean value. + * Creates a new CLValue instance containing a boolean value. * @param val - The boolean value to be stored in the CLValue. - * @returns A new CLValue instance containing the boolean value. + * @returns A new CLValue instance encapsulating the boolean value. */ public static fromBoolean(val: boolean): CLValue { const res = new CLValue(CLTypeBool); @@ -52,9 +53,10 @@ export class CLValueBool { /** * Creates a CLValueBool instance from a Uint8Array. + * Parses the first byte in the array to determine the boolean value. * @param source - The Uint8Array containing the byte representation of the boolean value. - * @returns A new CLValueBool instance. - * @throws Will throw an error if the source array is empty. + * @returns An object containing the new CLValueBool instance and any remaining bytes. + * @throws Will throw an error if the source array is empty or contains an invalid boolean byte. */ public static fromBytes(source: Uint8Array): IResultWithBytes { if (source.length === 0) { diff --git a/src/types/clvalue/ByteArray.ts b/src/types/clvalue/ByteArray.ts index c04de345b..b0731e107 100644 --- a/src/types/clvalue/ByteArray.ts +++ b/src/types/clvalue/ByteArray.ts @@ -2,13 +2,14 @@ import { CLTypeByteArray } from './cltype'; import { CLValue, IResultWithBytes } from './CLValue'; /** - * Represents a byte array value in the CasperLabs type system. + * Represents a byte array value in the Casper type system. + * This class encapsulates a byte array, providing methods for conversion to and from CLValue. */ export class CLValueByteArray { private data: Uint8Array; /** - * Constructs a new CLValueByteArray instance. + * Initializes a new instance of the CLValueByteArray class. * @param data - The Uint8Array to be stored in the CLValueByteArray. */ constructor(data: Uint8Array) { @@ -16,7 +17,7 @@ export class CLValueByteArray { } /** - * Returns the byte representation of the byte array. + * Retrieves the byte representation of the byte array. * @returns A Uint8Array representing the bytes of the byte array. */ public bytes(): Uint8Array { @@ -24,7 +25,8 @@ export class CLValueByteArray { } /** - * Returns a hexadecimal string representation of the byte array. + * Provides a hexadecimal string representation of the byte array. + * Each byte is represented by two hexadecimal digits. * @returns A string representing the byte array in hexadecimal format. */ public toString(): string { @@ -34,9 +36,9 @@ export class CLValueByteArray { } /** - * Creates a new CLValue instance with a ByteArray value. - * @param val - The Uint8Array to be stored in the CLValue. - * @returns A new CLValue instance containing the ByteArray. + * Creates a new CLValue instance containing a ByteArray value. + * @param val - The Uint8Array to be stored within the CLValue. + * @returns A new CLValue instance encapsulating the ByteArray. */ public static newCLByteArray(val: Uint8Array): CLValue { const byteArrayType = new CLTypeByteArray(val.length); @@ -48,9 +50,10 @@ export class CLValueByteArray { /** * Creates a CLValueByteArray instance from a Uint8Array. + * Extracts the bytes specified by the given CLTypeByteArray size. * @param data - The Uint8Array containing the byte representation of the ByteArray value. - * @param clType - The CLTypeByteArray representing the type of the ByteArray. - * @returns A new CLValueByteArray instance. + * @param clType - The CLTypeByteArray defining the size of the ByteArray. + * @returns An object containing the new CLValueByteArray instance and any remaining bytes. */ public static fromBytes( data: Uint8Array, diff --git a/src/types/clvalue/CLValue.ts b/src/types/clvalue/CLValue.ts index 6edcca6aa..4f2e745f8 100644 --- a/src/types/clvalue/CLValue.ts +++ b/src/types/clvalue/CLValue.ts @@ -30,7 +30,7 @@ import { CLValueTuple3 } from './Tuple3'; import { CLValueAny } from './Any'; /** - * Interface representing a value that can be converted to bytes and string. + * Interface representing a value that can be converted to bytes and a string. */ interface IValue { bytes(): Uint8Array; @@ -43,7 +43,7 @@ export interface IResultWithBytes { } /** - * Represents a CLValue in the CasperLabs type system. + * Represents a CLValue in the Casper type system. * CLValue is a container for various types of values used in smart contracts. */ export class CLValue { @@ -73,7 +73,7 @@ export class CLValue { public publicKey?: PublicKey; /** - * Constructs a new CLValue instance. + * Initializes a new CLValue instance. * @param type - The CLType of the value. */ constructor(type: CLType) { @@ -81,14 +81,11 @@ export class CLValue { } /** - * Gets the actual type of the CLValue. - * @returns The CLType of the value, resolving CLTypeDynamic if necessary. + * Gets the actual type of the CLValue, resolving dynamic types if necessary. + * @returns The CLType of the value. */ public getType(): CLType { - if (this.type instanceof CLTypeDynamic) { - return this.type.inner; - } - return this.type; + return this.type instanceof CLTypeDynamic ? this.type.inner : this.type; } /** @@ -108,7 +105,7 @@ export class CLValue { } /** - * Gets the appropriate value based on the CLValue's type. + * Retrieves the value associated with the CLValue's type. * @returns An IValue representing the actual value stored in the CLValue. * @throws Error if the type is not implemented. */ @@ -168,7 +165,7 @@ export class CLValue { } /** - * Gets the Key value from the CLValue. + * Retrieves the Key value from the CLValue. * @returns The Key stored in the CLValue. * @throws Error if the Key property is empty. */ @@ -182,9 +179,9 @@ export class CLValue { } /** - * Creates a new CLValue instance with a Key value. + * Creates a new CLValue instance containing a Key value. * @param data - The Key to be stored in the CLValue. - * @returns A new CLValue instance containing the Key. + * @returns A new CLValue instance encapsulating the Key. */ public static newCLKey(data: Key): CLValue { const clValue = new CLValue(CLTypeKey); @@ -193,9 +190,9 @@ export class CLValue { } /** - * Creates a new CLValue instance with a URef value. + * Creates a new CLValue instance containing a URef value. * @param data - The URef to be stored in the CLValue. - * @returns A new CLValue instance containing the URef. + * @returns A new CLValue instance encapsulating the URef. */ public static newCLUref(data: URef): CLValue { const clValue = new CLValue(CLTypeUref); @@ -204,9 +201,9 @@ export class CLValue { } /** - * Creates a new CLValue instance with a PublicKey value. + * Creates a new CLValue instance containing a PublicKey value. * @param data - The PublicKey to be stored in the CLValue. - * @returns A new CLValue instance containing the PublicKey. + * @returns A new CLValue instance encapsulating the PublicKey. */ public static newCLPublicKey(data: PublicKey): CLValue { const clValue = new CLValue(CLTypePublicKey); diff --git a/src/types/clvalue/Int32.ts b/src/types/clvalue/Int32.ts index 5d8696c20..ba94be465 100644 --- a/src/types/clvalue/Int32.ts +++ b/src/types/clvalue/Int32.ts @@ -5,38 +5,39 @@ import { CLValue, IResultWithBytes } from './CLValue'; import { toBytesI32 } from '../ByteConverters'; /** - * Represents a 32-bit signed integer value in the CasperLabs type system. + * Represents a 32-bit signed integer value in the Casper type system. + * This class provides methods for handling 32-bit integers, including byte conversion and CLValue integration. */ export class CLValueInt32 { private value: BigNumberish; /** - * Constructs a new CLValueInt32 instance. - * @param value - The value to initialize the CLValueInt32 with. Should be a 32-bit integer. + * Initializes a new instance of the CLValueInt32 class. + * @param value - The 32-bit integer value to be stored in the CLValueInt32. */ constructor(value: BigNumberish) { this.value = value; } /** - * Returns the byte representation of the Int32 value. - * @returns A Uint8Array representing the bytes of the Int32 value in little-endian format. + * Converts the Int32 value to its byte representation in little-endian format. + * @returns A Uint8Array representing the bytes of the Int32 value. */ public bytes(): Uint8Array { return toBytesI32(this.value); } /** - * Returns a string representation of the Int32 value. - * @returns The string representation of the value. + * Provides a string representation of the Int32 value. + * @returns The string representation of the stored value. */ public toString(): string { return this.value.toString(); } /** - * Returns the number value of the Int32. - * @returns The number representation of the value. + * Retrieves the numeric value of the Int32. + * @returns The numeric representation of the value. */ public getValue(): BigNumberish { return this.value; @@ -44,8 +45,8 @@ export class CLValueInt32 { /** * Creates a new CLValue instance with an Int32 value. - * @param val - The value to initialize the Int32 with. Should be a 32-bit integer. - * @returns A new CLValue instance with CLTypeInt32 and a CLValueInt32. + * @param val - The 32-bit integer to be encapsulated in a CLValue. + * @returns A new CLValue instance containing CLTypeInt32 and a CLValueInt32. */ public static newCLInt32(val: BigNumberish): CLValue { const res = new CLValue(CLTypeInt32); @@ -55,8 +56,9 @@ export class CLValueInt32 { /** * Creates a CLValueInt32 instance from a Uint8Array. + * Interprets the first 4 bytes of the array as a 32-bit integer in little-endian format. * @param source - The Uint8Array containing the byte representation of the Int32 value. - * @returns A new CLValueInt32 instance. + * @returns An object containing the new CLValueInt32 instance and any remaining bytes. * @throws Will throw an error if the source array is smaller than Int32ByteSize. */ public static fromBytes(source: Uint8Array): IResultWithBytes { diff --git a/src/types/clvalue/Int64.ts b/src/types/clvalue/Int64.ts index 244488a1e..2b9a61496 100644 --- a/src/types/clvalue/Int64.ts +++ b/src/types/clvalue/Int64.ts @@ -5,38 +5,39 @@ import { CLValue, IResultWithBytes } from './CLValue'; import { toBytesI64 } from '../ByteConverters'; /** - * Represents a 64-bit signed integer value in the CasperLabs type system. + * Represents a 64-bit signed integer value in the Casper type system. + * This class provides methods for handling 64-bit integers, including byte conversion and CLValue integration. */ export class CLValueInt64 { private value: BigNumberish; /** - * Constructs a new CLValueInt64 instance. - * @param value - The value to initialize the CLValueInt64 with. Can be any BigNumberish type. + * Initializes a new instance of the CLValueInt64 class. + * @param value - The value to be stored in the CLValueInt64. Accepts any BigNumberish type. */ constructor(value: BigNumberish) { this.value = value; } /** - * Returns the byte representation of the Int64 value. - * @returns A Uint8Array representing the bytes of the Int64 value in little-endian format. + * Converts the Int64 value to its byte representation in little-endian format. + * @returns A Uint8Array representing the bytes of the Int64 value. */ public bytes(): Uint8Array { return toBytesI64(this.value); } /** - * Returns a string representation of the Int64 value. - * @returns The string representation of the value. + * Provides a string representation of the Int64 value. + * @returns The string representation of the stored value. */ public toString(): string { return this.value.toString(); } /** - * Returns the bigint value of the Int64. - * @returns The bigint representation of the value. + * Retrieves the bigint value of the Int64. + * @returns The bigint representation of the stored value. */ public getValue(): BigNumberish { return this.value; @@ -44,8 +45,8 @@ export class CLValueInt64 { /** * Creates a new CLValue instance with an Int64 value. - * @param val - The value to initialize the Int64 with. Can be any BigNumberish type. - * @returns A new CLValue instance with CLTypeInt64 and a CLValueInt64. + * @param val - The value to be stored in the Int64. Accepts any BigNumberish type. + * @returns A new CLValue instance containing CLTypeInt64 and a CLValueInt64. */ public static newCLInt64(val: BigNumberish): CLValue { const res = new CLValue(CLTypeInt64); @@ -55,8 +56,9 @@ export class CLValueInt64 { /** * Creates a CLValueInt64 instance from a Uint8Array. + * Interprets the first 8 bytes of the array as a 64-bit integer in little-endian format. * @param source - The Uint8Array containing the byte representation of the Int64 value. - * @returns A new CLValueInt64 instance. + * @returns An object containing the new CLValueInt64 instance and any remaining bytes. * @throws Will throw an error if the source array is smaller than Int64ByteSize. */ public static fromBytes(source: Uint8Array): IResultWithBytes { @@ -65,8 +67,8 @@ export class CLValueInt64 { } const bytes = Uint8Array.from(source.subarray(0, 8)); const val = BigNumber.from(bytes.slice().reverse()).fromTwos(64); - const resultButes = source.subarray(8); + const resultBytes = source.subarray(8); - return { result: new CLValueInt64(val), bytes: resultButes }; + return { result: new CLValueInt64(val), bytes: resultBytes }; } } diff --git a/src/types/clvalue/List.ts b/src/types/clvalue/List.ts index 694150b07..8b9260ccd 100644 --- a/src/types/clvalue/List.ts +++ b/src/types/clvalue/List.ts @@ -7,11 +7,12 @@ import { CLValueParser } from './Parser'; import { toBytesU32 } from '../ByteConverters'; /** - * Represents a List value in the CasperLabs type system. + * Represents a List value in the Casper type system. + * This class provides methods to manage and manipulate lists of CLValues. */ export class CLValueList { /** - * The type of the list. + * The type of the list elements. */ public type: CLTypeList; @@ -21,7 +22,7 @@ export class CLValueList { public elements: CLValue[]; /** - * Constructs a new CLValueList instance. + * Initializes a new instance of the CLValueList class. * @param type - The CLTypeList representing the type of the list. * @param elements - Optional array of CLValues to initialize the list with. */ @@ -31,8 +32,8 @@ export class CLValueList { } /** - * Returns the byte representation of the list. - * @returns A Uint8Array representing the bytes of the list, including its length and elements. + * Converts the list to its byte representation, including the length and each element's bytes. + * @returns A Uint8Array representing the bytes of the list. */ public bytes(): Uint8Array { const valueByteList = this.elements.map(e => e.bytes()); @@ -41,8 +42,8 @@ export class CLValueList { } /** - * Returns a string representation of the list. - * @returns A string representation of the list in the format "[elem1,elem2,...]". + * Provides a string representation of the list. + * @returns A string in the format "[elem1, elem2, ...]". */ public toString(): string { const strData = this.elements.map(one => `"${one.toString()}"`); @@ -116,7 +117,7 @@ export class CLValueList { } /** - * Returns a JSON representation of the list. + * Converts the list to a JSON-compatible representation. * @returns An array of string representations of the list elements. */ public toJSON(): any { @@ -126,7 +127,7 @@ export class CLValueList { /** * Creates a new CLValue instance with a List value. * @param elementType - The CLType for the elements of the list. - * @returns A new CLValue instance with CLTypeList and a CLValueList. + * @returns A new CLValue instance containing CLTypeList and a CLValueList. */ public static newCLList(elementType: CLType): CLValue { const listType = new CLTypeList(elementType); @@ -137,9 +138,10 @@ export class CLValueList { /** * Creates a CLValueList instance from a Uint8Array. + * Parses the byte array to interpret the length of the list and each element in the list. * @param source - The Uint8Array containing the byte representation of the List value. * @param clType - The CLTypeList representing the type of the list. - * @returns A new CLValueList instance. + * @returns An object containing the new CLValueList instance and any remaining bytes. */ public static fromBytes( source: Uint8Array, diff --git a/src/types/clvalue/Map.ts b/src/types/clvalue/Map.ts index 00e991ff2..f86e21132 100644 --- a/src/types/clvalue/Map.ts +++ b/src/types/clvalue/Map.ts @@ -1,13 +1,15 @@ +import { concat } from '@ethersproject/bytes'; + import { CLType, CLTypeMap } from './cltype'; import { CLValue, IResultWithBytes } from './CLValue'; import { CLValueTuple2 } from './Tuple2'; import { CLValueUInt32 } from './Uint32'; import { CLValueParser } from './Parser'; -import { concat } from '@ethersproject/bytes'; import { toBytesU32 } from '../ByteConverters'; /** - * Represents a Map value in the CasperLabs type system. + * Represents a Map value in the Casper type system. + * This class manages key-value pairs, providing efficient access and manipulation. */ export class CLValueMap { /** @@ -26,7 +28,7 @@ export class CLValueMap { private indexedData: Map = new Map(); /** - * Constructs a new CLValueMap instance. + * Initializes a new instance of the CLValueMap class. * @param mapType - The CLTypeMap representing the type of the map. * @param data - Optional array of CLValueTuple2 representing the map entries. * @param indexedData - Optional Map of string keys to CLValues for faster lookups. @@ -42,8 +44,8 @@ export class CLValueMap { } /** - * Returns the byte representation of the map. - * @returns A Uint8Array representing the bytes of the map. + * Converts the map to its byte representation. + * @returns A Uint8Array representing the bytes of the map, including its size and key-value pairs. */ bytes(): Uint8Array { const kvBytes = Array.from(this.data).map(element => { @@ -76,7 +78,7 @@ export class CLValueMap { } /** - * Returns a string representation of the map. + * Provides a string representation of the map. * @returns A string representation of the map entries. */ public toString(): string { @@ -161,9 +163,10 @@ export class CLValueMap { /** * Creates a CLValueMap instance from a Uint8Array. + * Parses the byte array to interpret the size of the map and each key-value pair. * @param bytes - The Uint8Array containing the byte representation of the Map value. * @param mapType - The CLTypeMap representing the type of the map. - * @returns A new CLValueMap instance. + * @returns An object containing the new CLValueMap instance and any remaining bytes. */ public static fromBytes( bytes: Uint8Array, diff --git a/src/types/clvalue/Option.ts b/src/types/clvalue/Option.ts index 79363ee42..18cf62508 100644 --- a/src/types/clvalue/Option.ts +++ b/src/types/clvalue/Option.ts @@ -6,15 +6,15 @@ import { CLValueParser } from './Parser'; import { CLValueUInt8 } from './Uint8'; /** - * Represents an optional value in the CasperLabs type system. - * An option can either contain a value or be empty. + * Represents an optional value in the Casper type system. + * An option can either contain a value or be empty (null). */ export class CLValueOption { public type?: CLTypeOption; public inner: CLValue | null; /** - * Constructs a new CLValueOption instance. + * Initializes a new instance of the CLValueOption class. * @param inner - The CLValue contained in the option, or null if empty. * @param type - The CLTypeOption representing the type of the option. */ @@ -24,9 +24,10 @@ export class CLValueOption { } /** - * Returns the byte representation of the option. + * Converts the option to its byte representation. + * If the option is empty, it returns a Uint8Array with a single 0 byte. + * If it contains a value, it returns a Uint8Array with 1 followed by the inner value's bytes. * @returns A Uint8Array representing the bytes of the option. - * If the option is empty, it returns [0]. Otherwise, it returns [1] followed by the inner value's bytes. */ public bytes(): Uint8Array { if (this.isEmpty()) { @@ -37,14 +38,11 @@ export class CLValueOption { } /** - * Returns a string representation of the option. + * Provides a string representation of the option. * @returns An empty string if the option is empty, otherwise the string representation of the inner value. */ public toString(): string { - if (this.isEmpty()) { - return ''; - } - return this.inner!.toString(); + return this.isEmpty() ? '' : this.inner!.toString(); } /** @@ -56,8 +54,8 @@ export class CLValueOption { } /** - * Returns the inner value of the option. - * @returns The inner CLValue if the option is not empty, null otherwise. + * Retrieves the inner value of the option. + * @returns The inner CLValue if the option is not empty, or null if it is empty. */ public value(): CLValue | null { return this.inner; @@ -66,7 +64,7 @@ export class CLValueOption { /** * Creates a new CLValue instance with an Option value. * @param inner - The CLValue to be contained in the option. - * @returns A new CLValue instance with CLTypeOption and a CLValueOption. + * @returns A new CLValue instance containing CLTypeOption and a CLValueOption. */ public static newCLOption(inner: CLValue): CLValue { const optionType = new CLTypeOption(inner.type); @@ -77,9 +75,10 @@ export class CLValueOption { /** * Creates a CLValueOption instance from a Uint8Array. + * Parses the byte array to determine if the option is empty or contains a value. * @param source - The Uint8Array containing the byte representation of the Option value. * @param clType - The CLTypeOption representing the type of the option. - * @returns A new CLValueOption instance or null if parsing fails. + * @returns An object containing the new CLValueOption instance and any remaining bytes. */ public static fromBytes( source: Uint8Array, diff --git a/src/types/clvalue/Parser.ts b/src/types/clvalue/Parser.ts index d94310661..eb93a30f9 100644 --- a/src/types/clvalue/Parser.ts +++ b/src/types/clvalue/Parser.ts @@ -45,7 +45,7 @@ export const ErrUnsupportedCLType = new Error( ); /** - * A utility class for parsing CLValues from various formats. + * A utility class for parsing CLValues from various formats, including JSON and byte arrays. */ export class CLValueParser { /** @@ -86,15 +86,14 @@ export class CLValueParser { * @returns A Uint8Array containing the serialized CLValue with type information. */ static toBytesWithType(value: CLValue): Uint8Array { - const valueBytes = value.bytes(); - return valueBytes; + return value.bytes(); } /** * Parses a CLValue from a Uint8Array given its type. * @param bytes - The Uint8Array containing the serialized CLValue. * @param sourceType - The CLType of the value to parse. - * @returns The parsed CLValue. + * @returns An object containing the parsed CLValue and any remaining bytes. * @throws {ErrUnsupportedCLType} If an unsupported CLType is encountered. */ public static fromBytesByType( diff --git a/src/types/clvalue/Result.ts b/src/types/clvalue/Result.ts index 9d4960009..1e308217f 100644 --- a/src/types/clvalue/Result.ts +++ b/src/types/clvalue/Result.ts @@ -1,11 +1,12 @@ +import { concat } from '@ethersproject/bytes'; + import { CLType, CLTypeResult } from './cltype'; import { CLValue, IResultWithBytes } from './CLValue'; import { CLValueParser } from './Parser'; -import { concat } from '@ethersproject/bytes'; import { CLValueUInt8 } from './Uint8'; /** - * Represents a Result type in the CasperLabs type system. + * Represents a Result type in the Casper type system. * A Result can either be a success (Ok) or an error (Err). */ export class CLValueResult { @@ -14,7 +15,7 @@ export class CLValueResult { public inner: CLValue; /** - * Constructs a new CLValueResult instance. + * Initializes a new instance of the CLValueResult class. * @param type - The CLTypeResult representing the type of the Result. * @param isSuccess - A boolean indicating whether the Result is a success (true) or an error (false). * @param inner - The CLValue contained within the Result. @@ -26,8 +27,9 @@ export class CLValueResult { } /** - * Returns the byte representation of the Result. - * @returns A Uint8Array representing the bytes of the Result, including a success flag and the inner value. + * Converts the Result to its byte representation. + * Includes a success flag byte (1 for success, 0 for error) followed by the bytes of the inner value. + * @returns A Uint8Array representing the bytes of the Result. */ public bytes(): Uint8Array { const successByte = Uint8Array.from([this.isSuccess ? 1 : 0]); @@ -36,7 +38,7 @@ export class CLValueResult { } /** - * Returns a string representation of the Result. + * Provides a string representation of the Result. * @returns A string representation of the Result, either "Ok(innerValue)" or "Err(innerValue)". */ public toString(): string { @@ -46,7 +48,7 @@ export class CLValueResult { } /** - * Returns the inner CLValue of the Result. + * Retrieves the inner CLValue of the Result. * @returns The CLValue contained within the Result. */ public value(): CLValue { @@ -59,7 +61,7 @@ export class CLValueResult { * @param innerErr - The CLType for the error case. * @param value - The CLValue to be contained in the Result. * @param isSuccess - A boolean indicating whether the Result is a success (true) or an error (false). - * @returns A new CLValue instance with CLTypeResult and a CLValueResult. + * @returns A new CLValue instance containing CLTypeResult and a CLValueResult. */ public static newCLResult( innerOk: CLType, @@ -75,9 +77,10 @@ export class CLValueResult { /** * Creates a CLValueResult instance from a Uint8Array. + * Parses the byte array to interpret the success flag and the inner value. * @param source - The Uint8Array containing the byte representation of the Result value. * @param clType - The CLTypeResult representing the type of the Result. - * @returns A new CLValueResult instance. + * @returns An object containing the new CLValueResult instance and any remaining bytes. */ public static fromBytes( source: Uint8Array, diff --git a/src/types/clvalue/String.ts b/src/types/clvalue/String.ts index c476d2780..507488640 100644 --- a/src/types/clvalue/String.ts +++ b/src/types/clvalue/String.ts @@ -6,13 +6,13 @@ import { CLValueUInt32 } from './Uint32'; import { fromBytesString } from '../ByteConverters'; /** - * Represents a string value in the CasperLabs type system. + * Represents a string value in the Casper type system. */ export class CLValueString { private value: string; /** - * Constructs a new CLValueString instance. + * Initializes a new instance of the CLValueString class. * @param value - The string value to be represented. */ constructor(value: string) { @@ -20,8 +20,9 @@ export class CLValueString { } /** - * Returns the byte representation of the string value. - * @returns A Uint8Array representing the bytes of the string, prefixed with its length. + * Converts the string value to its byte representation. + * The result is a Uint8Array containing the length of the string (as a 4-byte prefix) followed by the string's bytes. + * @returns A Uint8Array representing the bytes of the string. */ public bytes(): Uint8Array { const sizeBytes = this.sizeToBytes(this.value.length); @@ -29,6 +30,11 @@ export class CLValueString { return concat([sizeBytes, valueBytes]); } + /** + * Converts a size number to its 4-byte Uint8Array representation in little-endian format. + * @param size - The size to convert. + * @returns A Uint8Array representing the size. + */ private sizeToBytes(size: number): Uint8Array { const buffer = new ArrayBuffer(4); const view = new DataView(buffer); @@ -37,7 +43,7 @@ export class CLValueString { } /** - * Returns the string value. + * Provides the string value. * @returns The string value. */ public toString(): string { @@ -47,7 +53,7 @@ export class CLValueString { /** * Creates a new CLValue instance with a string value. * @param val - The string value to be represented. - * @returns A new CLValue instance with CLTypeString and a CLValueString. + * @returns A new CLValue instance containing CLTypeString and a CLValueString. */ public static newCLString(val: string): CLValue { const res = new CLValue(CLTypeString); @@ -57,8 +63,9 @@ export class CLValueString { /** * Creates a CLValueString instance from a Uint8Array. + * Parses the byte array to retrieve the string value, interpreting the first 4 bytes as the string length. * @param source - The Uint8Array containing the byte representation of the string value. - * @returns A new CLValueString instance. + * @returns An object containing the new CLValueString instance and any remaining bytes. */ public static fromBytes(source: Uint8Array): IResultWithBytes { const uint32Value = CLValueUInt32.fromBytes(source); diff --git a/src/types/clvalue/Tuple1.ts b/src/types/clvalue/Tuple1.ts index ea97c02f6..10c9730fa 100644 --- a/src/types/clvalue/Tuple1.ts +++ b/src/types/clvalue/Tuple1.ts @@ -3,14 +3,14 @@ import { CLValue, IResultWithBytes } from './CLValue'; import { CLValueParser } from './Parser'; /** - * Represents a tuple of one CLValue in the CasperLabs type system. + * Represents a tuple containing one CLValue in the Casper type system. */ export class CLValueTuple1 { public innerType: CLTypeTuple1; private innerVal: CLValue; /** - * Constructs a new CLValueTuple1 instance. + * Initializes a new instance of the CLValueTuple1 class. * @param innerType - The CLTypeTuple1 representing the type of the tuple. * @param innerVal - The CLValue contained in the tuple. */ @@ -20,7 +20,7 @@ export class CLValueTuple1 { } /** - * Returns the byte representation of the tuple. + * Converts the tuple to its byte representation. * @returns A Uint8Array representing the bytes of the inner CLValue. */ public bytes(): Uint8Array { @@ -28,7 +28,7 @@ export class CLValueTuple1 { } /** - * Returns a string representation of the tuple. + * Provides a string representation of the tuple. * @returns A string representation of the tuple in the format "(value)". */ public toString(): string { @@ -36,7 +36,7 @@ export class CLValueTuple1 { } /** - * Returns the value of the tuple. + * Retrieves the value of the tuple. * @returns The CLValue contained in the tuple. */ public value(): CLValue { @@ -46,7 +46,7 @@ export class CLValueTuple1 { /** * Creates a new CLValue instance with a Tuple1 value. * @param val - The CLValue to be contained in the tuple. - * @returns A new CLValue instance with CLTypeTuple1 and a CLValueTuple1. + * @returns A new CLValue instance containing CLTypeTuple1 and a CLValueTuple1. */ public static newCLTuple1(val: CLValue): CLValue { const tupleType = new CLTypeTuple1(val.type); @@ -57,9 +57,10 @@ export class CLValueTuple1 { /** * Creates a CLValueTuple1 instance from a Uint8Array. + * Parses the byte array to retrieve the inner value of the tuple. * @param source - The Uint8Array containing the byte representation of the Tuple1 value. * @param clType - The CLTypeTuple1 representing the type of the tuple. - * @returns A new CLValueTuple1 instance. + * @returns An object containing the new CLValueTuple1 instance and any remaining bytes. */ public static fromBytes( source: Uint8Array, diff --git a/src/types/clvalue/Tuple2.ts b/src/types/clvalue/Tuple2.ts index 2be6e6f83..a7aefc739 100644 --- a/src/types/clvalue/Tuple2.ts +++ b/src/types/clvalue/Tuple2.ts @@ -5,7 +5,7 @@ import { CLValue, IResultWithBytes } from './CLValue'; import { CLValueParser } from './Parser'; /** - * Represents a tuple of two CLValues in the CasperLabs type system. + * Represents a tuple containing two CLValues in the Casper type system. */ export class CLValueTuple2 { public innerType: CLTypeTuple2; @@ -13,7 +13,7 @@ export class CLValueTuple2 { public inner2: CLValue; /** - * Constructs a new CLValueTuple2 instance. + * Initializes a new instance of the CLValueTuple2 class. * @param innerType - The CLTypeTuple2 representing the type of the tuple. * @param inner1 - The first CLValue in the tuple. * @param inner2 - The second CLValue in the tuple. @@ -25,7 +25,7 @@ export class CLValueTuple2 { } /** - * Returns the byte representation of the tuple. + * Converts the tuple to its byte representation. * @returns A Uint8Array representing the concatenated bytes of both inner CLValues. */ public bytes(): Uint8Array { @@ -35,7 +35,7 @@ export class CLValueTuple2 { } /** - * Returns a string representation of the tuple. + * Provides a string representation of the tuple. * @returns A string representation of the tuple in the format "(value1, value2)". */ public toString(): string { @@ -43,7 +43,7 @@ export class CLValueTuple2 { } /** - * Returns the values of the tuple as an array of CLValues. + * Retrieves the values of the tuple as an array. * @returns An array containing the two CLValues of the tuple. */ public value(): [CLValue, CLValue] { @@ -54,7 +54,7 @@ export class CLValueTuple2 { * Creates a new CLValue instance with a Tuple2 value. * @param val1 - The first CLValue in the tuple. * @param val2 - The second CLValue in the tuple. - * @returns A new CLValue instance with CLTypeTuple2 and a CLValueTuple2. + * @returns A new CLValue instance containing CLTypeTuple2 and a CLValueTuple2. */ public static newCLTuple2(val1: CLValue, val2: CLValue): CLValue { const tupleType = new CLTypeTuple2(val1.type, val2.type); @@ -65,9 +65,10 @@ export class CLValueTuple2 { /** * Creates a CLValueTuple2 instance from a Uint8Array. + * Parses the byte array to retrieve the two values of the tuple. * @param source - The Uint8Array containing the byte representation of the Tuple2 value. * @param clType - The CLTypeTuple2 representing the type of the tuple. - * @returns A new CLValueTuple2 instance. + * @returns An object containing the new CLValueTuple2 instance and any remaining bytes. */ public static fromBytes( source: Uint8Array, diff --git a/src/types/clvalue/Tuple3.ts b/src/types/clvalue/Tuple3.ts index 99860f408..75084622a 100644 --- a/src/types/clvalue/Tuple3.ts +++ b/src/types/clvalue/Tuple3.ts @@ -4,7 +4,7 @@ import { CLValue, IResultWithBytes } from './CLValue'; import { concat } from '@ethersproject/bytes'; /** - * Represents a tuple of three CLValues in the CasperLabs type system. + * Represents a tuple containing three CLValues in the Casper type system. */ export class CLValueTuple3 { public innerType: CLType; @@ -13,7 +13,7 @@ export class CLValueTuple3 { public inner3: CLValue; /** - * Constructs a new CLValueTuple3 instance. + * Initializes a new instance of the CLValueTuple3 class. * @param innerType - The CLType representing the type of the tuple. * @param inner1 - The first CLValue in the tuple. * @param inner2 - The second CLValue in the tuple. @@ -32,7 +32,7 @@ export class CLValueTuple3 { } /** - * Returns the byte representation of the tuple. + * Converts the tuple to its byte representation. * @returns A Uint8Array representing the concatenated bytes of all three inner CLValues. */ public bytes(): Uint8Array { @@ -43,7 +43,7 @@ export class CLValueTuple3 { } /** - * Returns a string representation of the tuple. + * Provides a string representation of the tuple. * @returns A string representation of the tuple in the format "(value1, value2, value3)". */ public toString(): string { @@ -51,7 +51,7 @@ export class CLValueTuple3 { } /** - * Returns the values of the tuple as an array of CLValues. + * Retrieves the values of the tuple as an array. * @returns An array containing the three CLValues of the tuple. */ public getValue(): [CLValue, CLValue, CLValue] { @@ -63,7 +63,7 @@ export class CLValueTuple3 { * @param val1 - The first CLValue in the tuple. * @param val2 - The second CLValue in the tuple. * @param val3 - The third CLValue in the tuple. - * @returns A new CLValue instance with CLTypeTuple3 and a CLValueTuple3. + * @returns A new CLValue instance containing CLTypeTuple3 and a CLValueTuple3. */ public static newCLTuple3( val1: CLValue, @@ -78,9 +78,10 @@ export class CLValueTuple3 { /** * Creates a CLValueTuple3 instance from a Uint8Array. + * Parses the byte array to retrieve the three values of the tuple. * @param source - The Uint8Array containing the byte representation of the Tuple3 value. * @param clType - The CLTypeTuple3 representing the type of the tuple. - * @returns A new CLValueTuple3 instance or null if parsing fails. + * @returns An object containing the new CLValueTuple3 instance and any remaining bytes. */ public static fromBytes( source: Uint8Array, diff --git a/src/types/clvalue/Uint128.ts b/src/types/clvalue/Uint128.ts index dd9c60eed..dd755731f 100644 --- a/src/types/clvalue/Uint128.ts +++ b/src/types/clvalue/Uint128.ts @@ -6,21 +6,21 @@ import { CLValue, IResultWithBytes } from './CLValue'; import { toBytesU128 } from '../ByteConverters'; /** - * Represents a 128-bit unsigned integer value in the CasperLabs type system. + * Represents a 128-bit unsigned integer value in the Casper type system. */ export class CLValueUInt128 { private val: BigNumber; /** - * Constructs a new CLValueUInt128 instance. - * @param val - The value to initialize the CLValueUInt128 with. Can be a BigNumber or a string. + * Initializes a new instance of the CLValueUInt128 class. + * @param val - The value to initialize the CLValueUInt128 with. Accepts a BigNumber or a string. */ constructor(val: BigNumber | string) { this.val = BigNumber.from(val); } /** - * Returns the byte representation of the UInt128 value. + * Converts the UInt128 value to its byte representation. * @returns A Uint8Array representing the bytes of the UInt128 value. */ public bytes(): Uint8Array { @@ -28,7 +28,7 @@ export class CLValueUInt128 { } /** - * Returns a string representation of the UInt128 value. + * Provides a string representation of the UInt128 value. * @returns The string representation of the value. */ public toString(): string { @@ -36,7 +36,7 @@ export class CLValueUInt128 { } /** - * Returns the BigNumber value of the UInt128. + * Retrieves the BigNumber value of the UInt128. * @returns The BigNumber representation of the value. */ public getValue(): BigNumber { @@ -46,7 +46,7 @@ export class CLValueUInt128 { /** * Creates a new CLValue instance with a UInt128 value. * @param val - The value to initialize the UInt128 with. Can be a BigNumber or a string. - * @returns A new CLValue instance with CLTypeUInt128 and a CLValueUInt128. + * @returns A new CLValue instance containing CLTypeUInt128 and a CLValueUInt128. */ public static newCLUInt128(val: BigNumber | string): CLValue { const res = new CLValue(CLTypeUInt128); @@ -56,8 +56,9 @@ export class CLValueUInt128 { /** * Creates a CLValueUInt128 instance from a Uint8Array. + * Parses the byte array to retrieve the UInt128 value. * @param source - The Uint8Array containing the byte representation of the UInt128 value. - * @returns A new CLValueUInt128 instance. + * @returns An object containing the new CLValueUInt128 instance and any remaining bytes. */ public static fromBytes( source: Uint8Array diff --git a/src/types/clvalue/Uint256.ts b/src/types/clvalue/Uint256.ts index 57572d188..990b46fc9 100644 --- a/src/types/clvalue/Uint256.ts +++ b/src/types/clvalue/Uint256.ts @@ -6,21 +6,21 @@ import { CLTypeUInt256 } from './cltype'; import { toBytesU256 } from '../ByteConverters'; /** - * Represents a 256-bit unsigned integer value in the CasperLabs type system. + * Represents a 256-bit unsigned integer value in the Casper type system. */ export class CLValueUInt256 { private val: BigNumber; /** - * Constructs a new CLValueUInt256 instance. - * @param val - The value to initialize the CLValueUInt256 with. Can be a BigNumber or a string. + * Initializes a new instance of the CLValueUInt256 class. + * @param val - The value to initialize the CLValueUInt256 with. Accepts a BigNumber or a string. */ constructor(val: BigNumber | string) { this.val = BigNumber.from(val); } /** - * Returns the byte representation of the UInt256 value. + * Converts the UInt256 value to its byte representation. * @returns A Uint8Array representing the bytes of the UInt256 value. */ public bytes(): Uint8Array { @@ -28,7 +28,7 @@ export class CLValueUInt256 { } /** - * Returns a string representation of the UInt256 value. + * Provides a string representation of the UInt256 value. * @returns The string representation of the value. */ public toString(): string { @@ -36,7 +36,7 @@ export class CLValueUInt256 { } /** - * Returns the BigNumber value of the UInt256. + * Retrieves the BigNumber value of the UInt256. * @returns The BigNumber representation of the value. */ public getValue(): BigNumber { @@ -46,7 +46,7 @@ export class CLValueUInt256 { /** * Creates a new CLValue instance with a UInt256 value. * @param val - The value to initialize the UInt256 with. Can be a BigNumber or a string. - * @returns A new CLValue instance with CLTypeUInt256 and a CLValueUInt256. + * @returns A new CLValue instance containing CLTypeUInt256 and a CLValueUInt256. */ public static newCLUInt256(val: BigNumber | string): CLValue { const res = new CLValue(CLTypeUInt256); @@ -56,8 +56,9 @@ export class CLValueUInt256 { /** * Creates a CLValueUInt256 instance from a Uint8Array. + * Parses the byte array to retrieve the UInt256 value. * @param source - The Uint8Array containing the byte representation of the UInt256 value. - * @returns A new CLValueUInt256 instance. + * @returns An object containing the new CLValueUInt256 instance and any remaining bytes. */ public static fromBytes( source: Uint8Array diff --git a/src/types/clvalue/Uint32.ts b/src/types/clvalue/Uint32.ts index d4ba323b7..a41ddc7b7 100644 --- a/src/types/clvalue/Uint32.ts +++ b/src/types/clvalue/Uint32.ts @@ -5,13 +5,13 @@ import { CLValue, IResultWithBytes } from './CLValue'; import { toBytesU32 } from '../ByteConverters'; /** - * Represents a 32-bit unsigned integer value in the CasperLabs type system. + * Represents a 32-bit unsigned integer value in the Casper type system. */ export class CLValueUInt32 { private value: BigNumber; /** - * Constructs a new CLValueUInt32 instance. + * Initializes a new instance of the CLValueUInt32 class. * @param value - The value to initialize the CLValueUInt32 with. */ constructor(value: BigNumber) { @@ -19,15 +19,15 @@ export class CLValueUInt32 { } /** - * Returns the byte representation of the UInt32 value. - * @returns A Uint8Array representing the bytes of the UInt32 value in little-endian format. + * Converts the UInt32 value to its byte representation in little-endian format. + * @returns A Uint8Array representing the bytes of the UInt32 value. */ public bytes(): Uint8Array { return toBytesU32(this.value); } /** - * Returns a string representation of the UInt32 value. + * Provides a string representation of the UInt32 value. * @returns The string representation of the value. */ public toString(): string { @@ -35,8 +35,8 @@ export class CLValueUInt32 { } /** - * Returns the number value of the UInt32. - * @returns The number representation of the value. + * Retrieves the numeric value of the UInt32. + * @returns The BigNumber representation of the value. */ public getValue(): BigNumber { return this.value; @@ -45,7 +45,7 @@ export class CLValueUInt32 { /** * Creates a new CLValue instance with a UInt32 value. * @param val - The value to initialize the UInt32 with. - * @returns A new CLValue instance with CLTypeUInt32 and a CLValueUInt32. + * @returns A new CLValue instance containing CLTypeUInt32 and a CLValueUInt32. */ public static newCLUInt32(val: BigNumber): CLValue { const res = new CLValue(CLTypeUInt32); @@ -55,8 +55,10 @@ export class CLValueUInt32 { /** * Creates a CLValueUInt32 instance from a Uint8Array. + * Parses the byte array to retrieve the UInt32 value. * @param source - The Uint8Array containing the byte representation of the UInt32 value. - * @returns A new CLValueUInt32 instance. + * @returns An object containing the new CLValueUInt32 instance and any remaining bytes. + * @throws Error if the source array is too short for a UInt32 value. */ public static fromBytes(source: Uint8Array): IResultWithBytes { if (source.length < Int32ByteSize) { @@ -69,8 +71,8 @@ export class CLValueUInt32 { } /** - * Converts a number to its UInt32 byte representation. - * @param val - The number to convert. + * Converts a BigNumber to its UInt32 byte representation. + * @param val - The BigNumber value to convert. * @returns A Uint8Array representing the bytes of the UInt32 value. */ public static sizeToBytes(val: BigNumber): Uint8Array { diff --git a/src/types/clvalue/Uint512.ts b/src/types/clvalue/Uint512.ts index d329a7615..9b9da6572 100644 --- a/src/types/clvalue/Uint512.ts +++ b/src/types/clvalue/Uint512.ts @@ -6,15 +6,15 @@ import { CLTypeUInt512 } from './cltype'; import { toBytesU512 } from '../ByteConverters'; /** - * Represents a 512-bit unsigned integer value in the CasperLabs type system. + * Represents a 512-bit unsigned integer value in the Casper type system. */ export class CLValueUInt512 { public val: BigNumber; public isStringFmt: boolean; /** - * Constructs a new CLValueUInt512 instance. - * @param val - The value to initialize the CLValueUInt512 with. Can be a BigNumber or a string. + * Initializes a new instance of the CLValueUInt512 class. + * @param val - The value to initialize the CLValueUInt512 with. Accepts a BigNumber or a string. */ constructor(val: BigNumber | string) { this.val = BigNumber.from(val); @@ -22,7 +22,7 @@ export class CLValueUInt512 { } /** - * Returns the byte representation of the UInt512 value. + * Converts the UInt512 value to its byte representation. * @returns A Uint8Array representing the bytes of the UInt512 value. */ public bytes(): Uint8Array { @@ -30,7 +30,7 @@ export class CLValueUInt512 { } /** - * Returns a string representation of the UInt512 value. + * Provides a string representation of the UInt512 value. * @returns The string representation of the value. */ public toString(): string { @@ -38,7 +38,7 @@ export class CLValueUInt512 { } /** - * Returns the BigNumber value of the UInt512. + * Retrieves the BigNumber value of the UInt512. * @returns The BigNumber representation of the value. */ public value(): BigNumber { @@ -50,10 +50,7 @@ export class CLValueUInt512 { * @returns A string if the value was originally provided as a string, otherwise a number. */ public toJSON(): string | number { - if (this.isStringFmt) { - return this.toString(); - } - return this.val.toNumber(); + return this.isStringFmt ? this.toString() : this.val.toNumber(); } /** @@ -77,8 +74,9 @@ export class CLValueUInt512 { /** * Creates a CLValueUInt512 instance from a Uint8Array. + * Parses the byte array to retrieve the UInt512 value. * @param source - The Uint8Array containing the byte representation of the UInt512 value. - * @returns A new CLValueUInt512 instance. + * @returns An object containing the new CLValueUInt512 instance and any remaining bytes. */ public static fromBytes( source: Uint8Array @@ -89,7 +87,7 @@ export class CLValueUInt512 { /** * Creates a new CLValue instance with a UInt512 value. * @param val - The value to initialize the UInt512 with. Can be a BigNumber or a string. - * @returns A new CLValue instance with CLTypeUInt512 and a CLValueUInt512. + * @returns A new CLValue instance containing CLTypeUInt512 and a CLValueUInt512. */ public static newCLUInt512(val: BigNumber | string): CLValue { const res = new CLValue(CLTypeUInt512); @@ -98,6 +96,12 @@ export class CLValueUInt512 { } } +/** + * Deserializes an array of rewards into a Map. + * @param arr - The array to be deserialized, where each element is a tuple containing a key and an array of rewards. + * @returns A Map where each key corresponds to an array of CLValueUInt512 rewards. + * @throws Will throw an error if duplicate keys are detected. + */ export const deserializeRewards = (arr: any) => { const parsed = new Map( Array.from(arr, ([key, value]) => { @@ -115,6 +119,11 @@ export const deserializeRewards = (arr: any) => { return parsed; }; +/** + * Serializes a Map of rewards into an array format suitable for JSON storage. + * @param map - A Map where each key corresponds to an array of CLValueUInt512 rewards. + * @returns An array where each element is a tuple containing a key and an array of rewards in JSON format. + */ export const serializeRewards = (map: Map) => { return Array.from(map, ([key, value]) => { const serializedValue = value.map(item => item.toJSON()); diff --git a/src/types/clvalue/Uint64.ts b/src/types/clvalue/Uint64.ts index 3f1dfcd3c..d3b8461ff 100644 --- a/src/types/clvalue/Uint64.ts +++ b/src/types/clvalue/Uint64.ts @@ -4,13 +4,13 @@ import { CLValue, IResultWithBytes } from './CLValue'; import { toBytesU64 } from '../ByteConverters'; /** - * Represents a 64-bit unsigned integer value in the CasperLabs type system. + * Represents a 64-bit unsigned integer value in the Casper type system. */ export class CLValueUInt64 { private value: BigNumberish; /** - * Constructs a new CLValueUInt64 instance. + * Initializes a new instance of the CLValueUInt64 class. * @param value - The value to initialize the CLValueUInt64 with. Can be any BigNumberish type. */ constructor(value: BigNumberish) { @@ -18,15 +18,15 @@ export class CLValueUInt64 { } /** - * Returns the byte representation of the UInt64 value. - * @returns A Uint8Array representing the bytes of the UInt64 value in little-endian format. + * Converts the UInt64 value to its byte representation in little-endian format. + * @returns A Uint8Array representing the bytes of the UInt64 value. */ public bytes(): Uint8Array { return toBytesU64(this.value); } /** - * Returns a string representation of the UInt64 value. + * Provides a string representation of the UInt64 value. * @returns The string representation of the value. */ public toString(): string { @@ -34,8 +34,8 @@ export class CLValueUInt64 { } /** - * Returns the bigint value of the UInt64. - * @returns The bigint representation of the value. + * Retrieves the BigNumberish value of the UInt64. + * @returns The BigNumberish representation of the value. */ public getValue(): BigNumberish { return this.value; @@ -44,7 +44,7 @@ export class CLValueUInt64 { /** * Creates a new CLValue instance with a UInt64 value. * @param val - The value to initialize the UInt64 with. Can be any BigNumberish type. - * @returns A new CLValue instance with CLTypeUInt64 and a CLValueUInt64. + * @returns A new CLValue instance containing CLTypeUInt64 and a CLValueUInt64. */ public static newCLUint64(val: BigNumberish): CLValue { const res = new CLValue(CLTypeUInt64); @@ -54,9 +54,10 @@ export class CLValueUInt64 { /** * Creates a CLValueUInt64 instance from a Uint8Array. + * Parses the byte array to retrieve the UInt64 value. * @param source - The Uint8Array containing the byte representation of the UInt64 value. - * @returns A new CLValueUInt64 instance. - * @throws Will throw an error if the source array is smaller than Int64ByteSize. + * @returns An object containing the new CLValueUInt64 instance and any remaining bytes. + * @throws Error if the source array is smaller than the required size for a UInt64. */ public static fromBytes(source: Uint8Array): IResultWithBytes { if (source.length < Int64ByteSize) { diff --git a/src/types/clvalue/Uint8.ts b/src/types/clvalue/Uint8.ts index 49727c69a..10ba09280 100644 --- a/src/types/clvalue/Uint8.ts +++ b/src/types/clvalue/Uint8.ts @@ -3,21 +3,21 @@ import { CLTypeUInt8 } from './cltype'; import { toBytesU8 } from '../ByteConverters'; /** - * Represents an 8-bit unsigned integer value in the CasperLabs type system. + * Represents an 8-bit unsigned integer value in the Casper type system. */ export class CLValueUInt8 { private value: number; /** - * Constructs a new CLValueUInt8 instance. - * @param value - The value to initialize the CLValueUInt8 with. Should be an integer between 0 and 255. + * Initializes a new instance of the CLValueUInt8 class. + * @param value - The value to initialize the CLValueUInt8 with. Must be an integer between 0 and 255. */ constructor(value: number) { this.value = value; } /** - * Returns the byte representation of the UInt8 value. + * Converts the UInt8 value to its byte representation. * @returns A Uint8Array containing a single byte representing the UInt8 value. */ public bytes(): Uint8Array { @@ -25,7 +25,7 @@ export class CLValueUInt8 { } /** - * Returns a string representation of the UInt8 value. + * Provides a string representation of the UInt8 value. * @returns The string representation of the value. */ public toString(): string { @@ -33,7 +33,7 @@ export class CLValueUInt8 { } /** - * Returns the number value of the UInt8. + * Retrieves the number value of the UInt8. * @returns The number representation of the value. */ public getValue(): number { @@ -42,8 +42,8 @@ export class CLValueUInt8 { /** * Creates a new CLValue instance with a UInt8 value. - * @param val - The value to initialize the UInt8 with. Should be an integer between 0 and 255. - * @returns A new CLValue instance with CLTypeUInt8 and a CLValueUInt8. + * @param val - The value to initialize the UInt8 with. Must be an integer between 0 and 255. + * @returns A new CLValue instance containing CLTypeUInt8 and a CLValueUInt8. */ public static newCLUint8(val: number): CLValue { const res = new CLValue(CLTypeUInt8); @@ -53,8 +53,10 @@ export class CLValueUInt8 { /** * Creates a CLValueUInt8 instance from a Uint8Array. + * Parses the first byte to retrieve the UInt8 value. * @param source - The Uint8Array containing the byte representation of the UInt8 value. - * @returns A new CLValueUInt8 instance. + * @returns An object containing the new CLValueUInt8 instance and any remaining bytes. + * @throws Error if the source array is empty. */ public static fromBytes(source: Uint8Array): IResultWithBytes { if (source.length === 0) { diff --git a/src/types/clvalue/UintBig.ts b/src/types/clvalue/UintBig.ts index 55ff5fded..cd26593ce 100644 --- a/src/types/clvalue/UintBig.ts +++ b/src/types/clvalue/UintBig.ts @@ -6,19 +6,14 @@ import { CLValueUInt512 } from './Uint512'; import { IResultWithBytes } from './CLValue'; /** - * Converts a BigNumber to a Uint8Array representation. + * Converts a BigNumber to a Uint8Array with a length prefix. * - * The resulting Uint8Array has the following structure: - * - The first byte represents the length of the BigNumber in bytes. - * - The remaining bytes represent the BigNumber value itself. + * The resulting Uint8Array structure: + * - The first byte is the length of the BigNumber in bytes. + * - The remaining bytes represent the BigNumber itself. * * @param val - The BigNumber to convert. - * @returns A Uint8Array representation of the BigNumber. - * - * @example - * const bigNum = BigNumber.from('123456789'); - * const bytes = bigToBytes(bigNum); - * console.log(bytes); // Uint8Array [ 4, 7, 91, 205, 21 ] + * @returns Uint8Array representation of the BigNumber. */ export const bigToBytes = (val: BigNumber): Uint8Array => { let hex = val.toHexString().slice(2); @@ -40,19 +35,14 @@ export const bigToBytes = (val: BigNumber): Uint8Array => { }; /** - * Converts an ArrayBuffer containing a byte representation of a BigNumber back to a BigNumber. - * - * The input ArrayBuffer should have the following structure: - * - The first byte represents the length of the BigNumber in bytes. - * - The remaining bytes represent the BigNumber value itself. + * Converts an ArrayBuffer with a length prefix to a BigNumber. * - * @param buffer - The ArrayBuffer containing the byte representation of a BigNumber. - * @returns The BigNumber reconstructed from the byte representation. + * Expected input structure: + * - First byte: length of the BigNumber in bytes. + * - Remaining bytes: BigNumber value. * - * @example - * const buffer = new Uint8Array([4, 7, 91, 205, 21]).buffer; - * const bigNum = bigFromBuffer(buffer); - * console.log(bigNum.toString()); // '123456789' + * @param buffer - The ArrayBuffer containing the prefixed byte representation. + * @returns BigNumber reconstructed from the byte representation. */ export const bigFromBuffer = (buffer: ArrayBuffer): BigNumber => { const view = new DataView(buffer); @@ -68,6 +58,14 @@ export const bigFromBuffer = (buffer: ArrayBuffer): BigNumber => { return BigNumber.from('0x' + hex); }; +/** + * Helper to parse BigNumber from prefixed bytes with bit size validation. + * + * @param rawBytes - Byte array containing the prefixed BigNumber data. + * @param bitSize - Bit size (e.g., 128, 256, or 512) to validate the BigNumber. + * @returns An object containing the parsed BigNumber and remaining bytes. + * @throws Error if the byte length exceeds expected size or data is insufficient. + */ const fromBytesBigIntBase = ( rawBytes: Uint8Array, bitSize: number @@ -100,6 +98,11 @@ const fromBytesBigIntBase = ( }; }; +/** + * Parses a Uint128 CLValue from prefixed bytes. + * @param rawBytes - Byte array containing the prefixed Uint128 data. + * @returns The CLValueUInt128 parsed from the byte data. + */ export const fromBytesUInt128 = ( rawBytes: Uint8Array ): IResultWithBytes => { @@ -107,6 +110,11 @@ export const fromBytesUInt128 = ( return { result: new CLValueUInt128(value?.result), bytes: value?.bytes }; }; +/** + * Parses a Uint256 CLValue from prefixed bytes. + * @param rawBytes - Byte array containing the prefixed Uint256 data. + * @returns The CLValueUInt256 parsed from the byte data. + */ export const fromBytesUInt256 = ( rawBytes: Uint8Array ): IResultWithBytes => { @@ -114,6 +122,11 @@ export const fromBytesUInt256 = ( return { result: new CLValueUInt256(value?.result), bytes: value?.bytes }; }; +/** + * Parses a Uint512 CLValue from prefixed bytes. + * @param rawBytes - Byte array containing the prefixed Uint512 data. + * @returns The CLValueUInt512 parsed from the byte data. + */ export const fromBytesUInt512 = ( rawBytes: Uint8Array ): IResultWithBytes => { diff --git a/src/types/clvalue/Unit.ts b/src/types/clvalue/Unit.ts index b972d72b9..c97c3d4d8 100644 --- a/src/types/clvalue/Unit.ts +++ b/src/types/clvalue/Unit.ts @@ -2,7 +2,7 @@ import { CLTypeUnit } from './cltype'; import { CLValue, IResultWithBytes } from './CLValue'; /** - * Represents a Unit value in the CasperLabs type system. + * Represents a Unit value in the Casper type system. * A Unit value is similar to 'null' or 'void' in other languages. */ export class CLValueUnit { diff --git a/src/types/clvalue/cltype/ByteArray.ts b/src/types/clvalue/cltype/ByteArray.ts index 16857c94a..48e3e7202 100644 --- a/src/types/clvalue/cltype/ByteArray.ts +++ b/src/types/clvalue/cltype/ByteArray.ts @@ -1,33 +1,34 @@ import { concat } from '@ethersproject/bytes'; - import { CLType, TypeID, TypeName } from './CLType'; import { toBytesU32 } from '../../ByteConverters'; /** - * Represents a ByteArray type in the CasperLabs type system. - * This type is used for fixed-size byte arrays. + * Represents a fixed-size ByteArray type within the Casper type system. + * This class allows for defining a ByteArray with a specific size, and includes methods + * to handle its serialization, string representation, and conversion to JSON format. */ export class CLTypeByteArray implements CLType { public size: number; /** - * Constructs a new CLTypeByteArray instance. - * @param size - The size of the byte array. + * Initializes a new instance of the CLTypeByteArray class. + * @param size - Specifies the fixed size of the byte array. */ constructor(size: number) { this.size = size; } /** - * Converts the CLTypeByteArray to its byte representation. - * @returns A Uint8Array representing the CLTypeByteArray, including its type ID and size. + * Converts the CLTypeByteArray instance into a byte representation. + * This includes the type ID and the size of the byte array. + * @returns A Uint8Array that represents the CLTypeByteArray. */ public toBytes(): Uint8Array { return concat([Uint8Array.from([this.getTypeID()]), toBytesU32(this.size)]); } /** - * Returns a string representation of the CLTypeByteArray. + * Provides a human-readable string representation of the CLTypeByteArray. * @returns A string in the format "ByteArray: size". */ public toString(): string { @@ -35,23 +36,23 @@ export class CLTypeByteArray implements CLType { } /** - * Gets the type ID of the CLTypeByteArray. - * @returns The TypeID for ByteArray. + * Retrieves the unique type identifier (TypeID) for the ByteArray. + * @returns TypeID for ByteArray. */ public getTypeID(): TypeID { return TypeID.ByteArray; } /** - * Gets the name of the CLTypeByteArray. - * @returns The TypeName for ByteArray. + * Retrieves the name of this type as defined in the Casper system. + * @returns TypeName for ByteArray. */ public getName(): TypeName { return TypeName.ByteArray; } /** - * Gets the size of the byte array. + * Gets the fixed size of the byte array. * @returns The size of the byte array. */ public getSize(): number { @@ -59,18 +60,20 @@ export class CLTypeByteArray implements CLType { } /** - * Converts the CLTypeByteArray to a JSON representation. - * @returns An object with a single key-value pair, where the key is "ByteArray" and the value is the size. + * Converts the CLTypeByteArray instance to a JSON-compatible representation. + * The JSON object contains a single key-value pair, where the key is "ByteArray" + * and the value is the size of the array. + * @returns An object with the ByteArray size. */ public toJSON(): { [key: string]: number } { return { [this.getName()]: this.size }; } /** - * Creates a CLTypeByteArray instance from a JSON representation. - * @param source - The JSON representation of the CLTypeByteArray. + * Constructs a CLTypeByteArray instance from a JSON representation. + * @param source - The JSON input containing the size of the ByteArray. * @returns A new CLTypeByteArray instance. - * @throws Will throw an error if the source is not a number. + * @throws Will throw an error if the input type is not a number. */ public static fromJSON(source: any): CLTypeByteArray { if (typeof source !== 'number') { diff --git a/src/types/clvalue/cltype/CLType.ts b/src/types/clvalue/cltype/CLType.ts index e5a96228d..bb0dd1e56 100644 --- a/src/types/clvalue/cltype/CLType.ts +++ b/src/types/clvalue/cltype/CLType.ts @@ -1,15 +1,16 @@ /** - * The size of a 32-bit integer in bytes. + * The byte size of a 32-bit integer. */ export const Int32ByteSize = 4; /** - * The size of a 64-bit integer in bytes. + * The byte size of a 64-bit integer. */ export const Int64ByteSize = 8; /** - * Enumeration of type identifiers used in the CasperLabs type system. + * Enumeration of type identifiers used within the Casper type system. + * Each TypeID uniquely identifies a specific data type. */ export enum TypeID { Bool, @@ -43,7 +44,7 @@ export enum TypeID { export type TypeName = string; /** - * Object containing string constants for type names in the CasperLabs type system. + * Object containing string constants for each type name in the Casper type system. */ export const TypeName = { Bool: 'Bool' as TypeName, @@ -72,51 +73,51 @@ export const TypeName = { }; /** - * Interface representing a CLType in the CasperLabs type system. + * Interface representing a CLType in the Casper type system. */ export interface CLType { /** - * Converts the CLType to its byte representation. + * Converts the CLType instance to its byte representation. * @returns A Uint8Array representing the CLType. */ toBytes(): Uint8Array; /** - * Returns a string representation of the CLType. + * Provides a string representation of the CLType. * @returns A string representation of the CLType. */ toString(): string; /** - * Gets the type ID of the CLType. - * @returns The TypeID of the CLType. + * Retrieves the type ID of the CLType. + * @returns The TypeID associated with the CLType. */ getTypeID(): TypeID; /** - * Gets the name of the CLType. - * @returns The TypeName of the CLType. + * Retrieves the name of the CLType. + * @returns The TypeName associated with the CLType. */ getName(): TypeName; /** - * Converts the CLType to a JSON representation. - * @returns A JSON representation of the CLType. + * Converts the CLType instance to a JSON representation. + * @returns A JSON-compatible representation of the CLType. */ toJSON(): any; } /** - * Represents a simple type in the CasperLabs type system. + * Represents a simple data type in the Casper type system. */ export class SimpleType implements CLType { private readonly typeID: TypeID; private readonly typeName: TypeName; /** - * Constructs a new SimpleType instance. - * @param typeID - The TypeID of the simple type. - * @param name - The TypeName of the simple type. + * Constructs a new instance of the SimpleType class. + * @param typeID - The TypeID for the simple type. + * @param name - The TypeName for the simple type. */ constructor(typeID: TypeID, name: TypeName) { this.typeID = typeID; @@ -132,7 +133,7 @@ export class SimpleType implements CLType { } /** - * Returns a string representation of the SimpleType. + * Provides a string representation of the SimpleType. * @returns The name of the SimpleType. */ toString(): string { @@ -140,23 +141,23 @@ export class SimpleType implements CLType { } /** - * Gets the type ID of the SimpleType. - * @returns The TypeID of the SimpleType. + * Retrieves the type ID of the SimpleType. + * @returns The TypeID for the SimpleType. */ getTypeID(): TypeID { return this.typeID; } /** - * Gets the name of the SimpleType. - * @returns The TypeName of the SimpleType. + * Retrieves the name of the SimpleType. + * @returns The TypeName for the SimpleType. */ getName(): TypeName { return this.typeName; } /** - * Converts the SimpleType to a JSON representation. + * Converts the SimpleType instance to a JSON representation. * @returns The name of the SimpleType as a string. */ toJSON(): string { @@ -165,78 +166,79 @@ export class SimpleType implements CLType { } // Predefined SimpleType instances + /** - * Represents a Boolean type in the CasperLabs type system. + * Represents a Boolean type in the Casper type system. */ export const CLTypeBool = new SimpleType(TypeID.Bool, TypeName.Bool); /** - * Represents a 32-bit signed integer type in the CasperLabs type system. + * Represents a 32-bit signed integer type in the Casper type system. */ export const CLTypeInt32 = new SimpleType(TypeID.I32, TypeName.I32); /** - * Represents a 64-bit signed integer type in the CasperLabs type system. + * Represents a 64-bit signed integer type in the Casper type system. */ export const CLTypeInt64 = new SimpleType(TypeID.I64, TypeName.I64); /** - * Represents an 8-bit unsigned integer type in the CasperLabs type system. + * Represents an 8-bit unsigned integer type in the Casper type system. */ export const CLTypeUInt8 = new SimpleType(TypeID.U8, TypeName.U8); /** - * Represents a 32-bit unsigned integer type in the CasperLabs type system. + * Represents a 32-bit unsigned integer type in the Casper type system. */ export const CLTypeUInt32 = new SimpleType(TypeID.U32, TypeName.U32); /** - * Represents a 64-bit unsigned integer type in the CasperLabs type system. + * Represents a 64-bit unsigned integer type in the Casper type system. */ export const CLTypeUInt64 = new SimpleType(TypeID.U64, TypeName.U64); /** - * Represents a 128-bit unsigned integer type in the CasperLabs type system. + * Represents a 128-bit unsigned integer type in the Casper type system. */ export const CLTypeUInt128 = new SimpleType(TypeID.U128, TypeName.U128); /** - * Represents a 256-bit unsigned integer type in the CasperLabs type system. + * Represents a 256-bit unsigned integer type in the Casper type system. */ export const CLTypeUInt256 = new SimpleType(TypeID.U256, TypeName.U256); /** - * Represents a 512-bit unsigned integer type in the CasperLabs type system. + * Represents a 512-bit unsigned integer type in the Casper type system. */ export const CLTypeUInt512 = new SimpleType(TypeID.U512, TypeName.U512); /** - * Represents a Unit type (similar to void) in the CasperLabs type system. + * Represents a Unit type (similar to void) in the Casper type system. */ export const CLTypeUnit = new SimpleType(TypeID.Unit, TypeName.Unit); /** - * Represents a String type in the CasperLabs type system. + * Represents a String type in the Casper type system. */ export const CLTypeString = new SimpleType(TypeID.String, TypeName.String); /** - * Represents a Key type in the CasperLabs type system. + * Represents a Key type in the Casper type system. */ export const CLTypeKey = new SimpleType(TypeID.Key, TypeName.Key); /** - * Represents a URef (Unforgeable Reference) type in the CasperLabs type system. + * Represents a URef (Unforgeable Reference) type in the Casper type system. */ export const CLTypeUref = new SimpleType(TypeID.URef, TypeName.URef); /** - * Represents an Any type in the CasperLabs type system. + * Represents an Any type in the Casper type system. */ export const CLTypeAny = new SimpleType(TypeID.Any, TypeName.Any); /** - * Represents a PublicKey type in the CasperLabs type system. + * Represents a PublicKey type in the Casper type system. */ export const CLTypePublicKey = new SimpleType( TypeID.PublicKey, diff --git a/src/types/clvalue/cltype/CLTypeRaw.ts b/src/types/clvalue/cltype/CLTypeRaw.ts index 55e0862df..0ffa2342a 100644 --- a/src/types/clvalue/cltype/CLTypeRaw.ts +++ b/src/types/clvalue/cltype/CLTypeRaw.ts @@ -3,29 +3,29 @@ import { CLType } from './CLType'; import { CLTypeParser } from './Parser'; /** - * Represents a raw CLType message that can be parsed into a CLType. - * This class is decorated with typedjson for JSON serialization/deserialization. + * Represents a raw CLType message that can be parsed into a `CLType` instance. + * This class utilizes `typedjson` decorators for JSON serialization and deserialization. */ @jsonObject export class CLTypeRaw { /** - * The raw message string representing a CLType. + * The raw message string representation of a CLType. */ @jsonMember({ constructor: String }) rawMessage: string; /** - * Constructs a new CLTypeRaw instance. - * @param rawMessage - The raw message string representing a CLType. + * Initializes a new instance of the CLTypeRaw class. + * @param rawMessage - A string representing the raw CLType message. */ constructor(rawMessage: string) { this.rawMessage = rawMessage; } /** - * Parses the raw message into a CLType. - * @returns A CLType instance if parsing is successful. - * @throws Error if parsing fails. + * Parses the raw message into a `CLType` object. + * @returns A `CLType` instance if parsing is successful. + * @throws Error if parsing fails, with a descriptive error message. */ parseCLType(): CLType | Error { try { diff --git a/src/types/clvalue/cltype/Dynamic.ts b/src/types/clvalue/cltype/Dynamic.ts index bbb627680..aa6647ccc 100644 --- a/src/types/clvalue/cltype/Dynamic.ts +++ b/src/types/clvalue/cltype/Dynamic.ts @@ -1,16 +1,16 @@ import { TypeID, TypeName, CLType } from './CLType'; /** - * Represents a dynamic CLType in the CasperLabs type system. - * This class allows for runtime determination of CLTypes. + * Represents a dynamic CLType in the Casper type system. + * This class allows for runtime determination of types, enabling dynamic manipulation of CLTypes. */ export class CLTypeDynamic implements CLType { public typeID: TypeID; public inner: CLType; /** - * Constructs a new CLTypeDynamic instance. - * @param typeID - The TypeID of the dynamic type. + * Initializes a new instance of the CLTypeDynamic class. + * @param typeID - The TypeID representing the dynamic type. * @param inner - The inner CLType that this dynamic type represents. */ constructor(typeID: TypeID, inner: CLType) { @@ -19,7 +19,7 @@ export class CLTypeDynamic implements CLType { } /** - * Converts the CLTypeDynamic to its byte representation. + * Converts the CLTypeDynamic instance to its byte representation. * @returns A Uint8Array representing the bytes of the inner CLType. */ public toBytes(): Uint8Array { @@ -27,23 +27,23 @@ export class CLTypeDynamic implements CLType { } /** - * Returns a string representation of the CLTypeDynamic. - * @returns A string representation of the inner CLType. + * Provides a string representation of the CLTypeDynamic. + * @returns A string representing the inner CLType. */ public toString(): string { return this.inner.toString(); } /** - * Gets the type ID of the CLTypeDynamic. - * @returns The TypeID of the dynamic type. + * Retrieves the type ID of the CLTypeDynamic. + * @returns The TypeID associated with this dynamic type. */ public getTypeID(): TypeID { return this.typeID; } /** - * Gets the name of the CLTypeDynamic. + * Retrieves the name of the CLTypeDynamic. * @returns The TypeName of the inner CLType. */ public getName(): TypeName { @@ -51,8 +51,8 @@ export class CLTypeDynamic implements CLType { } /** - * Converts the CLTypeDynamic to a JSON representation. - * @returns The JSON representation of the inner CLType. + * Converts the CLTypeDynamic instance to a JSON-compatible representation. + * @returns A JSON representation of the inner CLType. */ public toJSON(): any { return this.inner.toJSON(); diff --git a/src/types/clvalue/cltype/List.ts b/src/types/clvalue/cltype/List.ts index 0e8470d08..5a2c1ba81 100644 --- a/src/types/clvalue/cltype/List.ts +++ b/src/types/clvalue/cltype/List.ts @@ -1,11 +1,10 @@ import { concat } from '@ethersproject/bytes'; - import { CLType, TypeID, TypeName } from './CLType'; import { CLTypeParser } from './Parser'; /** - * Represents a List type in the CasperLabs type system. - * This class implements the CLType interface for List types. + * Represents a List type in the Casper type system. + * This class implements the CLType interface specifically for List types, allowing lists of elements with a specified type. */ export class CLTypeList implements CLType { /** @@ -14,16 +13,17 @@ export class CLTypeList implements CLType { public elementsType: CLType; /** - * Constructs a new CLTypeList instance. - * @param elementsType - The CLType of elements in the list. + * Initializes a new instance of the CLTypeList class. + * @param elementsType - The CLType of the elements in the list. */ constructor(elementsType: CLType) { this.elementsType = elementsType; } /** - * Converts the CLTypeList to its byte representation. - * @returns A Uint8Array representing the CLTypeList, including its type ID and the bytes of its element type. + * Converts the CLTypeList instance to its byte representation. + * This includes the type ID for List followed by the byte representation of the element type. + * @returns A Uint8Array representing the CLTypeList. */ public toBytes(): Uint8Array { return concat([ @@ -33,7 +33,7 @@ export class CLTypeList implements CLType { } /** - * Returns a string representation of the CLTypeList. + * Provides a string representation of the CLTypeList. * @returns A string in the format "(List of [element type])". */ public toString(): string { @@ -41,15 +41,15 @@ export class CLTypeList implements CLType { } /** - * Gets the type ID of the CLTypeList. - * @returns The TypeID for List. + * Retrieves the type ID of the CLTypeList. + * @returns The TypeID associated with List. */ public getTypeID(): TypeID { return TypeID.List; } /** - * Gets the name of the CLTypeList. + * Retrieves the name of the CLTypeList. * @returns The TypeName for List. */ public getName(): TypeName { @@ -57,8 +57,9 @@ export class CLTypeList implements CLType { } /** - * Converts the CLTypeList to a JSON representation. - * @returns An object with a single key-value pair, where the key is "List" and the value is the JSON representation of the element type. + * Converts the CLTypeList to a JSON-compatible representation. + * The JSON object contains a single key-value pair, where the key is "List" and the value is the JSON representation of the element type. + * @returns A JSON object representing the list type and its element type. */ public toJSON(): { [key: string]: CLType } { return { [this.getName()]: this.elementsType.toJSON() }; @@ -67,7 +68,7 @@ export class CLTypeList implements CLType { /** * Creates a CLTypeList instance from a JSON representation. * @param source - The JSON representation of the CLTypeList. - * @returns A new CLTypeList instance. + * @returns A new CLTypeList instance with the parsed element type. */ public static fromJSON(source: any): CLTypeList { const inner = CLTypeParser.fromInterface(source); diff --git a/src/types/clvalue/cltype/Map.ts b/src/types/clvalue/cltype/Map.ts index dcec5c040..f0196a581 100644 --- a/src/types/clvalue/cltype/Map.ts +++ b/src/types/clvalue/cltype/Map.ts @@ -1,5 +1,4 @@ import { concat } from '@ethersproject/bytes'; - import { TypeID, TypeName, CLType } from './CLType'; import { CLTypeParser } from './Parser'; @@ -9,8 +8,8 @@ import { CLTypeParser } from './Parser'; export const MapJsonParsingError = new Error('map type parsing error'); /** - * Represents a Map type in the CasperLabs type system. - * This class implements the CLType interface for Map types. + * Represents a Map type in the Casper type system. + * This class implements the CLType interface, allowing the use of key-value pairs with specified types. */ export class CLTypeMap implements CLType { /** @@ -24,7 +23,7 @@ export class CLTypeMap implements CLType { public val: CLType; /** - * Constructs a new CLTypeMap instance. + * Initializes a new instance of the CLTypeMap class. * @param keyType - The CLType of the map's keys. * @param valType - The CLType of the map's values. */ @@ -34,8 +33,9 @@ export class CLTypeMap implements CLType { } /** - * Converts the CLTypeMap to its byte representation. - * @returns A Uint8Array representing the CLTypeMap, including its type ID and the bytes of its key and value types. + * Converts the CLTypeMap instance to its byte representation. + * This includes the type ID for Map followed by the byte representations of the key and value types. + * @returns A Uint8Array representing the CLTypeMap. */ public toBytes(): Uint8Array { return concat([ @@ -46,7 +46,7 @@ export class CLTypeMap implements CLType { } /** - * Returns a string representation of the CLTypeMap. + * Provides a string representation of the CLTypeMap. * @returns A string in the format "Map (keyType: valueType)". */ public toString(): string { @@ -54,15 +54,15 @@ export class CLTypeMap implements CLType { } /** - * Gets the type ID of the CLTypeMap. - * @returns The TypeID for Map. + * Retrieves the type ID of the CLTypeMap. + * @returns The TypeID associated with Map. */ public getTypeID(): TypeID { return TypeID.Map; } /** - * Gets the name of the CLTypeMap. + * Retrieves the name of the CLTypeMap. * @returns The TypeName for Map. */ public getName(): TypeName { @@ -70,8 +70,9 @@ export class CLTypeMap implements CLType { } /** - * Converts the CLTypeMap to a JSON representation. - * @returns An object with a "Map" key containing the key and value types. + * Converts the CLTypeMap instance to a JSON-compatible representation. + * The JSON object includes a "Map" key containing the JSON representations of the key and value types. + * @returns A JSON object representing the map type and its key and value types. */ public toJSON(): { Map: { key: CLType; value: CLType } } { return { @@ -84,8 +85,9 @@ export class CLTypeMap implements CLType { /** * Creates a CLTypeMap instance from a JSON representation. + * Parses JSON input to determine the key and value types of the map. * @param source - The JSON representation of the CLTypeMap. - * @returns A new CLTypeMap instance. + * @returns A new CLTypeMap instance with parsed key and value types. * @throws {MapJsonParsingError} If the JSON structure is invalid. */ public static fromJSON(source: any): CLTypeMap { diff --git a/src/types/clvalue/cltype/Option.ts b/src/types/clvalue/cltype/Option.ts index 7bb8bc7cc..8dcd3774b 100644 --- a/src/types/clvalue/cltype/Option.ts +++ b/src/types/clvalue/cltype/Option.ts @@ -1,20 +1,19 @@ import { concat } from '@ethersproject/bytes'; - import { TypeID, TypeName, CLType } from './CLType'; import { CLTypeParser } from './Parser'; /** - * Represents an Option type in the CasperLabs type system. - * This class implements the CLType interface for Option types. + * Represents an Option type in the Casper type system. + * This class implements the CLType interface, allowing for optional values with specified inner types. */ export class CLTypeOption implements CLType { /** - * The inner CLType that this Option can contain. + * The inner CLType that this Option may contain. */ public inner: CLType; /** - * Constructs a new CLTypeOption instance. + * Initializes a new instance of the CLTypeOption class. * @param inner - The CLType of the value that this Option can contain. */ constructor(inner: CLType) { @@ -22,15 +21,16 @@ export class CLTypeOption implements CLType { } /** - * Converts the CLTypeOption to its byte representation. - * @returns A Uint8Array representing the CLTypeOption, including its type ID and the bytes of its inner type. + * Converts the CLTypeOption instance to its byte representation. + * This includes the type ID for Option followed by the byte representation of the inner type. + * @returns A Uint8Array representing the CLTypeOption. */ public toBytes(): Uint8Array { return concat([Uint8Array.from([this.getTypeID()]), this.inner.toBytes()]); } /** - * Returns a string representation of the CLTypeOption. + * Provides a string representation of the CLTypeOption. * @returns A string in the format "(Option: innerType)". */ public toString(): string { @@ -38,15 +38,15 @@ export class CLTypeOption implements CLType { } /** - * Gets the type ID of the CLTypeOption. - * @returns The TypeID for Option. + * Retrieves the type ID of the CLTypeOption. + * @returns The TypeID associated with Option. */ public getTypeID(): TypeID { return TypeID.Option; } /** - * Gets the name of the CLTypeOption. + * Retrieves the name of the CLTypeOption. * @returns The TypeName for Option. */ public getName(): TypeName { @@ -54,8 +54,9 @@ export class CLTypeOption implements CLType { } /** - * Converts the CLTypeOption to a JSON representation. - * @returns An object with a single key-value pair, where the key is "Option" and the value is the JSON representation of the inner type. + * Converts the CLTypeOption instance to a JSON-compatible representation. + * The JSON object includes a single key-value pair, where the key is "Option" and the value is the JSON representation of the inner type. + * @returns A JSON object representing the option type and its inner type. */ public toJSON(): { [key: string]: CLType } { return { [this.getName()]: this.inner.toJSON() }; @@ -63,8 +64,9 @@ export class CLTypeOption implements CLType { /** * Creates a CLTypeOption instance from a JSON representation. + * Parses JSON input to determine the inner type of the option. * @param source - The JSON representation of the CLTypeOption. - * @returns A new CLTypeOption instance. + * @returns A new CLTypeOption instance with the parsed inner type. */ public static fromJSON(source: any): CLTypeOption { const inner = CLTypeParser.fromInterface(source); diff --git a/src/types/clvalue/cltype/Parser.ts b/src/types/clvalue/cltype/Parser.ts index 67b2db7ba..0b0f05f82 100644 --- a/src/types/clvalue/cltype/Parser.ts +++ b/src/types/clvalue/cltype/Parser.ts @@ -29,7 +29,8 @@ import { CLTypeTuple3 } from './Tuple3'; import { IResultWithBytes } from '../CLValue'; /** - * A utility class for parsing CLTypes from various formats. + * A utility class for parsing various CLTypes from different formats, such as JSON, strings, and bytes. + * This class includes static methods for handling both simple and complex types, along with error handling for unsupported or unrecognized formats. */ export class CLTypeParser { /** @@ -131,9 +132,9 @@ export class CLTypeParser { } /** - * Parses a CLType from an ArrayBuffer. - * @param buf - The ArrayBuffer to parse. - * @returns The parsed CLType. + * Parses a CLType from a Uint8Array. + * @param bytes - The Uint8Array to parse. + * @returns An object containing the parsed CLType and the remaining bytes. * @throws BufferConstructorNotDetectedError if the type is not recognized. */ static matchBytesToCLType(bytes: Uint8Array): IResultWithBytes { @@ -165,19 +166,13 @@ export class CLTypeParser { result: optionInner, bytes: optionBytes } = CLTypeParser.matchBytesToCLType(remainder); - return { - result: new CLTypeOption(optionInner), - bytes: optionBytes - }; + return { result: new CLTypeOption(optionInner), bytes: optionBytes }; case TypeID.List: const { result: listInner, bytes: listBytes } = CLTypeParser.matchBytesToCLType(remainder); - return { - result: new CLTypeList(listInner), - bytes: listBytes - }; + return { result: new CLTypeList(listInner), bytes: listBytes }; case TypeID.ByteArray: const { result: byteArrayInner, @@ -201,7 +196,6 @@ export class CLTypeParser { result: innerErr, bytes: errBytes } = CLTypeParser.matchBytesToCLType(resultBytes); - return { result: new CLTypeResult(innerOk, innerErr), bytes: errBytes }; case TypeID.Map: const { @@ -217,7 +211,6 @@ export class CLTypeParser { result: val, bytes: valBytes } = CLTypeParser.matchBytesToCLType(keyBytes); - return { result: new CLTypeMap(key, val), bytes: valBytes }; case TypeID.Tuple1: const { @@ -239,7 +232,6 @@ export class CLTypeParser { result: innerType2Res, bytes: innerType2Bytes } = CLTypeParser.matchBytesToCLType(innerType1Bytes); - return { result: new CLTypeTuple2(innerType1Res, innerType2Res), bytes: innerType2Bytes @@ -251,7 +243,7 @@ export class CLTypeParser { } = CLTypeParser.matchBytesToCLType(remainder); if (!innerType1Byte) { - throw new Error('Missing second tuple type bytes in CLTuple2Type'); + throw new Error('Missing second tuple type bytes in CLTuple3Type'); } const { @@ -260,14 +252,13 @@ export class CLTypeParser { } = CLTypeParser.matchBytesToCLType(innerType1Byte); if (!innerType2Byte) { - throw new Error('Missing third tuple type bytes in CLTuple2Type'); + throw new Error('Missing third tuple type bytes in CLTuple3Type'); } const { result: innerType3, bytes: innerType3Byte } = CLTypeParser.matchBytesToCLType(innerType2Byte); - return { result: new CLTypeTuple3(innerType1, innerType2, innerType3), bytes: innerType3Byte @@ -286,7 +277,6 @@ export class CLTypeParser { if (typeof rawData === 'string') { return CLTypeParser.getSimpleTypeByName(rawData as TypeName); } - return CLTypeParser.fromComplexStruct(rawData); } diff --git a/src/types/clvalue/cltype/Result.ts b/src/types/clvalue/cltype/Result.ts index 3c03b3ae6..f7080b4e7 100644 --- a/src/types/clvalue/cltype/Result.ts +++ b/src/types/clvalue/cltype/Result.ts @@ -1,5 +1,4 @@ import { concat } from '@ethersproject/bytes'; - import { TypeID, TypeName, CLType } from './CLType'; import { CLTypeParser } from './Parser'; @@ -11,8 +10,8 @@ export const ErrInvalidResultJsonFormat = new Error( ); /** - * Represents a Result type in the CasperLabs type system. - * This class implements the CLType interface for Result types. + * Represents a Result type in the Casper type system. + * This class implements the CLType interface, allowing for Result types with defined Ok and Err types. */ export class CLTypeResult implements CLType { /** @@ -26,7 +25,7 @@ export class CLTypeResult implements CLType { innerErr: CLType; /** - * Constructs a new CLTypeResult instance. + * Initializes a new instance of the CLTypeResult class. * @param innerOk - The CLType of the Ok value. * @param innerErr - The CLType of the Err value. */ @@ -36,8 +35,9 @@ export class CLTypeResult implements CLType { } /** - * Converts the CLTypeResult to its byte representation. - * @returns A Uint8Array representing the CLTypeResult, including its type ID and the bytes of its Ok and Err types. + * Converts the CLTypeResult instance to its byte representation. + * This includes the type ID for Result, followed by the byte representations of the Ok and Err types. + * @returns A Uint8Array representing the CLTypeResult. */ public toBytes(): Uint8Array { return concat([ @@ -48,7 +48,7 @@ export class CLTypeResult implements CLType { } /** - * Returns a string representation of the CLTypeResult. + * Provides a string representation of the CLTypeResult. * @returns A string in the format "(Result: Ok(okType), Err(errType))". */ public toString(): string { @@ -56,15 +56,15 @@ export class CLTypeResult implements CLType { } /** - * Gets the type ID of the CLTypeResult. - * @returns The TypeID for Result. + * Retrieves the type ID of the CLTypeResult. + * @returns The TypeID associated with Result. */ public getTypeID(): TypeID { return TypeID.Result; } /** - * Gets the name of the CLTypeResult. + * Retrieves the name of the CLTypeResult. * @returns The TypeName for Result. */ public getName(): TypeName { @@ -72,8 +72,9 @@ export class CLTypeResult implements CLType { } /** - * Converts the CLTypeResult to a JSON representation. - * @returns An object with a "Result" key containing the Ok and Err types. + * Converts the CLTypeResult instance to a JSON-compatible representation. + * The JSON object includes a "Result" key containing the JSON representations of the Ok and Err types. + * @returns A JSON object representing the Result type and its Ok and Err types. */ public toJSON(): { [key: string]: { ok: CLType; err: CLType } } { return { @@ -86,8 +87,9 @@ export class CLTypeResult implements CLType { /** * Creates a CLTypeResult instance from a JSON representation. + * Parses JSON input to determine the Ok and Err types for the Result. * @param source - The JSON representation of the CLTypeResult. - * @returns A new CLTypeResult instance. + * @returns A new CLTypeResult instance with parsed Ok and Err types. * @throws {ErrInvalidResultJsonFormat} If the JSON structure is invalid. */ public static fromJSON(source: any): CLTypeResult { diff --git a/src/types/clvalue/cltype/Tuple1.ts b/src/types/clvalue/cltype/Tuple1.ts index 0e3dc49a3..c25bf997a 100644 --- a/src/types/clvalue/cltype/Tuple1.ts +++ b/src/types/clvalue/cltype/Tuple1.ts @@ -1,11 +1,10 @@ import { concat } from '@ethersproject/bytes'; - import { TypeID, TypeName, CLType } from './CLType'; import { CLTypeParser } from './Parser'; /** - * Represents a Tuple1 type in the CasperLabs type system. - * This class implements the CLType interface for Tuple1 types, which are tuples containing a single element. + * Represents a Tuple1 type in the Casper type system. + * This class implements the CLType interface for tuples containing a single element. */ export class CLTypeTuple1 implements CLType { /** @@ -14,7 +13,7 @@ export class CLTypeTuple1 implements CLType { inner: CLType; /** - * Constructs a new CLTypeTuple1 instance. + * Initializes a new instance of the CLTypeTuple1 class. * @param inner - The CLType of the single element in the Tuple1. */ constructor(inner: CLType) { @@ -22,15 +21,16 @@ export class CLTypeTuple1 implements CLType { } /** - * Converts the CLTypeTuple1 to its byte representation. - * @returns A Uint8Array representing the CLTypeTuple1, including its type ID and the bytes of its inner type. + * Converts the CLTypeTuple1 instance to its byte representation. + * This includes the type ID for Tuple1 followed by the byte representation of the inner type. + * @returns A Uint8Array representing the CLTypeTuple1. */ public toBytes(): Uint8Array { return concat([Uint8Array.from([this.getTypeID()]), this.inner.toBytes()]); } /** - * Returns a string representation of the CLTypeTuple1. + * Provides a string representation of the CLTypeTuple1. * @returns A string in the format "Tuple1 (innerType)". */ public toString(): string { @@ -38,15 +38,15 @@ export class CLTypeTuple1 implements CLType { } /** - * Gets the type ID of the CLTypeTuple1. - * @returns The TypeID for Tuple1. + * Retrieves the type ID of the CLTypeTuple1. + * @returns The TypeID associated with Tuple1. */ public getTypeID(): TypeID { return TypeID.Tuple1; } /** - * Gets the name of the CLTypeTuple1. + * Retrieves the name of the CLTypeTuple1. * @returns The TypeName for Tuple1. */ public getName(): TypeName { @@ -54,8 +54,9 @@ export class CLTypeTuple1 implements CLType { } /** - * Converts the CLTypeTuple1 to a JSON representation. - * @returns An object with a "Tuple1" key containing an array with the inner type. + * Converts the CLTypeTuple1 instance to a JSON-compatible representation. + * The JSON object contains a "Tuple1" key with an array that includes the inner type. + * @returns A JSON object representing the Tuple1 type and its inner type. */ public toJSON(): { [key: string]: CLType[] } { return { [this.getName()]: [this.inner.toJSON()] }; @@ -63,9 +64,10 @@ export class CLTypeTuple1 implements CLType { /** * Creates a CLTypeTuple1 instance from a JSON representation. + * Parses JSON input to determine the inner type for the Tuple1. * @param source - The JSON representation of the CLTypeTuple1. - * @returns A new CLTypeTuple1 instance. - * @throws Error if the JSON structure is invalid or the inner type is invalid. + * @returns A new CLTypeTuple1 instance with the parsed inner type. + * @throws Error if the JSON structure is invalid or the inner type is not correctly specified. */ public static fromJSON(source: any): CLTypeTuple1 { if (!Array.isArray(source) || source.length !== 1) { diff --git a/src/types/clvalue/cltype/Tuple2.ts b/src/types/clvalue/cltype/Tuple2.ts index 8ca722ac3..0405f402e 100644 --- a/src/types/clvalue/cltype/Tuple2.ts +++ b/src/types/clvalue/cltype/Tuple2.ts @@ -1,11 +1,10 @@ import { concat } from '@ethersproject/bytes'; - import { TypeID, TypeName, CLType } from './CLType'; import { CLTypeParser } from './Parser'; /** - * Represents a Tuple2 type in the CasperLabs type system. - * This class implements the CLType interface for Tuple2 types, which are tuples containing two elements. + * Represents a Tuple2 type in the Casper type system. + * This class implements the CLType interface for tuples containing two elements. */ export class CLTypeTuple2 implements CLType { /** @@ -19,7 +18,7 @@ export class CLTypeTuple2 implements CLType { inner2: CLType; /** - * Constructs a new CLTypeTuple2 instance. + * Initializes a new instance of the CLTypeTuple2 class. * @param inner1 - The CLType of the first element in the Tuple2. * @param inner2 - The CLType of the second element in the Tuple2. */ @@ -29,8 +28,9 @@ export class CLTypeTuple2 implements CLType { } /** - * Converts the CLTypeTuple2 to its byte representation. - * @returns A Uint8Array representing the CLTypeTuple2, including its type ID and the bytes of its inner types. + * Converts the CLTypeTuple2 instance to its byte representation. + * This includes the type ID for Tuple2 followed by the byte representations of both inner types. + * @returns A Uint8Array representing the CLTypeTuple2. */ public toBytes(): Uint8Array { return concat([ @@ -41,7 +41,7 @@ export class CLTypeTuple2 implements CLType { } /** - * Returns a string representation of the CLTypeTuple2. + * Provides a string representation of the CLTypeTuple2. * @returns A string in the format "Tuple2 (innerType1, innerType2)". */ public toString(): string { @@ -49,15 +49,15 @@ export class CLTypeTuple2 implements CLType { } /** - * Gets the type ID of the CLTypeTuple2. - * @returns The TypeID for Tuple2. + * Retrieves the type ID of the CLTypeTuple2. + * @returns The TypeID associated with Tuple2. */ public getTypeID(): TypeID { return TypeID.Tuple2; } /** - * Gets the name of the CLTypeTuple2. + * Retrieves the name of the CLTypeTuple2. * @returns The TypeName for Tuple2. */ public getName(): TypeName { @@ -65,8 +65,9 @@ export class CLTypeTuple2 implements CLType { } /** - * Converts the CLTypeTuple2 to a JSON representation. - * @returns An object with a "Tuple2" key containing an array with the two inner types. + * Converts the CLTypeTuple2 instance to a JSON-compatible representation. + * The JSON object contains a "Tuple2" key with an array including the two inner types. + * @returns A JSON object representing the Tuple2 type and its inner types. */ public toJSON(): { [key: string]: CLType[] } { return { [this.getName()]: [this.inner1.toJSON(), this.inner2.toJSON()] }; @@ -74,9 +75,10 @@ export class CLTypeTuple2 implements CLType { /** * Creates a CLTypeTuple2 instance from a JSON representation. + * Parses JSON input to determine the two inner types for the Tuple2. * @param source - The JSON representation of the CLTypeTuple2. - * @returns A new CLTypeTuple2 instance. - * @throws Error if the JSON structure is invalid or the inner types are invalid. + * @returns A new CLTypeTuple2 instance with the parsed inner types. + * @throws Error if the JSON structure is invalid or the inner types are not correctly specified. */ public static fromJSON(source: any): CLTypeTuple2 { if (!Array.isArray(source) || source.length !== 2) { diff --git a/src/types/clvalue/cltype/Tuple3.ts b/src/types/clvalue/cltype/Tuple3.ts index b96acd457..8528fb7f1 100644 --- a/src/types/clvalue/cltype/Tuple3.ts +++ b/src/types/clvalue/cltype/Tuple3.ts @@ -1,11 +1,10 @@ import { concat } from '@ethersproject/bytes'; - import { TypeID, TypeName, CLType } from './CLType'; import { CLTypeParser } from './Parser'; /** - * Represents a Tuple3 type in the CasperLabs type system. - * This class implements the CLType interface for Tuple3 types, which are tuples containing three elements. + * Represents a Tuple3 type in the Casper type system. + * This class implements the CLType interface for tuples containing three elements. */ export class CLTypeTuple3 implements CLType { /** @@ -24,7 +23,7 @@ export class CLTypeTuple3 implements CLType { inner3: CLType; /** - * Constructs a new CLTypeTuple3 instance. + * Initializes a new instance of the CLTypeTuple3 class. * @param inner1 - The CLType of the first element in the Tuple3. * @param inner2 - The CLType of the second element in the Tuple3. * @param inner3 - The CLType of the third element in the Tuple3. @@ -36,8 +35,9 @@ export class CLTypeTuple3 implements CLType { } /** - * Converts the CLTypeTuple3 to its byte representation. - * @returns A Uint8Array representing the CLTypeTuple3, including its type ID and the bytes of its inner types. + * Converts the CLTypeTuple3 instance to its byte representation. + * This includes the type ID for Tuple3 followed by the byte representations of the three inner types. + * @returns A Uint8Array representing the CLTypeTuple3. */ public toBytes(): Uint8Array { return concat([ @@ -49,7 +49,7 @@ export class CLTypeTuple3 implements CLType { } /** - * Returns a string representation of the CLTypeTuple3. + * Provides a string representation of the CLTypeTuple3. * @returns A string in the format "Tuple3 (innerType1, innerType2, innerType3)". */ public toString(): string { @@ -57,15 +57,15 @@ export class CLTypeTuple3 implements CLType { } /** - * Gets the type ID of the CLTypeTuple3. - * @returns The TypeID for Tuple3. + * Retrieves the type ID of the CLTypeTuple3. + * @returns The TypeID associated with Tuple3. */ public getTypeID(): TypeID { return TypeID.Tuple3; } /** - * Gets the name of the CLTypeTuple3. + * Retrieves the name of the CLTypeTuple3. * @returns The TypeName for Tuple3. */ public getName(): TypeName { @@ -73,8 +73,9 @@ export class CLTypeTuple3 implements CLType { } /** - * Converts the CLTypeTuple3 to a JSON representation. - * @returns An object with a "Tuple3" key containing an array with the three inner types. + * Converts the CLTypeTuple3 instance to a JSON-compatible representation. + * The JSON object contains a "Tuple3" key with an array that includes the three inner types. + * @returns A JSON object representing the Tuple3 type and its inner types. */ public toJSON(): { [key: string]: CLType[] } { return { @@ -88,9 +89,10 @@ export class CLTypeTuple3 implements CLType { /** * Creates a CLTypeTuple3 instance from a JSON representation. + * Parses JSON input to determine the three inner types for the Tuple3. * @param source - The JSON representation of the CLTypeTuple3. - * @returns A new CLTypeTuple3 instance. - * @throws Error if the JSON structure is invalid or the inner types are invalid. + * @returns A new CLTypeTuple3 instance with the parsed inner types. + * @throws Error if the JSON structure is invalid or the inner types are not correctly specified. */ public static fromJSON(source: any): CLTypeTuple3 { if (!Array.isArray(source) || source.length !== 3) { @@ -101,6 +103,11 @@ export class CLTypeTuple3 implements CLType { const inner1 = CLTypeParser.fromInterface(source[0]); const inner2 = CLTypeParser.fromInterface(source[1]); const inner3 = CLTypeParser.fromInterface(source[2]); + + if (!inner1 || !inner2 || !inner3) { + throw new Error('Invalid inner types in Tuple3 JSON format'); + } + return new CLTypeTuple3(inner1, inner2, inner3); } } diff --git a/src/types/key/Account.ts b/src/types/key/Account.ts index 6c261a7ef..279ca926a 100644 --- a/src/types/key/Account.ts +++ b/src/types/key/Account.ts @@ -3,19 +3,20 @@ import { Hash } from './Hash'; /** * Represents an account hash in the Casper network. - * Extends the Hash class with additional functionality specific to account hashes. + * This class extends the `Hash` class, adding specific methods and properties for managing account hashes, which include special prefixes. */ @jsonObject export class AccountHash extends Hash { /** - * The prefix of the original hash string, if any. + * Stores the prefix of the original hash string if it had one. + * Possible prefixes are `"00"` or `"account-hash-"`. */ private originPrefix: string; /** - * Creates a new AccountHash instance. - * @param hash - The underlying Hash object. - * @param originPrefix - The prefix of the original hash string, if any. + * Initializes a new AccountHash instance. + * @param hash - The underlying Hash object containing the raw bytes of the account hash. + * @param originPrefix - Optional. The prefix of the original hash string (default is an empty string). */ constructor(hash: Hash, originPrefix = '') { super(hash.toBytes()); @@ -23,9 +24,10 @@ export class AccountHash extends Hash { } /** - * Creates an AccountHash instance from a string representation. + * Parses a string representation of an account hash and creates an AccountHash instance. + * Recognizes and preserves any prefix, either `"00"` or `"account-hash-"`. * @param source - The string representation of the account hash. - * @returns A new AccountHash instance. + * @returns A new AccountHash instance containing the parsed hash and prefix. */ public static fromString(source: string): AccountHash { let originPrefix = ''; @@ -41,26 +43,28 @@ export class AccountHash extends Hash { } /** - * Returns the account hash as a prefixed string. - * @returns The account hash with the 'account-hash-' prefix. + * Returns the account hash as a string, prefixed with `"account-hash-"`. + * This is useful for displaying the hash in a format recognized by the Casper network. + * @returns The account hash as a prefixed string. */ public toPrefixedString(): string { return PrefixNameAccount + this.toHex(); } /** - * Converts the AccountHash to its JSON representation. - * @returns A string representation of the AccountHash, including the original prefix. + * Serializes the AccountHash to its JSON representation. + * The JSON representation includes the original prefix if present. + * @returns A string representation of the AccountHash for JSON serialization. */ public toJSON(): string { return this.originPrefix + this.toHex(); } /** - * Creates an AccountHash instance from its JSON representation. + * Deserializes an AccountHash instance from a JSON string representation. * @param data - The JSON string representation of the AccountHash. - * @returns A new AccountHash instance. - * @throws {Error} If the input is not a valid JSON string. + * @returns A new AccountHash instance created from the JSON string. + * @throws {Error} Throws an error if the input is not a valid JSON string. */ public static fromJSON(data: string): AccountHash { return AccountHash.fromString(data); @@ -68,6 +72,6 @@ export class AccountHash extends Hash { } /** - * The prefix used for account hash strings. + * Constant defining the prefix used for account hash strings in the Casper network. */ const PrefixNameAccount = 'account-hash-'; diff --git a/src/types/key/AddressableEntity.ts b/src/types/key/AddressableEntity.ts index 69df25b0f..628e17786 100644 --- a/src/types/key/AddressableEntity.ts +++ b/src/types/key/AddressableEntity.ts @@ -8,20 +8,21 @@ const PrefixAddressableEntity = 'addressable-entity-'; /** * Represents an addressable entity hash in the Casper network. - * Extends the Hash class with additional functionality specific to addressable entity hashes. + * This class extends the `Hash` class to include a prefix indicating it is an addressable entity, adding specific methods and properties for managing such hashes. */ @jsonObject export class AddressableEntityHash extends Hash { /** - * The prefix of the original hash string, if any. + * Stores the prefix of the original hash string if it had one. + * Defaults to `addressable-entity-` if not provided. */ @jsonMember({ constructor: String }) originPrefix: string; /** - * Creates a new AddressableEntityHash instance. - * @param hashBytes - The byte array representing the hash. - * @param originPrefix - The prefix of the original hash string. Defaults to PrefixAddressableEntity. + * Initializes a new AddressableEntityHash instance. + * @param hashBytes - The byte array representing the hash value. + * @param originPrefix - Optional. The prefix of the original hash string. Defaults to `addressable-entity-`. */ constructor( hashBytes: Uint8Array, @@ -32,8 +33,9 @@ export class AddressableEntityHash extends Hash { } /** - * Creates an AddressableEntityHash instance from a hexadecimal string. - * @param source - The hexadecimal string representation of the hash. + * Parses a hexadecimal string to create an AddressableEntityHash instance. + * Checks if the input string starts with the `addressable-entity-` prefix, removing it if present. + * @param source - The hexadecimal string representation of the hash, with or without the prefix. * @returns A new AddressableEntityHash instance. */ static fromHex(source: string): AddressableEntityHash { @@ -46,24 +48,26 @@ export class AddressableEntityHash extends Hash { /** * Returns the addressable entity hash as a prefixed string. - * @returns The hash with the 'addressable-entity-' prefix. + * Always includes the `addressable-entity-` prefix. + * @returns The prefixed hexadecimal string representation of the hash. */ toPrefixedString(): string { return `${PrefixAddressableEntity}${this.toHex()}`; } /** - * Converts the AddressableEntityHash to its JSON representation. - * @returns A string representation of the AddressableEntityHash, including the original prefix. + * Serializes the AddressableEntityHash to its JSON representation. + * The JSON representation includes the original prefix if it was specified. + * @returns A string combining the prefix (if present) and the hexadecimal representation of the hash. */ toJSON(): string { return `${this.originPrefix}${this.toHex()}`; } /** - * Creates an AddressableEntityHash instance from its JSON representation. - * @param json - The JSON string representation of the AddressableEntityHash. - * @returns A new AddressableEntityHash instance. + * Deserializes an AddressableEntityHash instance from a JSON string representation. + * @param json - The JSON string representation of the AddressableEntityHash, with or without the prefix. + * @returns A new AddressableEntityHash instance created from the JSON string. */ static fromJSON(json: string): AddressableEntityHash { return AddressableEntityHash.fromHex(json); diff --git a/src/types/key/BalanceHoldAddr.ts b/src/types/key/BalanceHoldAddr.ts index 46e081bbe..bec31a8b7 100644 --- a/src/types/key/BalanceHoldAddr.ts +++ b/src/types/key/BalanceHoldAddr.ts @@ -33,6 +33,9 @@ export function getBalanceHoldAddrTag(tag: number): BalanceHoldAddrTag { throw new BalanceHoldAddrTagError('Invalid BalanceHoldAddrTag'); } +/** + * Constants related to the structure of a BalanceHoldAddr. + */ const ByteHashLen = 32; const BlockTypeBytesLen = 8; const PrefixNameBalanceHold = 'balance-hold-'; @@ -40,18 +43,18 @@ const PrefixNameBalanceHold = 'balance-hold-'; type URefAddr = Uint8Array; /** - * Represents a hold on a balance. + * Represents a hold on a balance, including the address of the purse and the block time. */ @jsonObject export class Hold { /** - * The address of the purse. + * The address of the purse on which the hold is placed. */ @jsonMember({ name: 'PurseAddr', constructor: Uint8Array }) purseAddr: URefAddr; /** - * The block time of the hold. + * The block time at which the hold was created. */ @jsonMember({ name: 'BlockTime', @@ -68,18 +71,18 @@ export class Hold { } /** - * Represents a balance hold address. + * Represents an address holding a balance, categorized by either 'Gas' or 'Processing' type. */ @jsonObject export class BalanceHoldAddr { /** - * The gas hold, if any. + * The hold categorized as 'Gas', if any. */ @jsonMember({ name: 'Gas', constructor: Hold }) gas?: Hold; /** - * The processing hold, if any. + * The hold categorized as 'Processing', if any. */ @jsonMember({ name: 'Processing', constructor: Hold }) processing?: Hold; @@ -90,7 +93,7 @@ export class BalanceHoldAddr { } /** - * Creates a BalanceHoldAddr from a string representation. + * Parses a string representation of a BalanceHoldAddr and returns a new instance. * @param source - The string representation of the BalanceHoldAddr. * @returns A new BalanceHoldAddr instance. */ @@ -102,8 +105,8 @@ export class BalanceHoldAddr { } /** - * Returns the prefixed string representation of the BalanceHoldAddr. - * @returns The prefixed string representation. + * Converts the BalanceHoldAddr to a prefixed string, using 'balance-hold-' as the prefix. + * @returns The prefixed string representation of the BalanceHoldAddr. */ toPrefixedString(): string { const bytes = this.toBytes(); @@ -111,8 +114,9 @@ export class BalanceHoldAddr { } /** - * Converts the BalanceHoldAddr to its byte representation. - * @returns The byte representation of the BalanceHoldAddr. + * Serializes the BalanceHoldAddr to its byte representation. + * Includes a byte for the hold type, the purse address, and an 8-byte block time. + * @returns The serialized byte representation of the BalanceHoldAddr. */ toBytes(): Uint8Array { let hold = this.gas; @@ -137,8 +141,8 @@ export class BalanceHoldAddr { } /** - * Creates a BalanceHoldAddr from its byte representation. - * @param bytes - The byte representation of the BalanceHoldAddr. + * Deserializes a BalanceHoldAddr from a byte array. + * @param bytes - The byte array containing the BalanceHoldAddr data. * @returns A new BalanceHoldAddr instance. * @throws Error if the byte format is invalid. * @throws BalanceHoldAddrTagError if the hold type is unexpected. @@ -170,8 +174,8 @@ export class BalanceHoldAddr { } /** - * Creates a BalanceHoldAddr from its JSON representation. - * @param json - The JSON string representation of the BalanceHoldAddr. + * Parses a JSON string representation of a BalanceHoldAddr. + * @param json - The JSON string. * @returns A new BalanceHoldAddr instance. */ public static fromJSON(json: string): BalanceHoldAddr { @@ -179,7 +183,7 @@ export class BalanceHoldAddr { } /** - * Converts the BalanceHoldAddr to its JSON representation. + * Serializes the BalanceHoldAddr to its JSON string representation. * @returns The JSON string representation of the BalanceHoldAddr. */ public toJSON(): string { diff --git a/src/types/key/BidAddr.ts b/src/types/key/BidAddr.ts index 6ee12fe4e..26433e767 100644 --- a/src/types/key/BidAddr.ts +++ b/src/types/key/BidAddr.ts @@ -6,6 +6,7 @@ import { IResultWithBytes } from '../clvalue'; /** * Enum representing the types of bid addresses. + * Each type corresponds to a unique tag value that identifies the specific type of bid address. */ export enum BidAddrTag { Unified = 0, @@ -26,14 +27,14 @@ export const ErrUnexpectedBidAddrTagInBidAddr = new Error( export const ErrInvalidBidAddrFormat = new Error('invalid BidAddr format'); /** - * Utility class for BidAddrTag operations. + * Utility class for handling operations related to BidAddrTag. */ export class BidAddrTagUtils { /** * Converts a byte to a BidAddrTag. - * @param tag - The byte to convert. + * @param tag - The byte value to convert. * @returns The corresponding BidAddrTag. - * @throws {ErrInvalidBidAddrTag} If the byte doesn't correspond to a valid BidAddrTag. + * @throws {ErrInvalidBidAddrTag} If the byte doesn't match a valid BidAddrTag. */ static fromByte(tag: number): BidAddrTag { const addrTag = tag as BidAddrTag; @@ -52,8 +53,12 @@ export class BidAddrTagUtils { const UnifiedOrValidatorAddrLen = 33; const CreditAddrLen = 41; +/** + * Represents information for a delegator in a Delegator BidAddr. + */ @jsonObject export class DelegatorInfo { + /** The validator hash associated with this delegator. */ @jsonMember({ name: 'validator', constructor: Hash, @@ -62,6 +67,7 @@ export class DelegatorInfo { }) validator: Hash; + /** The delegator's hash. */ @jsonMember({ name: 'delegator', constructor: Hash, @@ -71,8 +77,12 @@ export class DelegatorInfo { delegator: Hash; } +/** + * Represents credit information within a Credit BidAddr. + */ @jsonObject export class CreditInfo { + /** The validator associated with this credit. */ @jsonMember({ name: 'validator', constructor: Hash, @@ -81,33 +91,34 @@ export class CreditInfo { }) validator: Hash; + /** The era ID for this credit. */ @jsonMember({ name: 'eraId', constructor: Number }) eraId: number; } /** - * Represents a bid address in the system. + * Represents a bid address, which can store information for unified, validator, delegator, or credit types. */ @jsonObject export class BidAddr { - /** The unified hash, if this is a unified bid address. */ + /** The unified hash if this is a unified bid address. */ @jsonMember({ name: 'Unified', constructor: Hash }) unified?: Hash; - /** The validator hash, if this is a validator bid address. */ + /** The validator hash if this is a validator bid address. */ @jsonMember({ name: 'Validator', constructor: Hash }) validator?: Hash; - /** The delegator information, if this is a delegator bid address. */ + /** The delegator information if this is a delegator bid address. */ @jsonMember({ name: 'Delegator', constructor: DelegatorInfo }) delegator?: DelegatorInfo; - /** The credit information, if this is a credit bid address. */ + /** The credit information if this is a credit bid address. */ @jsonMember({ name: 'Credit', constructor: CreditInfo }) credit?: CreditInfo; /** - * Creates a new BidAddr instance. + * Constructs a new BidAddr instance. * @param unified - The unified hash. * @param validator - The validator hash. * @param delegator - The delegator information. diff --git a/src/types/key/BlockGlobalAddr.ts b/src/types/key/BlockGlobalAddr.ts index 9d9eef1e1..b3fb6e345 100644 --- a/src/types/key/BlockGlobalAddr.ts +++ b/src/types/key/BlockGlobalAddr.ts @@ -10,7 +10,7 @@ export enum BlockGlobalAddrTag { } /** - * Custom error class for BlockGlobalAddrTag related errors. + * Custom error class for errors related to BlockGlobalAddrTag. */ export class BlockGlobalAddrTagError extends Error { constructor(message: string) { @@ -40,7 +40,7 @@ const MessageCountPrefix = 'message-count-'; const PrefixNameBlockGlobal = 'block-global-'; /** - * Represents a block global address in the system. + * Represents a block global address within the system, supporting both block time and message count addresses. */ @jsonObject export class BlockGlobalAddr { @@ -57,9 +57,9 @@ export class BlockGlobalAddr { messageCount?: object; /** - * Creates a new BlockGlobalAddr instance. - * @param blockTime - The block time object. - * @param messageCount - The message count object. + * Constructs a new BlockGlobalAddr instance. + * @param blockTime - Optional parameter for the block time object. + * @param messageCount - Optional parameter for the message count object. */ constructor(blockTime?: object, messageCount?: object) { this.blockTime = blockTime; @@ -70,7 +70,7 @@ export class BlockGlobalAddr { * Creates a BlockGlobalAddr from a string representation. * @param source - The string representation of the block global address. * @returns A new BlockGlobalAddr instance. - * @throws Error if the format is invalid. + * @throws Error if the format does not match known block global address types. */ static fromString(source: string): BlockGlobalAddr { if (source.startsWith(BlockTimePrefix)) { @@ -83,7 +83,7 @@ export class BlockGlobalAddr { /** * Returns a prefixed string representation of the BlockGlobalAddr. - * @returns The prefixed string representation. + * @returns A prefixed string that includes the block global address type and a default hash value. */ toPrefixedString(): string { const prefix = this.blockTime ? BlockTimePrefix : MessageCountPrefix; @@ -92,10 +92,10 @@ export class BlockGlobalAddr { } /** - * Creates a BlockGlobalAddr from a byte array. - * @param bytes - The byte array. - * @returns A new BlockGlobalAddr instance. - * @throws Error if the BlockGlobalAddr type is unexpected. + * Creates a BlockGlobalAddr from a byte array representation. + * @param bytes - The byte array containing the tag for the block global address type. + * @returns An instance of BlockGlobalAddr representing the given type. + * @throws Error if the byte array tag does not match any known BlockGlobalAddr type. */ static fromBytes(bytes: Uint8Array): IResultWithBytes { const tagByte = bytes[0]; @@ -111,8 +111,8 @@ export class BlockGlobalAddr { } /** - * Converts the BlockGlobalAddr to a byte array. - * @returns The byte array representation of the BlockGlobalAddr. + * Converts the BlockGlobalAddr to a byte array representation. + * @returns A Uint8Array containing the byte tag representing the block global address type. */ toBytes(): Uint8Array { const tag = this.messageCount @@ -122,8 +122,8 @@ export class BlockGlobalAddr { } /** - * Creates a BlockGlobalAddr from its JSON representation. - * @param json - The JSON string. + * Creates a BlockGlobalAddr from a JSON string representation. + * @param json - The JSON string representation. * @returns A new BlockGlobalAddr instance. */ public static fromJSON(json: string): BlockGlobalAddr { @@ -131,8 +131,8 @@ export class BlockGlobalAddr { } /** - * Converts the BlockGlobalAddr to its JSON representation. - * @returns The JSON string representation. + * Converts the BlockGlobalAddr to its JSON string representation. + * @returns The JSON string that represents this BlockGlobalAddr. */ public toJSON(): string { return this.toPrefixedString(); diff --git a/src/types/key/ByteCode.ts b/src/types/key/ByteCode.ts index e504e9472..4aa343bd7 100644 --- a/src/types/key/ByteCode.ts +++ b/src/types/key/ByteCode.ts @@ -1,14 +1,15 @@ import { concat } from '@ethersproject/bytes'; - import { Hash } from './Hash'; import { PrefixName } from './Key'; import { IResultWithBytes } from '../clvalue'; /** - * Enum representing the types of byte code. + * Enum representing types of byte code within the system. */ enum ByteCodeKind { + /** Represents an empty byte code type. */ EmptyKind = 0, + /** Represents a V1 Casper WASM byte code type. */ V1CasperWasmKind = 1 } @@ -16,12 +17,14 @@ const EmptyPrefix = 'empty-'; const V1WasmPrefix = 'v1-wasm-'; /** - * Custom error class for ByteCode related errors. + * Custom error class for ByteCode-related errors. */ class ByteCodeError extends Error { + /** Error for an invalid byte code format. */ static ErrInvalidByteCodeFormat = new ByteCodeError( 'Invalid ByteCode format' ); + /** Error for an invalid byte code kind. */ static ErrInvalidByteCodeKind = new ByteCodeError('Invalid ByteCodeKind'); constructor(message: string) { @@ -31,16 +34,16 @@ class ByteCodeError extends Error { } /** - * Represents a byte code in the system. + * Represents a byte code in the system, providing support for V1 Casper WASM or an empty byte code. */ export class ByteCode { private V1CasperWasm?: Hash; private isEmpty: boolean; /** - * Creates a new ByteCode instance. - * @param V1CasperWasm - The V1 Casper WASM hash. - * @param isEmpty - Whether the byte code is empty. + * Constructs a new ByteCode instance. + * @param V1CasperWasm - The hash representing V1 Casper WASM byte code. + * @param isEmpty - Whether the byte code is empty. Default is `false`. */ constructor(V1CasperWasm?: Hash, isEmpty = false) { this.V1CasperWasm = V1CasperWasm; @@ -48,7 +51,7 @@ export class ByteCode { } /** - * Creates a ByteCode from its JSON representation. + * Creates a ByteCode from a JSON string representation. * @param data - The JSON string representation of the ByteCode. * @returns A new ByteCode instance. * @throws ByteCodeError.ErrInvalidByteCodeFormat if the format is invalid. @@ -64,7 +67,7 @@ export class ByteCode { } /** - * Converts the ByteCode to its JSON representation. + * Converts the ByteCode instance to its JSON string representation. * @returns The JSON string representation of the ByteCode. */ toJSON(): string { @@ -72,8 +75,8 @@ export class ByteCode { } /** - * Checks if the ByteCode is empty. - * @returns True if the ByteCode is empty, false otherwise. + * Determines if the ByteCode instance represents an empty byte code. + * @returns True if the byte code is empty; otherwise, false. */ isEmptyCode(): boolean { return this.isEmpty; @@ -81,7 +84,7 @@ export class ByteCode { /** * Returns a prefixed string representation of the ByteCode. - * @returns The prefixed string representation. + * @returns A prefixed string based on the byte code type. * @throws Error if the ByteCode type is unexpected. */ toPrefixedString(): string { @@ -97,9 +100,9 @@ export class ByteCode { } /** - * Creates a ByteCode from a byte array. + * Creates a ByteCode instance from a byte array representation. * @param bytes - The byte array. - * @returns A new ByteCode instance. + * @returns An object with the new ByteCode instance and remaining bytes. * @throws ByteCodeError.ErrInvalidByteCodeFormat if the format is invalid. */ static fromBytes(bytes: Uint8Array): IResultWithBytes { @@ -122,10 +125,10 @@ export class ByteCode { } /** - * Converts a byte to a ByteCodeKind. + * Converts a byte to its corresponding ByteCodeKind. * @param tag - The byte to convert. * @returns The corresponding ByteCodeKind. - * @throws ByteCodeError.ErrInvalidByteCodeKind if the byte doesn't correspond to a valid ByteCodeKind. + * @throws ByteCodeError.ErrInvalidByteCodeKind if the byte doesn't match a valid ByteCodeKind. */ static newByteCodeKindFromByte(tag: number): ByteCodeKind { if (tag in ByteCodeKind) { @@ -135,7 +138,7 @@ export class ByteCode { } /** - * Converts the ByteCode to a byte array. + * Converts the ByteCode instance to a byte array representation. * @returns The byte array representation of the ByteCode. * @throws Error if the ByteCode type is unexpected. */ @@ -143,7 +146,6 @@ export class ByteCode { if (this.V1CasperWasm) { const kindBytes = new Uint8Array([ByteCodeKind.V1CasperWasmKind]); const wasmBytes = this.V1CasperWasm.toBytes(); - return concat([kindBytes, wasmBytes]); } else if (this.isEmpty) { return new Uint8Array([ByteCodeKind.EmptyKind]); diff --git a/src/types/key/Contract.ts b/src/types/key/Contract.ts index 432137ee3..1dd73731a 100644 --- a/src/types/key/Contract.ts +++ b/src/types/key/Contract.ts @@ -3,25 +3,25 @@ import { Hash } from './Hash'; import { PrefixName } from './Key'; /** - * Represents a contract hash in the system. + * Represents a contract hash within the system, providing various prefixed representations. */ @jsonObject export class ContractHash { /** - * The hash of the contract. + * The hash object representing the contract. */ @jsonMember({ name: 'hash', constructor: Hash }) hash: Hash; /** - * The original prefix of the contract hash string, if any. + * The prefix of the original contract hash string, if any (e.g., "hash-", "contract-wasm-", "contract-"). */ @jsonMember({ name: 'originPrefix', constructor: String }) originPrefix: string; /** - * Creates a new ContractHash instance. - * @param hash - The Hash object representing the contract hash. + * Constructs a new `ContractHash` instance. + * @param hash - The `Hash` object representing the contract hash. * @param originPrefix - The original prefix of the contract hash string. */ constructor(hash: Hash, originPrefix: string) { @@ -30,42 +30,42 @@ export class ContractHash { } /** - * Converts the ContractHash to its JSON representation. - * @returns A string representation of the ContractHash, including the original prefix. + * Converts the `ContractHash` instance to its JSON representation. + * @returns A string representation of the `ContractHash`, including the original prefix. */ toJSON(): string { return this.originPrefix + this.hash.toHex(); } /** - * Returns the contract hash as a prefixed WASM string. - * @returns The contract hash with the ContractWasm prefix. + * Returns the contract hash as a WASM-prefixed string. + * @returns The contract hash prefixed with `ContractWasm`. */ toPrefixedWasmString(): string { return PrefixName.ContractWasm + this.hash.toHex(); } /** - * Returns the contract hash as a prefixed string. - * @returns The contract hash with the Contract prefix. + * Returns the contract hash as a general prefixed string. + * @returns The contract hash prefixed with `Contract`. */ toPrefixedString(): string { return PrefixName.Contract + this.hash.toHex(); } /** - * Creates a ContractHash instance from its JSON representation. - * @param json - The JSON string representation of the ContractHash. - * @returns A new ContractHash instance. + * Creates a `ContractHash` instance from its JSON representation. + * @param json - The JSON string representation of the `ContractHash`. + * @returns A new `ContractHash` instance. */ static fromJSON(json: string): ContractHash { return ContractHash.newContract(json); } /** - * Creates a new ContractHash instance from a string representation. + * Creates a new `ContractHash` instance from a string representation. * @param source - The string representation of the contract hash. - * @returns A new ContractHash instance. + * @returns A new `ContractHash` instance. */ static newContract(source: string): ContractHash { let originPrefix = ''; diff --git a/src/types/key/ContractPackage.ts b/src/types/key/ContractPackage.ts index 63cfa4f9e..4c16de2ae 100644 --- a/src/types/key/ContractPackage.ts +++ b/src/types/key/ContractPackage.ts @@ -3,26 +3,26 @@ import { Hash } from './Hash'; import { PrefixName } from './Key'; /** - * Represents a contract package hash in the system. + * Represents a contract package hash within the system, with support for prefixed and JSON representations. */ @jsonObject export class ContractPackageHash { /** - * The hash of the contract package. + * The hash object representing the contract package. */ @jsonMember({ name: 'hash', constructor: Hash }) hash: Hash; /** - * The original prefix of the contract package hash string, if any. + * The original prefix of the contract package hash string, if any (e.g., "hash-", "contract-package-wasm-", "contract-package-"). */ @jsonMember({ name: 'originPrefix', constructor: String }) originPrefix: string; /** - * Creates a new ContractPackageHash instance. - * @param hash - The Hash object representing the contract package hash. - * @param originPrefix - The original prefix of the contract package hash string. + * Constructs a new `ContractPackageHash` instance. + * @param hash - The `Hash` object representing the contract package hash. + * @param originPrefix - The original prefix of the contract package hash string, if applicable. */ constructor(hash: Hash, originPrefix: string) { this.hash = hash; @@ -30,8 +30,8 @@ export class ContractPackageHash { } /** - * Converts the ContractPackageHash to its JSON representation. - * @returns A string representation of the ContractPackageHash, including the original prefix. + * Converts the `ContractPackageHash` instance to its JSON representation. + * @returns A string representation of the `ContractPackageHash`, including the original prefix. */ toJSON(): string { return this.originPrefix + this.hash.toHex(); @@ -39,25 +39,25 @@ export class ContractPackageHash { /** * Returns the contract package hash as a prefixed string. - * @returns The contract package hash with the ContractPackage prefix. + * @returns The contract package hash prefixed with `ContractPackage`. */ toPrefixedString(): string { return PrefixName.ContractPackage + this.hash.toHex(); } /** - * Creates a ContractPackageHash instance from its JSON representation. - * @param json - The JSON string representation of the ContractPackageHash. - * @returns A new ContractPackageHash instance. + * Creates a `ContractPackageHash` instance from its JSON representation. + * @param json - The JSON string representation of the `ContractPackageHash`. + * @returns A new `ContractPackageHash` instance. */ static fromJSON(json: string): ContractPackageHash { return ContractPackageHash.newContractPackage(json); } /** - * Creates a new ContractPackageHash instance from a string representation. - * @param source - The string representation of the contract package hash. - * @returns A new ContractPackageHash instance. + * Creates a new `ContractPackageHash` instance from a string representation. + * @param source - The string representation of the contract package hash, including any prefix. + * @returns A new `ContractPackageHash` instance. */ static newContractPackage(source: string): ContractPackageHash { let originPrefix = ''; diff --git a/src/types/key/EntityAddr.ts b/src/types/key/EntityAddr.ts index f4dd6c683..4c10507c2 100644 --- a/src/types/key/EntityAddr.ts +++ b/src/types/key/EntityAddr.ts @@ -5,7 +5,7 @@ import { Hash } from './Hash'; import { IResultWithBytes } from '../clvalue'; /** - * Enum representing the types of entities. + * Enum representing the types of entities within the system. */ export enum EntityKindType { SystemKind = 0, @@ -22,7 +22,8 @@ export const ErrInvalidEntityAddrFormat = new Error( export const ErrInvalidEntityKind = new Error('invalid EntityKind'); /** - * Represents an entity address in the system. + * Represents an entity address in the system. This class supports addresses for three types of entities: + * system, account, and smart contract. The address type is indicated by either the system, account, or smartContract property being set. */ @jsonObject export class EntityAddr { @@ -40,9 +41,9 @@ export class EntityAddr { /** * Creates a new EntityAddr instance. - * @param system - The system hash. - * @param account - The account hash. - * @param smartContract - The smart contract hash. + * @param system - The hash representing a system entity. + * @param account - The hash representing an account entity. + * @param smartContract - The hash representing a smart contract entity. */ constructor(system?: Hash, account?: Hash, smartContract?: Hash) { this.system = system; @@ -51,8 +52,8 @@ export class EntityAddr { } /** - * Returns a prefixed string representation of the EntityAddr. - * @returns The prefixed string representation. + * Returns a prefixed string representation of the EntityAddr, with different prefixes for each entity type. + * @returns The prefixed string representation, with "prefix-system-", "prefix-account-", or "prefix-contract-" based on entity type. */ toPrefixedString(): string { const PrefixNameAddressableEntity = 'prefix-'; @@ -91,6 +92,7 @@ export class EntityAddr { /** * Converts the EntityAddr to a byte array. + * The first byte represents the entity type, followed by the bytes of the associated hash. * @returns The byte array representation of the EntityAddr. * @throws {Error} If the EntityAddr type is unexpected. */ @@ -115,7 +117,8 @@ export class EntityAddr { } /** - * Creates an EntityAddr from a byte array. + * Creates an EntityAddr from a byte array. The first byte indicates the entity type, + * and the remaining bytes represent the hash. * @param bytes - The byte array. * @returns A new EntityAddr instance. * @throws {Error} If the buffer is empty or the format is invalid. diff --git a/src/types/key/EntryPointAddr.ts b/src/types/key/EntryPointAddr.ts index d7c4e9101..68f8b9dbf 100644 --- a/src/types/key/EntryPointAddr.ts +++ b/src/types/key/EntryPointAddr.ts @@ -7,7 +7,7 @@ import { Conversions } from '../Conversions'; import { IResultWithBytes } from '../clvalue'; /** - * Enum representing the types of entry points. + * Enum representing the types of entry points in the Casper VM. */ export enum EntryPointTag { V1EntryPoint = 0, @@ -45,7 +45,7 @@ const V2Prefix = 'v2-'; const SelectorBytesLen = 4; /** - * Represents a V1 Casper VM entry point. + * Represents a V1 Casper VM entry point with an entity address and name bytes. */ @jsonObject class VmCasperV1 { @@ -67,7 +67,7 @@ class VmCasperV1 { } /** - * Represents a V2 Casper VM entry point. + * Represents a V2 Casper VM entry point with an entity address and selector. */ @jsonObject class VmCasperV2 { @@ -89,7 +89,7 @@ class VmCasperV2 { } /** - * Represents an entry point address in the system. + * Represents an entry point address in the system, which may be a V1 or V2 Casper VM entry point. */ @jsonObject export class EntryPointAddr { @@ -99,6 +99,11 @@ export class EntryPointAddr { @jsonMember({ name: 'VmCasperV2', constructor: VmCasperV2 }) vmCasperV2?: VmCasperV2; + /** + * Creates a new EntryPointAddr instance. + * @param vmCasperV1 - The V1 Casper VM entry point, if applicable. + * @param vmCasperV2 - The V2 Casper VM entry point, if applicable. + */ constructor(vmCasperV1?: VmCasperV1, vmCasperV2?: VmCasperV2) { this.vmCasperV1 = vmCasperV1; this.vmCasperV2 = vmCasperV2; diff --git a/src/types/key/Era.ts b/src/types/key/Era.ts index fa0c544cb..0f4d0e5d4 100644 --- a/src/types/key/Era.ts +++ b/src/types/key/Era.ts @@ -2,37 +2,37 @@ import { jsonMember, jsonObject } from 'typedjson'; /** * Represents an Era in the system. - * An Era is a period of time in the blockchain, typically used for consensus and reward distribution. + * An Era is a distinct period in the blockchain, typically used for consensus, validator rotations, and reward distributions. */ @jsonObject export class Era { /** - * The numeric value of the Era. + * The numeric identifier of the Era. */ @jsonMember({ constructor: Number }) public value: number; /** * Creates a new Era instance. - * @param value - The numeric value of the Era. + * @param value - The numeric identifier of the Era. */ constructor(value: number) { this.value = value; } /** - * Converts the Era to its JSON representation. - * @returns A string representation of the Era's value. + * Converts the Era instance to its JSON representation. + * @returns A string representation of the Era's numeric value. */ toJSON(): string { return this.value.toString(); } /** - * Creates an Era from its JSON representation. + * Creates an Era instance from its JSON representation. * @param json - The JSON string representation of the Era. * @returns A new Era instance. - * @throws Error if the JSON string cannot be parsed to a valid number. + * @throws Error if the JSON string cannot be parsed as a valid number. */ static fromJSON(json: string): Era { const value = parseInt(json, 10); @@ -43,8 +43,8 @@ export class Era { } /** - * Creates an Era from a byte array. - * @param bytes - The byte array representing the Era. + * Creates an Era instance from a byte array. + * @param bytes - The byte array representing the Era value as a 32-bit unsigned integer. * @returns A new Era instance. */ static fromBytes(bytes: Uint8Array): Era { @@ -53,11 +53,11 @@ export class Era { } /** - * Converts the Era to a byte array. - * @returns A Uint8Array representation of the Era. + * Converts the Era instance to a byte array. + * @returns A Uint8Array representation of the Era value as a 32-bit unsigned integer. */ toBytes(): Uint8Array { - const buffer = new ArrayBuffer(8); + const buffer = new ArrayBuffer(4); new DataView(buffer).setUint32(0, this.value, true); return new Uint8Array(buffer); } diff --git a/src/types/key/Hash.ts b/src/types/key/Hash.ts index 794a354b9..2a94b16d0 100644 --- a/src/types/key/Hash.ts +++ b/src/types/key/Hash.ts @@ -10,16 +10,16 @@ import { IResultWithBytes } from '../clvalue'; export class Hash { private hashBytes: Uint8Array; - /** The length of the hash in bytes. */ + /** The fixed length of the hash in bytes. */ static ByteHashLen = 32; - /** The length of the hash string representation in hexadecimal. */ + /** The fixed length of the hash string representation in hexadecimal characters. */ static StringHashLen = 64; /** * Creates a new Hash instance. * @param hashBytes - The byte array representing the hash. - * @throws Error if the hash length is invalid. + * @throws Error if the byte array length does not match the expected hash length. */ constructor(hashBytes: Uint8Array) { if (hashBytes.length !== Hash.ByteHashLen) { @@ -31,10 +31,10 @@ export class Hash { } /** - * Creates a Hash from a hexadecimal string. + * Creates a Hash instance from a hexadecimal string. * @param source - The hexadecimal string representation of the hash. * @returns A new Hash instance. - * @throws Error if the string length is invalid. + * @throws Error if the string length does not match the expected hash length. */ static fromHex(source: string): Hash { if (source.length !== Hash.StringHashLen) { @@ -47,7 +47,7 @@ export class Hash { } /** - * Converts the Hash to a hexadecimal string. + * Converts the Hash instance to a hexadecimal string. * @returns The hexadecimal string representation of the hash. */ toHex(): string { @@ -55,7 +55,7 @@ export class Hash { } /** - * Converts the Hash to a byte array. + * Converts the Hash instance to a byte array. * @returns The byte array representation of the hash. */ toBytes(): Uint8Array { @@ -63,7 +63,7 @@ export class Hash { } /** - * Converts the Hash to its JSON representation. + * Converts the Hash instance to its JSON representation. * @returns The JSON string representation of the hash. */ toJSON(): string { @@ -71,7 +71,7 @@ export class Hash { } /** - * Creates a Hash from its JSON representation. + * Creates a Hash instance from its JSON representation. * @param json - The JSON string representation of the hash. * @returns A new Hash instance. */ @@ -80,14 +80,14 @@ export class Hash { } /** - * Creates a Hash from a byte array. + * Creates a Hash instance from a byte array. * @param source - The byte array representing the hash. - * @returns A new Hash instance. - * @throws Error if the byte array length is invalid. + * @returns A result object containing the new Hash instance and the remaining bytes. + * @throws Error if the byte array length does not match the expected hash length. */ static fromBytes(source: Uint8Array): IResultWithBytes { if (source.length !== Hash.ByteHashLen) { - throw new Error('key length is not equal 32'); + throw new Error('Key length is not equal to 32 bytes.'); } const hashBytes = source.subarray(0, Hash.ByteHashLen); @@ -98,18 +98,24 @@ export class Hash { } /** - * Creates a Hash from a Buffer. + * Creates a Hash instance from a Buffer. * @param buffer - The Buffer containing the hash bytes. * @returns A new Hash instance. * @throws Error if the buffer length is less than the required hash length. */ static fromBuffer(buffer: Buffer): Hash { if (buffer.length < Hash.ByteHashLen) { - throw new Error('key length is not equal 32'); + throw new Error('Key length is not equal to 32 bytes.'); } return new Hash(new Uint8Array(buffer.slice(0, Hash.ByteHashLen))); } + /** + * Creates an array of Hash instances from a byte array. + * @param byteArray - The byte array containing multiple hash values. + * @returns An array of Hash instances created from the byte array. + * @throws Error if the byte array length is not a multiple of the hash length. + */ public static createHashArray(byteArray: Uint8Array): Hash[] { if (byteArray.length % Hash.ByteHashLen !== 0) { throw new Error( @@ -127,7 +133,7 @@ export class Hash { } /** - * Compares this Hash with another Hash for equality. + * Compares this Hash instance with another Hash instance for equality. * @param other - The other Hash to compare with. * @returns True if the hashes are equal, false otherwise. */ diff --git a/src/types/key/Key.ts b/src/types/key/Key.ts index 39fd8082e..c59c70ece 100644 --- a/src/types/key/Key.ts +++ b/src/types/key/Key.ts @@ -14,6 +14,9 @@ import { EntryPointAddr } from './EntryPointAddr'; import { URef } from './URef'; import { IResultWithBytes } from '../clvalue'; +/** + * Enum that defines prefixes used to identify different types of blockchain entities and objects. + */ export enum PrefixName { Account = 'account-hash-', AddressableEntity = 'addressable-entity-', @@ -45,6 +48,9 @@ export enum PrefixName { EntryPoint = 'entry-point-' } +/** + * Enum representing different types of blockchain key types used in the system. + */ const enum TypeID { Account = 0, Hash, @@ -72,6 +78,9 @@ const enum TypeID { EntryPoint } +/** + * Enum for human-readable key type names, used to represent various key entities in the blockchain. + */ export enum KeyTypeName { Account = 'Account', Hash = 'Hash', @@ -90,6 +99,9 @@ export enum KeyTypeName { ChecksumRegistry = 'ChecksumRegistry' } +/** + * Mapping of key type names to their corresponding TypeID values. + */ export const typeIDbyNames = new Map([ [KeyTypeName.Account, TypeID.Account], [KeyTypeName.Hash, TypeID.Hash], @@ -108,6 +120,9 @@ export const typeIDbyNames = new Map([ [KeyTypeName.ChecksumRegistry, TypeID.ChecksumRegistry] ]); +/** + * Mapping of blockchain key prefixes to their corresponding TypeID values. + */ export const keyIDbyPrefix = new Map([ [PrefixName.Account, TypeID.Account], [PrefixName.Hash, TypeID.Hash], @@ -1029,8 +1044,6 @@ export class Key { return Key.createByType(source, keyIDbyPrefix.get(prefix)!); } - // Inside the Key class - /** * Converts the Key instance to a JSON object. * @returns The JSON representation of the Key instance. diff --git a/src/types/key/MessageAddr.ts b/src/types/key/MessageAddr.ts index 5fbd26ddb..8b343aa4e 100644 --- a/src/types/key/MessageAddr.ts +++ b/src/types/key/MessageAddr.ts @@ -1,5 +1,4 @@ import { concat } from '@ethersproject/bytes'; - import { jsonMember, jsonObject } from 'typedjson'; import { EntityAddr } from './EntityAddr'; import { Hash } from './Hash'; @@ -15,8 +14,9 @@ const PrefixNameMessage = 'message-'; const PrefixNameAddressableEntity = 'entity-'; /** - * Represents a message address within the system, identified by an entity address, - * a topic name hash, and an optional message index. + * Represents an addressable message within the system. The address is composed of an associated entity address, + * a hashed topic name, and an optional message index. It offers various utilities for serialization, deserialization, + * and converting the address into prefixed string and byte representations. */ @jsonObject export class MessageAddr { @@ -45,19 +45,20 @@ export class MessageAddr { }) public entityAddr: EntityAddr; - /** The hash of the topic name. */ + /** The hash of the topic name associated with this message. */ @jsonMember({ name: 'TopicNameHash', constructor: Hash }) public topicNameHash: Hash; - /** The optional index of the message. */ + /** The optional index of the message within the topic. */ @jsonMember({ name: 'MessageIndex', constructor: Number }) public messageIndex?: number; /** - * Creates a MessageAddr instance from a string representation. + * Instantiates a `MessageAddr` from its string representation. + * The string should follow the prefixed format used in the system. * @param source - The string representation of the MessageAddr. * @returns A new MessageAddr instance. - * @throws Error if the format is invalid. + * @throws Error if the provided string does not match the expected format. */ static fromString(source: string): MessageAddr { let messageIndex: number | undefined; @@ -88,8 +89,9 @@ export class MessageAddr { } /** - * Converts the MessageAddr to a prefixed string representation. - * @returns A prefixed string representation of the MessageAddr. + * Converts the `MessageAddr` into a standardized prefixed string format. + * Useful for displaying or storing the address in text format. + * @returns A prefixed string representation of the `MessageAddr`. */ toPrefixedString(): string { let result = PrefixNameMessage; @@ -107,17 +109,20 @@ export class MessageAddr { } /** - * Converts the MessageAddr to a JSON-compatible string. - * @returns A JSON string representation of the MessageAddr. + * Serializes the `MessageAddr` into a JSON-compatible string format. + * Primarily used for JSON-based data exchange. + * @returns A JSON string representation of the `MessageAddr`. */ toJSON(): string { return this.toPrefixedString(); } /** - * Creates a MessageAddr instance from a byte array. + * Constructs a `MessageAddr` instance from a byte array. + * Interprets the byte array in a structured format to extract + * the entity address, topic name hash, and optionally, the message index. * @param bytes - The byte array representing the MessageAddr. - * @returns A new MessageAddr instance. + * @returns A new `MessageAddr` instance wrapped in an `IResultWithBytes`. */ static fromBytes(bytes: Uint8Array): IResultWithBytes { const entityAddr = EntityAddr.fromBytes(bytes); @@ -140,8 +145,9 @@ export class MessageAddr { } /** - * Converts the MessageAddr to a byte array representation. - * @returns A Uint8Array representing the MessageAddr. + * Converts the `MessageAddr` to a byte array, enabling binary data storage. + * Useful for transmission or storage where a compact format is needed. + * @returns A `Uint8Array` representing the `MessageAddr`. */ toBytes(): Uint8Array { const entityBytes = this.entityAddr.toBytes(); diff --git a/src/types/key/NewNamedKeyAddr.ts b/src/types/key/NewNamedKeyAddr.ts index a384792fa..b47f8e5e6 100644 --- a/src/types/key/NewNamedKeyAddr.ts +++ b/src/types/key/NewNamedKeyAddr.ts @@ -4,18 +4,20 @@ import { PrefixName } from './Key'; import { IResultWithBytes } from '../clvalue'; /** - * Represents a named key address, identified by a base entity address and a name. + * Represents a named key address, which is identified by a base entity address and a unique name. + * The name is represented in bytes to allow for efficient encoding and decoding. */ @jsonObject export class NamedKeyAddr { /** - * The base address of the entity. + * The base address of the entity to which this key belongs. */ @jsonMember({ name: 'BaseAddr', constructor: EntityAddr }) baseAddr: EntityAddr; /** * The bytes representing the name associated with the address. + * Expected to be a 32-byte array for validity. */ @jsonMember({ name: 'NameBytes', constructor: Uint8Array }) nameBytes: Uint8Array; @@ -23,7 +25,7 @@ export class NamedKeyAddr { /** * Creates an instance of NamedKeyAddr. * @param baseAddr - The base address of the entity. - * @param nameBytes - The bytes representing the name. + * @param nameBytes - The 32-byte array representing the name associated with the address. */ constructor(baseAddr: EntityAddr, nameBytes: Uint8Array) { this.baseAddr = baseAddr; @@ -31,10 +33,11 @@ export class NamedKeyAddr { } /** - * Creates a NamedKeyAddr instance from a string representation. + * Creates a NamedKeyAddr instance from a string representation, parsing the base address and name bytes. + * The string should follow the expected prefixed format used by the system. * @param source - The string representation of the NamedKeyAddr. * @returns A new NamedKeyAddr instance. - * @throws Error if the name bytes length is not valid. + * @throws Error if the nameBytes length is not exactly 32 bytes. */ static fromString(source: string): NamedKeyAddr { const nameBytesData = source.substring(source.lastIndexOf('-') + 1); @@ -52,7 +55,8 @@ export class NamedKeyAddr { } /** - * Converts the NamedKeyAddr to a prefixed string representation. + * Converts the NamedKeyAddr instance to a standardized prefixed string format. + * This format includes the base address and the name bytes, represented in hexadecimal. * @returns A prefixed string representation of the NamedKeyAddr. */ toPrefixedString(): string { @@ -64,24 +68,26 @@ export class NamedKeyAddr { } /** - * Converts the NamedKeyAddr to a JSON-compatible string. - * @returns A JSON string representation of the NamedKeyAddr. + * Serializes the NamedKeyAddr to a JSON-compatible string. + * Primarily used for exchanging data in JSON format. + * @returns A JSON-compatible string representation of the NamedKeyAddr. */ toJSON(): string { return this.toPrefixedString(); } /** - * Creates a NamedKeyAddr instance from a byte array. + * Constructs a NamedKeyAddr instance from a byte array representation. + * The byte array should contain the base address followed by the name bytes. * @param bytes - The byte array representing the NamedKeyAddr. - * @returns A new NamedKeyAddr instance. - * @throws Error if the byte array is shorter than expected. + * @returns An `IResultWithBytes` object containing the NamedKeyAddr instance and any remaining bytes. + * @throws Error if the byte array does not contain at least 32 bytes for the name. */ static fromBytes(bytes: Uint8Array): IResultWithBytes { const baseAddr = EntityAddr.fromBytes(bytes); if (bytes.length < 32) { - throw new Error('It does not contain enough bytes for NameBytes.'); + throw new Error('Insufficient bytes for NameBytes; expected 32 bytes.'); } const nameBytes = bytes.slice(0, 32); return { @@ -91,7 +97,8 @@ export class NamedKeyAddr { } /** - * Converts the NamedKeyAddr to a byte array representation. + * Converts the NamedKeyAddr to a byte array for efficient storage or transmission. + * The byte array includes the base address followed by the 32-byte name. * @returns A Uint8Array representing the NamedKeyAddr. */ toBytes(): Uint8Array { diff --git a/src/types/key/Transfer.ts b/src/types/key/Transfer.ts index 07812ccb6..3dd8b8eb7 100644 --- a/src/types/key/Transfer.ts +++ b/src/types/key/Transfer.ts @@ -5,18 +5,20 @@ import { Hash } from './Hash'; export const PrefixNameTransfer = 'transfer-'; /** - * Represents a transfer hash, extending the Hash class, with an additional prefix for transfer entities. + * Represents a transfer hash, extending the `Hash` class, with an additional prefix specific to transfer entities. + * This prefix aids in identifying transfer-related hashes within the system. */ @jsonObject export class TransferHash extends Hash { /** - * The origin prefix used to identify transfer-related hashes. + * The origin prefix used to identify transfer-related hashes, defaulting to `transfer-`. */ @jsonMember({ name: 'originPrefix', constructor: String }) originPrefix: string = PrefixNameTransfer; /** * Creates an instance of TransferHash. + * Supports both hex strings (with or without the transfer prefix) and Uint8Array representations of the hash. * @param source - A hex string or Uint8Array representing the hash. */ constructor(source: string | Uint8Array) { @@ -33,9 +35,9 @@ export class TransferHash extends Hash { } /** - * Initializes the TransferHash from a source string. - * @param source - The source string representing the transfer hash. - * @returns An object containing the hash bytes and the origin prefix. + * Parses a source string to extract the hash bytes and verify if it includes the transfer prefix. + * @param source - The source string representing the transfer hash, optionally prefixed. + * @returns An object containing the hash bytes and the detected origin prefix. */ private static initializeFromSource( source: string @@ -51,7 +53,8 @@ export class TransferHash extends Hash { } /** - * Converts the TransferHash to a prefixed string representation. + * Converts the TransferHash to a standardized prefixed string format. + * This format includes the transfer-specific prefix followed by the hash in hexadecimal format. * @returns A string representation of the TransferHash with its prefix. */ toPrefixedString(): string { @@ -59,17 +62,19 @@ export class TransferHash extends Hash { } /** - * Converts the TransferHash to a JSON-compatible string. - * @returns A JSON string representation of the TransferHash. + * Serializes the TransferHash to a JSON-compatible string. + * Primarily used for JSON-based data exchange or storage. + * @returns A JSON-compatible string representation of the TransferHash. */ toJSON(): string { return this.toPrefixedString(); } /** - * Creates a TransferHash instance from a JSON string. + * Instantiates a TransferHash from a JSON-compatible string, allowing for easy deserialization. + * The string should represent the TransferHash in prefixed hex format. * @param json - The JSON string representing the TransferHash. - * @returns A new TransferHash instance. + * @returns A new TransferHash instance initialized from the JSON string. */ static fromJSON(json: string): TransferHash { return new TransferHash(json); diff --git a/src/types/key/URef.ts b/src/types/key/URef.ts index 60e113aa6..d265ff1ea 100644 --- a/src/types/key/URef.ts +++ b/src/types/key/URef.ts @@ -5,6 +5,7 @@ import { concat } from '@ethersproject/bytes'; /** * Enum representing the access permissions of a URef. + * These permissions define the allowed actions on the URef, such as read, write, or add. */ export enum UrefAccess { None = 0, @@ -27,23 +28,24 @@ export const PrefixNameURef = 'uref-'; export const ByteHashLen = 32; /** - * Represents an Unforgeable Reference (URef) with associated access permissions. + * Represents an Unforgeable Reference (URef) in the system, identified by a unique hash and associated with specific access permissions. + * A URef is used to control permissions and securely reference data in smart contracts. */ @jsonObject export class URef { - /** The data (hash) of the URef. */ + /** The unique data (hash) associated with the URef, represented as a 32-byte array. */ @jsonArrayMember(Number) data: Uint8Array; - /** The access permissions for the URef. */ + /** The access permissions assigned to this URef, defined by the `UrefAccess` enum. */ @jsonMember({ constructor: Number }) access: UrefAccess; /** * Creates an instance of URef. - * @param data - The data (hash) of the URef. - * @param access - The access permissions for the URef. - * @throws Error if the data length is not equal to `ByteHashLen`. + * @param data - The data (hash) of the URef, expected to be exactly 32 bytes. + * @param access - The access permissions for the URef, specified by the `UrefAccess` enum. + * @throws Error if the data length is not equal to `ByteHashLen` or if the access rights are unsupported. */ constructor(data: Uint8Array, access: UrefAccess) { if (data.length !== ByteHashLen) { @@ -51,7 +53,7 @@ export class URef { } if (!Object.values(UrefAccess).includes(access)) { - throw new Error('Unsuported AccessRights'); + throw new Error('Unsupported AccessRights'); } this.data = data; @@ -60,7 +62,8 @@ export class URef { /** * Converts the URef to a byte array representation. - * @returns A Uint8Array representing the URef. + * This format is useful for serialization or data transfer. + * @returns A Uint8Array representing the URef, combining its data and access bytes. */ bytes(): Uint8Array { const accessBytes = new Uint8Array([this.access]); @@ -68,13 +71,17 @@ export class URef { } /** - * Converts the URef to a prefixed string representation. - * @returns A string with the URef prefix, data in hex, and access in hex format. + * Converts the URef to a prefixed string representation, following the standard format for URef strings. + * @returns A string with the URef prefix, data in hex format, and access permissions in hex format. */ toPrefixedString(): string { return [PrefixNameURef.replace('-', ''), this.toString()].join('-'); } + /** + * Converts the URef to a string, displaying its data as a hexadecimal string along with the access permissions. + * @returns A string representation of the URef. + */ toString(): string { return [ Conversions.encodeBase16(this.data), @@ -83,15 +90,15 @@ export class URef { } /** - * Sets the access permissions for the URef. - * @param access - The new access permission to set. + * Sets or updates the access permissions for the URef. + * @param access - The new access permission to set, defined by the `UrefAccess` enum. */ setAccess(access: UrefAccess) { this.access = access; } /** - * Converts the URef to a JSON-compatible string. + * Serializes the URef to a JSON-compatible string format. * @returns A JSON string representation of the URef. */ toJSON(): string { @@ -99,8 +106,8 @@ export class URef { } /** - * Creates a URef from a JSON string. - * @param data - The JSON string representation of the URef. + * Creates a URef from a JSON-compatible string representation. + * @param data - The JSON string representing the URef. * @returns A new URef instance. */ static fromJSON(data: string): URef { @@ -108,10 +115,10 @@ export class URef { } /** - * Parses a URef from a string representation. - * @param source - The string containing the URef data. + * Parses a URef from a prefixed string format, which includes its data and access permissions. + * @param source - The string containing the URef data, starting with the URef prefix. * @returns A new URef instance. - * @throws ErrIncorrectUrefFormat if the format is invalid. + * @throws ErrIncorrectUrefFormat if the string format does not match the expected URef format. */ static fromString(source: string): URef { if (!source.startsWith(`${PrefixNameURef}`)) { @@ -129,10 +136,10 @@ export class URef { } /** - * Creates a URef from a byte array. - * @param bytes - The byte array representing the URef. - * @returns A new URef instance. - * @throws Error if the byte array length is invalid. + * Creates a URef from a byte array representation, expecting the hash data and access byte. + * @param bytes - The byte array containing the URef data and access byte. + * @returns A new URef instance wrapped in an `IResultWithBytes` object. + * @throws Error if the byte array length does not match the expected URef structure. */ static fromBytes(bytes: Uint8Array): IResultWithBytes { if (bytes.length !== ByteHashLen + 1) { @@ -147,7 +154,7 @@ export class URef { } /** - * Returns the byte array representation of the URef, used as a driver value. + * Returns the byte array representation of the URef, often used for driving values in other contexts. * @returns A Uint8Array representing the URef. */ toDriverValue(): Uint8Array { @@ -155,10 +162,10 @@ export class URef { } /** - * Creates a URef from an ArrayBuffer. + * Creates a URef instance from an ArrayBuffer, extracting the hash data and access byte. * @param arrayBuffer - The ArrayBuffer containing the URef data. * @returns A new URef instance. - * @throws Error if the ArrayBuffer size is too small. + * @throws Error if the ArrayBuffer size is smaller than expected. */ public static fromBuffer(arrayBuffer: ArrayBuffer): URef { const dataView = new DataView(arrayBuffer); diff --git a/src/types/key/Uref.test.ts b/src/types/key/Uref.test.ts index d4e7612cc..a518e86d3 100644 --- a/src/types/key/Uref.test.ts +++ b/src/types/key/Uref.test.ts @@ -22,7 +22,7 @@ describe('CLUref', () => { expect(RWExampleURef).to.be.an.instanceof(URef); expect(badFn1).to.throw('Invalid URef data length; expected 32'); - expect(badFn2).to.throw('Unsuported AccessRights'); + expect(badFn2).to.throw('Unsupported AccessRights'); }); it('fromFormattedString() / toFormattedString() proper value', () => { diff --git a/src/types/keypair/Algorithm.ts b/src/types/keypair/Algorithm.ts index 5cf82d57a..a3b2c5a02 100644 --- a/src/types/keypair/Algorithm.ts +++ b/src/types/keypair/Algorithm.ts @@ -1,5 +1,6 @@ /** * Enum representing supported cryptographic key algorithms. + * Each value corresponds to a specific cryptographic algorithm used in digital signatures. */ export enum KeyAlgorithm { /** ED25519 digital signature algorithm */ @@ -20,11 +21,12 @@ export const KeySettings: Record = { /** * Utility class for working with key algorithms, allowing conversion to string and byte formats. + * Provides convenient methods to retrieve the algorithm name and numeric representation. */ export class KeyAlgorithmUtils { /** * Creates an instance of KeyAlgorithmUtils. - * @param algorithm - The key algorithm to manage. + * @param algorithm - The key algorithm to manage, specified by the `KeyAlgorithm` enum. */ constructor(private algorithm: KeyAlgorithm) {} diff --git a/src/types/keypair/PrivateKey.ts b/src/types/keypair/PrivateKey.ts index a9f95e7ff..985006d14 100644 --- a/src/types/keypair/PrivateKey.ts +++ b/src/types/keypair/PrivateKey.ts @@ -33,6 +33,7 @@ enum KeyAlgorithm { /** * Represents a private key with associated public key and cryptographic algorithm. + * Provides methods for signing messages, exporting to PEM, and generating public keys. */ export class PrivateKey { /** The cryptographic algorithm used for the key. */ @@ -148,6 +149,7 @@ export class PrivateKey { /** * Factory class for creating instances of PrivateKeyInternal using different formats and algorithms. + * This utility class allows generating, importing, and creating private keys with specific cryptographic algorithms. */ class PrivateKeyFactory { /** diff --git a/src/types/keypair/PublicKey.ts b/src/types/keypair/PublicKey.ts index 01a4679af..2e6cc6ca8 100644 --- a/src/types/keypair/PublicKey.ts +++ b/src/types/keypair/PublicKey.ts @@ -47,7 +47,8 @@ interface PublicKeyInternal { } /** - * Represents a public key with cryptographic algorithm and key data. + * Represents a public key with a cryptographic algorithm and key data. + * Provides utilities for serialization, verification, and obtaining an associated account hash. */ @jsonObject export class PublicKey { @@ -60,8 +61,8 @@ export class PublicKey { /** * Creates an instance of PublicKey. - * @param cryptoAlg - The cryptographic algorithm. - * @param key - The key data. + * @param cryptoAlg - The cryptographic algorithm used by the key. + * @param key - The actual key data. */ constructor(cryptoAlg: KeyAlgorithm, key: PublicKeyInternal) { this.cryptoAlg = cryptoAlg; @@ -93,7 +94,7 @@ export class PublicKey { } /** - * Converts the public key to a JSON-compatible string. + * Serializes the public key to a JSON-compatible string. * @returns A JSON string representation of the public key. */ toJSON(): string { @@ -154,7 +155,7 @@ export class PublicKey { } /** - * Generates an account hash for the public key. + * Generates an account hash for the public key, used to uniquely identify an account. * @returns An AccountHash representing the account associated with this public key. */ accountHash(): AccountHash { @@ -250,7 +251,7 @@ export class PublicKey { } /** - * Represents a list of public keys with utility methods for checking membership. + * Represents a list of public keys, with utility methods for checking membership and managing keys. */ export class PublicKeyList { private keys: PublicKey[]; diff --git a/src/types/keypair/ed25519/PrivateKey.ts b/src/types/keypair/ed25519/PrivateKey.ts index 9bd6f479c..e1fadb372 100644 --- a/src/types/keypair/ed25519/PrivateKey.ts +++ b/src/types/keypair/ed25519/PrivateKey.ts @@ -22,6 +22,7 @@ interface PrivateKeyInternal { /** * Represents an Ed25519 private key, supporting key generation, signing, and PEM encoding. + * Provides methods for creating instances from byte arrays, hexadecimal strings, and PEM format. */ export class PrivateKey implements PrivateKeyInternal { /** Size of the PEM prefix for Ed25519 private keys. */ @@ -66,6 +67,7 @@ export class PrivateKey implements PrivateKeyInternal { /** * Creates a PrivateKey instance from a byte array. + * Validates that the byte array matches the expected length for an Ed25519 private key. * @param key - The byte array representing the private key. * @returns A new PrivateKey instance. * @throws Error if the byte array length is not 64. @@ -79,6 +81,7 @@ export class PrivateKey implements PrivateKeyInternal { /** * Creates a PrivateKey instance from a hexadecimal string. + * Converts the hexadecimal string to bytes and validates the length. * @param keyHex - The hexadecimal string representing the private key. * @returns A new PrivateKey instance. * @throws Error if the hex string length is not 128 characters. @@ -94,7 +97,7 @@ export class PrivateKey implements PrivateKeyInternal { } /** - * Exports the private key to PEM format. + * Exports the private key to PEM format, with a standardized prefix and suffix. * @returns A PEM-encoded string of the private key. */ toPem(): string { @@ -109,6 +112,7 @@ export class PrivateKey implements PrivateKeyInternal { /** * Creates a PrivateKey instance from a PEM-encoded string. + * Parses the PEM content to extract the private key bytes. * @param content - The PEM string representing the private key. * @returns A new PrivateKey instance. * @throws Error if the content cannot be properly parsed. diff --git a/src/types/keypair/ed25519/PublicKey.ts b/src/types/keypair/ed25519/PublicKey.ts index 45da5f2b7..217416ad3 100644 --- a/src/types/keypair/ed25519/PublicKey.ts +++ b/src/types/keypair/ed25519/PublicKey.ts @@ -5,7 +5,7 @@ const PublicKeySize = 32; /** * Represents an Ed25519 public key, supporting signature verification - * and loading from byte arrays or PEM files. + * and loading from byte arrays. */ export class PublicKey { /** The raw bytes of the public key. */ @@ -29,7 +29,9 @@ export class PublicKey { /** * Verifies a signature for a given message. - * @param message - The message that was signed. + * Utilizes the Ed25519 algorithm to check if the signature is valid + * for the given message and public key. + * @param message - The original message that was signed. * @param signature - The signature to verify. * @returns A promise that resolves to `true` if the signature is valid, or `false` otherwise. */ @@ -42,6 +44,8 @@ export class PublicKey { /** * Creates a PublicKey instance from a byte array. + * Validates the size of the byte array to ensure it matches the expected + * size of an Ed25519 public key. * @param data - The byte array representing the public key. * @returns A new PublicKey instance. * @throws Error if the byte array length is not equal to `PublicKeySize`. diff --git a/src/types/keypair/secp256k1/PrivateKey.ts b/src/types/keypair/secp256k1/PrivateKey.ts index 76030a30c..a158dac35 100644 --- a/src/types/keypair/secp256k1/PrivateKey.ts +++ b/src/types/keypair/secp256k1/PrivateKey.ts @@ -27,7 +27,8 @@ interface PrivateKeyInternal { } /** - * Represents a secp256k1 private key, supporting generation, signing, and PEM encoding. + * Represents a secp256k1 private key, supporting key generation, signing, and PEM encoding. + * The class offers static methods to create instances from bytes, hex, and PEM formats. */ export class PrivateKey implements PrivateKeyInternal { /** The raw bytes of the private key. */ @@ -68,6 +69,7 @@ export class PrivateKey implements PrivateKeyInternal { /** * Signs a message using the private key. + * The message is first hashed with SHA-256 before signing. * @param message - The message to sign. * @returns A promise that resolves to the signature bytes in compact format. */ @@ -115,7 +117,7 @@ export class PrivateKey implements PrivateKeyInternal { } /** - * Exports the private key to PEM format. + * Exports the private key to PEM format, which can be used for secure storage or sharing. * @returns A PEM-encoded string of the private key. */ toPem(): string { diff --git a/src/types/keypair/secp256k1/PublicKey.ts b/src/types/keypair/secp256k1/PublicKey.ts index 160619f12..e161a4475 100644 --- a/src/types/keypair/secp256k1/PublicKey.ts +++ b/src/types/keypair/secp256k1/PublicKey.ts @@ -5,16 +5,16 @@ import { sha256 } from '@noble/hashes/sha256'; const PublicKeySize = 33; /** - * Represents a secp256k1 public key, providing methods to retrieve bytes - * and verify signatures. + * Represents a secp256k1 public key, providing methods to retrieve the compressed + * public key bytes and verify digital signatures. */ export class PublicKey { - /** The raw bytes of the public key. */ + /** The raw bytes of the public key in compressed format. */ private key: Uint8Array; /** * Creates an instance of PublicKey. - * @param key - The public key bytes. + * @param key - The public key bytes in compressed format. */ constructor(key: Uint8Array) { this.key = key; @@ -30,8 +30,10 @@ export class PublicKey { /** * Verifies a signature for a given message. - * @param message - The message that was signed. - * @param signature - The signature to verify. + * Uses the secp256k1 algorithm to validate if the provided signature matches + * the public key for the given message. + * @param message - The original message that was signed. + * @param signature - The signature to verify. Supports both raw (64-byte R || S) and DER formats. * @returns A promise that resolves to `true` if the signature is valid, or `false` otherwise. */ async verifySignature( @@ -59,8 +61,8 @@ export class PublicKey { } /** - * Creates a PublicKey instance from a byte array. - * @param data - The byte array representing the public key. + * Creates a PublicKey instance from a byte array, validating the size and format. + * @param data - The byte array representing the public key in compressed format. * @returns A promise that resolves to a new PublicKey instance. * @throws Error if the public key size is incorrect or if the key is invalid. */