diff --git a/src/rpc/response.ts b/src/rpc/response.ts index dcfe8e9fc..a5278e21f 100644 --- a/src/rpc/response.ts +++ b/src/rpc/response.ts @@ -158,11 +158,12 @@ export class ChainGetBlockResult { public rawJSON?: any; public static fromJSON(data: any): ChainGetBlockResult { - const parsedResult = TypedJSON.parse(data, ChainGetBlockResult); + const serializer = new TypedJSON(ChainGetBlockResult); + const parsedResult = serializer.parse(data); if (!parsedResult) throw new Error('Failed to parse ChainGetBlockResult'); - parsedResult.rawJSON = JSON.stringify(data); + parsedResult.rawJSON = data; return parsedResult; } @@ -273,8 +274,9 @@ export class InfoGetTransactionResult { this.rawJSON = rawJSON; } - static fromJSON(json: string): InfoGetTransactionResult | null { - const temp = TypedJSON.parse(json, InfoGetTransactionResultV1Compatible); + static fromJSON(json: any): InfoGetTransactionResult | null { + const serializer = new TypedJSON(InfoGetTransactionResultV1Compatible); + const temp = serializer.parse(json); if (temp) { const result = InfoGetTransactionResultV1Compatible.newInfoGetTransactionResultFromV1Compatible( @@ -284,7 +286,8 @@ export class InfoGetTransactionResult { return result; } - return TypedJSON.parse(json, InfoGetTransactionResult) ?? null; + const transactionResultSerializer = new TypedJSON(InfoGetTransactionResult); + return transactionResultSerializer.parse(json) ?? null; } } @@ -356,16 +359,9 @@ export class InfoGetTransactionResultV1Compatible { rawJSON?: any; public static newInfoGetTransactionResultFromV1Compatible( - result: InfoGetTransactionResultV1Compatible, + parsedResult: InfoGetTransactionResultV1Compatible, rawJSON: any ): InfoGetTransactionResult { - const parsedResult = TypedJSON.parse( - result, - InfoGetTransactionResultV1Compatible - ); - if (!parsedResult) - throw new Error('Failed to parse InfoGetTransactionResultV1Compatible'); - if (parsedResult.transaction) { if (parsedResult.transaction.transactionV1) { return new InfoGetTransactionResult( diff --git a/src/sse/event.ts b/src/sse/event.ts index 2a7be3c1f..3520ededd 100644 --- a/src/sse/event.ts +++ b/src/sse/event.ts @@ -71,9 +71,12 @@ export class RawEvent { this.eventID = eventID; } - private parseEvent(type: new (params: any) => T): T { + private parseEvent( + type: new (params: any) => T, + parser?: (data: any) => T | Error + ): T { const serializer = new TypedJSON(type); - const parsed = serializer.parse(this.data); + const parsed = parser ? parser(this.data) : serializer.parse(this.data); if (!parsed) throw new Error('Error parsing event data'); return parsed; } @@ -87,7 +90,7 @@ export class RawEvent { } parseAsBlockAddedEvent(): BlockAddedEvent { - return this.parseEvent(BlockAddedEvent); + return this.parseEvent(BlockAddedEvent, BlockAddedEvent.fromJSON); } parseAsDeployAcceptedEvent(): DeployAcceptedEvent { @@ -95,19 +98,31 @@ export class RawEvent { } parseAsFinalitySignatureEvent(): FinalitySignatureEvent { - return this.parseEvent(FinalitySignatureEvent); + return this.parseEvent( + FinalitySignatureEvent, + FinalitySignatureEvent.deserialize + ); } parseAsTransactionExpiredEvent(): TransactionExpiredEvent { - return this.parseEvent(TransactionExpiredEvent); + return this.parseEvent( + TransactionExpiredEvent, + TransactionExpiredEvent.deserialize + ); } parseAsTransactionProcessedEvent(): TransactionProcessedEvent { - return this.parseEvent(TransactionProcessedEvent); + return this.parseEvent( + TransactionProcessedEvent, + TransactionProcessedEvent.fromJson + ); } parseAsTransactionAcceptedEvent(): TransactionAcceptedEvent { - return this.parseEvent(TransactionAcceptedEvent); + return this.parseEvent( + TransactionAcceptedEvent, + TransactionAcceptedEvent.fromJson + ); } parseAsFaultEvent(): FaultEvent { @@ -152,7 +167,7 @@ export class BlockAddedEvent { this.BlockAdded = blockAdded; } - static fromJSON(data: string): BlockAddedEvent { + static fromJSON(data: any): BlockAddedEvent { const parsedData = JSON.parse(data); if (!parsedData) { @@ -319,13 +334,10 @@ export class TransactionAcceptedEvent { public static fromJson(data: unknown): TransactionAcceptedEvent | Error { try { - const transactionEvent = TypedJSON.parse( - data as string, - TransactionAcceptedEvent - ); + const transactionEvent = TypedJSON.parse(data, TransactionAcceptedEvent); if (!transactionEvent) throw new Error('TransactionAcceptedEvent is nil'); - const wrapper = TypedJSON.parse(data as string, TransactionWrapper); + const wrapper = TypedJSON.parse(data, TransactionWrapper); if (wrapper?.deploy) { transactionEvent.transactionAcceptedPayload = { @@ -341,7 +353,7 @@ export class TransactionAcceptedEvent { return transactionEvent; } - const deployEvent = TypedJSON.parse(data as string, DeployAcceptedEvent); + const deployEvent = TypedJSON.parse(data, DeployAcceptedEvent); if (deployEvent?.deployAccepted) { transactionEvent.transactionAcceptedPayload = { transaction: Deploy.newTransactionFromDeploy( @@ -374,12 +386,9 @@ export class TransactionExpiredEvent { }) transactionExpiredPayload: TransactionExpiredPayload; - public static deserialize(data: unknown): TransactionExpiredEvent | Error { + public static deserialize(data: any): TransactionExpiredEvent | Error { try { - const transactionEvent = TypedJSON.parse( - data as string, - TransactionExpiredEvent - ); + const transactionEvent = TypedJSON.parse(data, TransactionExpiredEvent); if (!transactionEvent) throw new Error('TransactionExpiredEvent is nil'); const payload = transactionEvent.transactionExpiredPayload; @@ -391,7 +400,7 @@ export class TransactionExpiredEvent { return transactionEvent; } - const deployEvent = TypedJSON.parse(data as string, DeployExpiredEvent); + const deployEvent = TypedJSON.parse(data, DeployExpiredEvent); if (deployEvent?.deployExpired) { transactionEvent.transactionExpiredPayload = { transactionHash: new TransactionHash( @@ -450,12 +459,9 @@ export class TransactionProcessedEvent { }) transactionProcessedPayload: TransactionProcessedPayload; - public static fromJson(data: unknown): TransactionProcessedEvent | Error { + public static fromJson(data: any): TransactionProcessedEvent | Error { try { - const transactionEvent = TypedJSON.parse( - data as string, - TransactionProcessedEvent - ); + const transactionEvent = TypedJSON.parse(data, TransactionProcessedEvent); if (!transactionEvent) throw new Error('TransactionProcessedEvent is nil'); @@ -468,7 +474,7 @@ export class TransactionProcessedEvent { return transactionEvent; } - const deployEvent = TypedJSON.parse(data as string, DeployProcessedEvent); + const deployEvent = TypedJSON.parse(data, DeployProcessedEvent); if (deployEvent?.deployProcessed) { transactionEvent.transactionProcessedPayload = { blockHash: deployEvent.deployProcessed.blockHash, @@ -669,9 +675,9 @@ export class FinalitySignatureEvent { @jsonMember({ name: 'FinalitySignature', constructor: FinalitySignature }) finalitySignature: FinalitySignature; - public static deserialize(data: unknown): FinalitySignatureEvent | Error { + public static deserialize(data: any): FinalitySignatureEvent | Error { try { - const wrapped = TypedJSON.parse(data as string, FinalitySignatureWrapper); + const wrapped = TypedJSON.parse(data, FinalitySignatureWrapper); if (!wrapped) throw new Error('FinalitySignatureWrapper is nil'); let finalitySignature: FinalitySignature; @@ -693,7 +699,7 @@ export class FinalitySignatureEvent { publicKey: wrapped.v2.publicKey }; } else { - const v1Event = TypedJSON.parse(data as string, FinalitySignatureV1); + const v1Event = TypedJSON.parse(data, FinalitySignatureV1); if (!v1Event) throw new Error('Failed to parse FinalitySignatureV1'); finalitySignature = { diff --git a/src/types/Args.ts b/src/types/Args.ts index 701d02430..c590f7fb8 100644 --- a/src/types/Args.ts +++ b/src/types/Args.ts @@ -1,12 +1,12 @@ import { concat } from '@ethersproject/bytes'; import { + CLTypeString, CLValue, CLValueParser, CLValueString, CLValueUInt32, - IResultWithBytes, - CLTypeString + IResultWithBytes } from './clvalue'; import { jsonMapMember, jsonObject } from 'typedjson'; import { toBytesString, toBytesU32 } from './ByteConverters'; @@ -59,9 +59,7 @@ export class NamedArg { * @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)]; - }); + return Array.from(map, ([key, value]) => [key, CLValueParser.toJSON(value)]); }; /** diff --git a/src/types/BlockProposer.ts b/src/types/BlockProposer.ts index 8d0b96dd9..7e7e10254 100644 --- a/src/types/BlockProposer.ts +++ b/src/types/BlockProposer.ts @@ -89,7 +89,7 @@ export class Proposer { * @returns A JSON string representing the proposer. */ toJSON(): string { - return this.isSystem ? '00' : JSON.stringify(this.publicKey); + return this.isSystem ? '00' : this?.publicKey!.toJSON(); } /** diff --git a/src/types/ByteConverters.ts b/src/types/ByteConverters.ts index ad81c1102..3ec3777d7 100644 --- a/src/types/ByteConverters.ts +++ b/src/types/ByteConverters.ts @@ -91,16 +91,6 @@ export const toBytesU256 = toBytesNumber(256, false); */ export const toBytesU512 = toBytesNumber(512, false); -/** - * 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): Uint8Array => { - return deployHash; -}; - /** * Serializes a string into a byte array. * @param str - The string to be converted. diff --git a/src/types/Deploy.ts b/src/types/Deploy.ts index dd160ad69..2129e5e52 100644 --- a/src/types/Deploy.ts +++ b/src/types/Deploy.ts @@ -1,6 +1,5 @@ import { jsonArrayMember, jsonMember, jsonObject, TypedJSON } from 'typedjson'; import { concat } from '@ethersproject/bytes'; -import { BigNumber } from '@ethersproject/bignumber'; import { Hash } from './key'; import { PrivateKey } from './keypair/PrivateKey'; @@ -473,7 +472,7 @@ export class Deploy { } const serializer = new TypedJSON(Deploy); - deploy = serializer.parse(JSON.stringify(deployJson)); + deploy = serializer.parse(deployJson); if (!deploy) { throw new Error("The JSON can't be parsed as a Deploy."); @@ -524,22 +523,6 @@ export class Deploy { } } -/** - * 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`. - * - * @example - * const paymentAmount = BigNumber.from('1000000'); - * const paymentItem = standardPayment(paymentAmount); - */ -export const standardPayment = (paymentAmount: BigNumber) => { - return ExecutableDeployItem.standardPayment(paymentAmount); -}; - /** * 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. diff --git a/src/types/EntryPoint.ts b/src/types/EntryPoint.ts index 57e8c13a6..6845bc9dd 100644 --- a/src/types/EntryPoint.ts +++ b/src/types/EntryPoint.ts @@ -37,7 +37,15 @@ export class EntryPointArg { */ @jsonMember({ name: 'cl_type', - constructor: CLTypeRaw + constructor: CLTypeRaw, + deserializer: json => { + if (!json) return; + return CLTypeRaw.parseCLType(json); + }, + serializer: (value: CLTypeRaw) => { + if (!value) return; + return value.toJSON(); + } }) clType: CLTypeRaw; @@ -117,7 +125,15 @@ export class EntryPointV1 { */ @jsonMember({ name: 'ret', - constructor: CLTypeRaw + constructor: CLTypeRaw, + deserializer: json => { + if (!json) return; + return CLTypeRaw.parseCLType(json); + }, + serializer: (value: CLTypeRaw) => { + if (!value) return; + return value.toJSON(); + } }) ret: CLTypeRaw; diff --git a/src/types/ExecutableDeployItem.ts b/src/types/ExecutableDeployItem.ts index bd1730d44..e705b07d1 100644 --- a/src/types/ExecutableDeployItem.ts +++ b/src/types/ExecutableDeployItem.ts @@ -15,6 +15,7 @@ import { import { ContractHash, URef } from './key'; import { deserializeArgs, serializeArgs } from './SerializationUtils'; import { PublicKey } from './keypair'; +import { Conversions } from './Conversions'; /** * Enum representing the different types of executable deploy items. @@ -37,14 +38,12 @@ export class ModuleBytes { * The module bytes in hexadecimal format. */ @jsonMember({ name: 'module_bytes', constructor: String }) - moduleBytes: string; + moduleBytes!: string; /** * The arguments passed to the module. */ - @jsonMember({ - constructor: Args, - name: 'args', + @jsonMember(() => Args, { deserializer: deserializeArgs, serializer: serializeArgs }) @@ -109,9 +108,7 @@ export class StoredContractByHash { /** * The arguments for the contract call. */ - @jsonMember({ - constructor: Args, - name: 'args', + @jsonMember(() => Args, { deserializer: deserializeArgs, serializer: serializeArgs }) @@ -162,9 +159,7 @@ export class StoredContractByName { /** * The arguments for the contract call. */ - @jsonMember({ - constructor: Args, - name: 'args', + @jsonMember(() => Args, { deserializer: deserializeArgs, serializer: serializeArgs }) @@ -220,9 +215,7 @@ export class StoredVersionedContractByHash { /** * The arguments for the contract call. */ - @jsonMember({ - constructor: Args, - name: 'args', + @jsonMember(() => Args, { deserializer: deserializeArgs, serializer: serializeArgs }) @@ -297,9 +290,7 @@ export class StoredVersionedContractByName { /** * The arguments for the contract call. */ - @jsonMember({ - constructor: Args, - name: 'args', + @jsonMember(() => Args, { deserializer: deserializeArgs, serializer: serializeArgs }) @@ -345,9 +336,7 @@ export class TransferDeployItem { /** * The arguments for the transfer. */ - @jsonMember({ - constructor: Args, - name: 'args', + @jsonMember(() => Args, { deserializer: deserializeArgs, serializer: serializeArgs }) @@ -613,4 +602,23 @@ export class ExecutableDeployItem { public isModuleBytes(): boolean { return !!this.moduleBytes; } + + /** + * Creates a new `ModuleBytes` object from a `Uint8Array` of module bytes and a set of `RuntimeArgs` + * @param moduleBytes A set of module bytes as a `Uint8Array` + * @param args The runtime arguments for the new `ModuleBytes` object + * @returns A new `ExecutableDeployItem` created from a new `ModuleBytes` object built using `moduleBytes` and `args` + */ + public static newModuleBytes( + moduleBytes: Uint8Array, + args: Args + ): ExecutableDeployItem { + const executableDeployItem = new ExecutableDeployItem(); + executableDeployItem.moduleBytes = new ModuleBytes( + Conversions.encodeBase16(moduleBytes), + args + ); + + return executableDeployItem; + } } diff --git a/src/types/SerializationUtils.ts b/src/types/SerializationUtils.ts index a1b72eb78..716e44e5b 100644 --- a/src/types/SerializationUtils.ts +++ b/src/types/SerializationUtils.ts @@ -148,3 +148,17 @@ export const serializeArgs = (ra: Args) => { const json = raSerializer.toPlainJson(ra); return Object.values(json as any)[0]; }; + +/** + * Compares two arrays for equality. + * @param a The first array. + * @param b The second array. + * @returns `true` if the arrays are equal, `false` otherwise. + */ +export const arrayEquals = (a: Uint8Array, b: Uint8Array): boolean => { + if (a.length !== b.length) return false; + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) return false; + } + return true; +}; diff --git a/src/types/Transaction.ts b/src/types/Transaction.ts index 196a4c2fb..a6bbaeb63 100644 --- a/src/types/Transaction.ts +++ b/src/types/Transaction.ts @@ -14,7 +14,11 @@ import { HexBytes } from './HexBytes'; import { PrivateKey } from './keypair/PrivateKey'; import { CLValueString, CLValueUInt64 } from './clvalue'; import { Args } from './Args'; -import { deserializeArgs, serializeArgs } from './SerializationUtils'; +import { + arrayEquals, + deserializeArgs, + serializeArgs +} from './SerializationUtils'; import { byteHash } from './ByteConverters'; /** @@ -235,9 +239,7 @@ export class TransactionV1Body { /** * The arguments for the transaction. */ - @jsonMember({ - name: 'args', - constructor: Args, + @jsonMember(() => Args, { deserializer: deserializeArgs, serializer: serializeArgs }) @@ -387,12 +389,12 @@ export class TransactionV1 { public validate(): void { const bodyBytes = this.body.toBytes(); - if (!this.arrayEquals(byteHash(bodyBytes), this.header.bodyHash.toBytes())) + if (!arrayEquals(byteHash(bodyBytes), this.header.bodyHash.toBytes())) throw ErrInvalidBodyHash; const headerBytes = this.header.toBytes(); - if (!this.arrayEquals(byteHash(headerBytes), this.hash.toBytes())) + if (!arrayEquals(byteHash(headerBytes), this.hash.toBytes())) throw ErrInvalidTransactionHash; for (const approval of this.approvals) { @@ -407,20 +409,6 @@ 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++) { - if (a[i] !== b[i]) return false; - } - return true; - } - /** * Signs the transaction using the provided private key. * @param keys The private key to sign the transaction. @@ -514,7 +502,7 @@ export class TransactionV1 { } const serializer = new TypedJSON(TransactionV1); - tx = serializer.parse(JSON.stringify(txData)); + tx = serializer.parse(txData); if (!tx) { throw ErrTransactionV1FromJson; @@ -623,9 +611,7 @@ 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', + @jsonMember(() => Args, { deserializer: deserializeArgs, serializer: serializeArgs }) @@ -875,7 +861,10 @@ export class TransactionHash { if (!json) return; return Hash.fromJSON(json); }, - serializer: value => value.toJSON() + serializer: value => { + if (!value) return; + return value.toJSON(); + } }) public transactionV1?: Hash; diff --git a/src/types/Transform.ts b/src/types/Transform.ts index 4f45967f2..74a63aa63 100644 --- a/src/types/Transform.ts +++ b/src/types/Transform.ts @@ -499,9 +499,7 @@ export class NamedKeyKind { /** * The named key transformation data represented as `Args`. */ - @jsonMember({ - constructor: Args, - name: 'named_key', + @jsonMember(() => Args, { deserializer: deserializeArgs, serializer: serializeArgs }) @@ -510,9 +508,7 @@ export class NamedKeyKind { /** * The name of the key represented as `Args`. */ - @jsonMember({ - constructor: Args, - name: 'name', + @jsonMember(() => Args, { deserializer: deserializeArgs, serializer: serializeArgs }) diff --git a/src/types/TransformRaw.ts b/src/types/TransformRaw.ts index bfa042a8f..9a8da503a 100644 --- a/src/types/TransformRaw.ts +++ b/src/types/TransformRaw.ts @@ -31,7 +31,7 @@ export class RawWriteTransferTransform { /** * The write transfer operation. */ - @jsonMember({ name: 'WriteTransfer', constructor: WriteTransfer }) + @jsonMember({ name: 'WriteTransfer', constructor: () => WriteTransfer }) WriteTransfer?: WriteTransfer; } @@ -91,7 +91,7 @@ export class TranformBidKindData { /** * The bid kind data in the transform. */ - @jsonMember({ name: 'BidKind', constructor: BidKind }) + @jsonMember({ name: 'BidKind', constructor: () => BidKind }) BidKind?: BidKind; } @@ -103,7 +103,7 @@ export class BidKindRawData { /** * The write operation containing bid kind data. */ - @jsonMember({ name: 'Write' }) + @jsonMember({ name: 'Write', constructor: TranformBidKindData }) Write?: TranformBidKindData; } @@ -115,7 +115,7 @@ class WriteNamedKey { /** * The named key in the write operation. */ - @jsonMember({ constructor: NamedKeyKind, name: 'NamedKey' }) + @jsonMember({ constructor: () => NamedKeyKind, name: 'NamedKey' }) NamedKey?: NamedKeyKind; } @@ -235,17 +235,10 @@ export class RawWriteCLValue { /** * The write operation on a CLValue represented as `Args`. */ - @jsonMember({ - constructor: Args, - name: 'WriteCLValue', - deserializer: json => { - if (!json) return; - return deserializeArgs(json); - }, - serializer: value => { - if (!value) return; - return serializeArgs(value); - } + @jsonMember(() => Args, { + deserializer: deserializeArgs, + serializer: serializeArgs, + name: 'WriteCLValue' }) WriteCLValue?: Args; } @@ -258,17 +251,10 @@ export class WriteCLValue { /** * The CLValue write operation represented as `Args`. */ - @jsonMember({ - constructor: Args, - name: 'CLValue', - deserializer: json => { - if (!json) return; - return deserializeArgs(json); - }, - serializer: value => { - if (!value) return; - return serializeArgs(value); - } + @jsonMember(() => Args, { + deserializer: deserializeArgs, + serializer: serializeArgs, + name: 'CLValue' }) CLValue?: Args; } diff --git a/src/types/clvalue/Parser.ts b/src/types/clvalue/Parser.ts index eb93a30f9..22b98f8f4 100644 --- a/src/types/clvalue/Parser.ts +++ b/src/types/clvalue/Parser.ts @@ -4,7 +4,6 @@ import { PublicKey } from '../keypair'; import { CLType, CLTypeByteArray, - CLTypeDynamic, CLTypeList, CLTypeMap, CLTypeOption, @@ -101,121 +100,127 @@ export class CLValueParser { sourceType: CLType ): IResultWithBytes { const result = new CLValue(sourceType); + const typeID = sourceType.getTypeID(); - if (sourceType.constructor.name === 'SimpleType') { - switch (sourceType.getTypeID()) { - case TypeID.Bool: - const boolValue = CLValueBool.fromBytes(bytes); - result.bool = boolValue?.result; - return { result, bytes: boolValue.bytes }; - case TypeID.I32: - const i32 = CLValueInt32.fromBytes(bytes); - result.i32 = i32.result; - return { result, bytes: i32?.bytes }; - case TypeID.I64: - const i64 = CLValueInt64.fromBytes(bytes); - result.i64 = i64?.result; - return { result, bytes: i64?.bytes }; - case TypeID.U8: - const u8 = CLValueUInt8.fromBytes(bytes); - result.ui8 = u8?.result; - return { result, bytes: u8?.bytes }; - case TypeID.U32: - const u32 = CLValueUInt32.fromBytes(bytes); - result.ui32 = u32?.result; - return { result, bytes: u32?.bytes }; - case TypeID.U64: - const u64 = CLValueUInt64.fromBytes(bytes); - result.ui64 = u64?.result; - return { result, bytes: u64?.bytes }; - case TypeID.U128: - const u128 = CLValueUInt128.fromBytes(bytes); - result.ui128 = u128?.result; - return { result, bytes: u128?.bytes }; - case TypeID.U256: - const u256 = CLValueUInt256.fromBytes(bytes); - result.ui256 = u256?.result; - return { result, bytes: u256?.bytes }; - case TypeID.U512: - const u512 = CLValueUInt512.fromBytes(bytes); - result.ui512 = u512?.result; - return { result, bytes: u512?.bytes }; - case TypeID.String: - const stringValue = CLValueString.fromBytes(bytes); - result.stringVal = stringValue.result; - return { result, bytes: stringValue?.bytes }; - case TypeID.Unit: - const unit = CLValueUnit.fromBytes(bytes); - result.unit = unit?.result; - return { result, bytes: unit?.bytes }; - case TypeID.Key: - const key = Key.fromBytes(bytes); - result.key = key?.result; - return { result, bytes: key?.bytes }; - case TypeID.URef: - const uref = URef.fromBytes(bytes); - result.uref = uref?.result; - return { result, bytes: uref?.bytes }; - case TypeID.Any: - result.any = new CLValueAny(bytes); - return { result, bytes }; - case TypeID.PublicKey: - const pubKey = PublicKey.fromBytes(bytes); - result.publicKey = pubKey?.result; - return { result, bytes: pubKey?.bytes }; - default: - throw ErrUnsupportedCLType; - } - } else if (sourceType.constructor.name === 'CLTypeOption') { - const optionType = CLValueOption.fromBytes( - bytes, - sourceType as CLTypeOption - ); - result.option = optionType?.result; - return { result, bytes: optionType?.bytes }; - } else if (sourceType.constructor.name === 'CLTypeList') { - const listType = CLValueList.fromBytes(bytes, sourceType as CLTypeList); - result.list = listType?.result; - return { result, bytes: listType?.bytes }; - } else if (sourceType.constructor.name === 'CLTypeByteArray') { - const byteArrayType = CLValueByteArray.fromBytes( - bytes, - sourceType as CLTypeByteArray - ); - result.byteArray = byteArrayType?.result; - return { result, bytes: byteArrayType?.bytes }; - } else if (sourceType.constructor.name === 'CLTypeResult') { - const resultType = CLValueResult.fromBytes( - bytes, - sourceType as CLTypeResult - ); - result.result = resultType?.result; - return { result, bytes: resultType?.bytes }; - } else if (sourceType.constructor.name === 'CLTypeMap') { - const mapType = CLValueMap.fromBytes(bytes, sourceType as CLTypeMap); - result.map = mapType?.result; - return { result, bytes: mapType?.bytes }; - } else if (sourceType.constructor.name === 'CLTypeTuple1') { - const tuple1 = CLValueTuple1.fromBytes(bytes, sourceType as CLTypeTuple1); - result.tuple1 = tuple1.result; - return { result, bytes: tuple1?.bytes }; - } else if (sourceType.constructor.name === 'CLTypeTuple2') { - const tuple2 = CLValueTuple2.fromBytes(bytes, sourceType as CLTypeTuple2); - result.tuple2 = tuple2?.result; - return { result, bytes: tuple2?.bytes }; - } else if (sourceType.constructor.name === 'CLTypeTuple3') { - const tuple3 = CLValueTuple3.fromBytes(bytes, sourceType as CLTypeTuple3); - result.tuple3 = tuple3?.result; - return { result, bytes: tuple3?.bytes }; - } else if (sourceType.constructor.name === 'CLTypeDynamic') { - const typeData = CLTypeParser.matchBytesToCLType(bytes); - result.type = new CLTypeDynamic( - typeData.result?.getTypeID(), - typeData?.result - ); - return { result, bytes: typeData?.bytes }; - } else { - throw ErrUnsupportedCLType; + switch (typeID) { + case TypeID.Bool: + const boolValue = CLValueBool.fromBytes(bytes); + result.bool = boolValue?.result; + return { result, bytes: boolValue.bytes }; + case TypeID.I32: + const i32 = CLValueInt32.fromBytes(bytes); + result.i32 = i32.result; + return { result, bytes: i32?.bytes }; + case TypeID.I64: + const i64 = CLValueInt64.fromBytes(bytes); + result.i64 = i64?.result; + return { result, bytes: i64?.bytes }; + case TypeID.U8: + const u8 = CLValueUInt8.fromBytes(bytes); + result.ui8 = u8?.result; + return { result, bytes: u8?.bytes }; + case TypeID.U32: + const u32 = CLValueUInt32.fromBytes(bytes); + result.ui32 = u32?.result; + return { result, bytes: u32?.bytes }; + case TypeID.U64: + const u64 = CLValueUInt64.fromBytes(bytes); + result.ui64 = u64?.result; + return { result, bytes: u64?.bytes }; + case TypeID.U128: + const u128 = CLValueUInt128.fromBytes(bytes); + result.ui128 = u128?.result; + return { result, bytes: u128?.bytes }; + case TypeID.U256: + const u256 = CLValueUInt256.fromBytes(bytes); + result.ui256 = u256?.result; + return { result, bytes: u256?.bytes }; + case TypeID.U512: + const u512 = CLValueUInt512.fromBytes(bytes); + result.ui512 = u512?.result; + return { result, bytes: u512?.bytes }; + case TypeID.String: + const stringValue = CLValueString.fromBytes(bytes); + result.stringVal = stringValue.result; + return { result, bytes: stringValue?.bytes }; + case TypeID.Unit: + const unit = CLValueUnit.fromBytes(bytes); + result.unit = unit?.result; + return { result, bytes: unit?.bytes }; + case TypeID.Key: + const key = Key.fromBytes(bytes); + result.key = key?.result; + return { result, bytes: key?.bytes }; + case TypeID.URef: + const uref = URef.fromBytes(bytes); + result.uref = uref?.result; + return { result, bytes: uref?.bytes }; + case TypeID.Any: + result.any = new CLValueAny(bytes); + return { result, bytes }; + case TypeID.PublicKey: + const pubKey = PublicKey.fromBytes(bytes); + result.publicKey = pubKey?.result; + return { result, bytes: pubKey?.bytes }; + case TypeID.Option: + const optionType = CLValueOption.fromBytes( + bytes, + sourceType as CLTypeOption + ); + result.option = optionType?.result; + return { result, bytes: optionType?.bytes }; + case TypeID.List: + const listType = CLValueList.fromBytes(bytes, sourceType as CLTypeList); + result.list = listType?.result; + return { result, bytes: listType?.bytes }; + case TypeID.ByteArray: + const byteArrayType = CLValueByteArray.fromBytes( + bytes, + sourceType as CLTypeByteArray + ); + result.byteArray = byteArrayType?.result; + return { result, bytes: byteArrayType?.bytes }; + case TypeID.Result: + const resultType = CLValueResult.fromBytes( + bytes, + sourceType as CLTypeResult + ); + result.result = resultType?.result; + return { result, bytes: resultType?.bytes }; + case TypeID.Map: + const mapType = CLValueMap.fromBytes(bytes, sourceType as CLTypeMap); + result.map = mapType?.result; + return { result, bytes: mapType?.bytes }; + case TypeID.Tuple1: + const tuple1 = CLValueTuple1.fromBytes( + bytes, + sourceType as CLTypeTuple1 + ); + result.tuple1 = tuple1.result; + return { result, bytes: tuple1?.bytes }; + case TypeID.Tuple2: + const tuple2 = CLValueTuple2.fromBytes( + bytes, + sourceType as CLTypeTuple2 + ); + result.tuple2 = tuple2?.result; + return { result, bytes: tuple2?.bytes }; + case TypeID.Tuple3: + const tuple3 = CLValueTuple3.fromBytes( + bytes, + sourceType as CLTypeTuple3 + ); + result.tuple3 = tuple3?.result; + return { result, bytes: tuple3?.bytes }; + // case TypeID.Dynamic: + // const typeData = CLTypeParser.matchBytesToCLType(bytes); + // result.type = new CLTypeDynamic( + // typeData.result?.getTypeID(), + // typeData?.result + // ); + // return { result, bytes: typeData?.bytes }; + default: + throw ErrUnsupportedCLType; } } } diff --git a/src/types/clvalue/cltype/CLTypeRaw.ts b/src/types/clvalue/cltype/CLTypeRaw.ts index b067b9670..57f391b1e 100644 --- a/src/types/clvalue/cltype/CLTypeRaw.ts +++ b/src/types/clvalue/cltype/CLTypeRaw.ts @@ -1,4 +1,4 @@ -import { AnyT, jsonMember, jsonObject } from 'typedjson'; +import { jsonObject } from 'typedjson'; import { CLType } from './CLType'; import { CLTypeParser } from './Parser'; @@ -11,14 +11,13 @@ export class CLTypeRaw { /** * The raw message string representation of a CLType. */ - @jsonMember({ constructor: AnyT, name: 'RawMessage' }) - rawMessage: any; + private rawMessage: CLType; /** * Initializes a new instance of the CLTypeRaw class. * @param rawMessage - A string representing the raw CLType message. */ - constructor(rawMessage: any) { + constructor(rawMessage: CLType) { this.rawMessage = rawMessage; } @@ -27,11 +26,20 @@ export class CLTypeRaw { * @returns A `CLType` instance if parsing is successful. * @throws Error if parsing fails, with a descriptive error message. */ - parseCLType(): CLType | Error { + static parseCLType(json: any): CLType | Error { try { - return CLTypeParser.fromRawJson(this.rawMessage); + return CLTypeParser.fromRawJson(json); } catch (error) { throw new Error(`Error parsing CLType: ${error.message}`); } } + + /** + * 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. + */ + toJSON(): any { + return this.rawMessage?.toString() || this?.rawMessage?.toJSON(); + } } diff --git a/src/types/clvalue/cltype/Parser.ts b/src/types/clvalue/cltype/Parser.ts index 0b0f05f82..1d0227219 100644 --- a/src/types/clvalue/cltype/Parser.ts +++ b/src/types/clvalue/cltype/Parser.ts @@ -122,10 +122,9 @@ export class CLTypeParser { * @param source - The raw JSON string to parse. * @returns The parsed CLType. */ - static fromRawJson(source: string): CLType { + static fromRawJson(source: any): CLType { try { - const rawData = JSON.parse(source); - return CLTypeParser.fromInterface(rawData); + return CLTypeParser.fromInterface(source); } catch (err) { return CLTypeParser.getSimpleTypeByName(source as TypeName); } diff --git a/src/types/key/Hash.ts b/src/types/key/Hash.ts index 2a94b16d0..1b3bb7e55 100644 --- a/src/types/key/Hash.ts +++ b/src/types/key/Hash.ts @@ -1,5 +1,4 @@ import { jsonObject } from 'typedjson'; -import { Conversions } from '../Conversions'; import { IResultWithBytes } from '../clvalue'; /** @@ -51,7 +50,7 @@ export class Hash { * @returns The hexadecimal string representation of the hash. */ toHex(): string { - return Conversions.encodeBase16(this.hashBytes); + return Buffer.from(this.hashBytes).toString('hex'); } /** diff --git a/src/types/keypair/PrivateKey.ts b/src/types/keypair/PrivateKey.ts index 985006d14..27e2342f5 100644 --- a/src/types/keypair/PrivateKey.ts +++ b/src/types/keypair/PrivateKey.ts @@ -27,8 +27,8 @@ interface PrivateKeyInternal { * Enum representing supported cryptographic key algorithms. */ enum KeyAlgorithm { - ED25519, - SECP256K1 + ED25519 = 1, + SECP256K1 = 2 } /**