From 1b702e70f4d79a8556bb53db3067f3b87a64c8b6 Mon Sep 17 00:00:00 2001 From: Oleksandr Myshchyshyn Date: Mon, 23 Dec 2024 12:54:29 +0200 Subject: [PATCH 1/2] Fixed Tuple3 constructor inconsistency, aligned Numerics CLValue by value type --- src/types/Deploy.test.ts | 3 +- src/types/EraEnd.ts | 9 +- src/types/PricingMode.ts | 2 +- src/types/SerializationUtils.ts | 36 ++++++ src/types/clvalue/Bool.test.ts | 2 +- src/types/clvalue/Bool.ts | 2 +- src/types/clvalue/CLValue.ts | 18 +-- src/types/clvalue/List.test.ts | 10 +- src/types/clvalue/List.ts | 4 +- src/types/clvalue/Map.ts | 4 +- src/types/clvalue/Numeric/Abstract.ts | 56 +++++++++ src/types/clvalue/{ => Numeric}/Int32.ts | 42 +------ src/types/clvalue/{ => Numeric}/Int64.ts | 42 +------ src/types/clvalue/Numeric/Uint128.ts | 47 ++++++++ src/types/clvalue/Numeric/Uint256.ts | 47 ++++++++ src/types/clvalue/Numeric/Uint32.ts | 51 +++++++++ src/types/clvalue/Numeric/Uint512.ts | 63 +++++++++++ src/types/clvalue/{ => Numeric}/Uint64.ts | 43 ++----- src/types/clvalue/Numeric/Uint8.ts | 49 ++++++++ src/types/clvalue/Numeric/index.ts | 8 ++ src/types/clvalue/Option.ts | 4 +- src/types/clvalue/Parser.ts | 20 ++-- src/types/clvalue/Result.ts | 2 +- src/types/clvalue/String.ts | 4 +- src/types/clvalue/Tuple3.ts | 9 +- src/types/clvalue/Uint128.ts | 77 ------------- src/types/clvalue/Uint256.ts | 77 ------------- src/types/clvalue/Uint32.ts | 90 --------------- src/types/clvalue/Uint512.ts | 132 ---------------------- src/types/clvalue/Uint8.ts | 77 ------------- src/types/clvalue/UintBig.ts | 4 +- src/types/clvalue/index.ts | 9 +- src/utils/cep-nft-transfer.ts | 43 +++++-- 33 files changed, 458 insertions(+), 628 deletions(-) create mode 100644 src/types/clvalue/Numeric/Abstract.ts rename src/types/clvalue/{ => Numeric}/Int32.ts (63%) rename src/types/clvalue/{ => Numeric}/Int64.ts (64%) create mode 100644 src/types/clvalue/Numeric/Uint128.ts create mode 100644 src/types/clvalue/Numeric/Uint256.ts create mode 100644 src/types/clvalue/Numeric/Uint32.ts create mode 100644 src/types/clvalue/Numeric/Uint512.ts rename src/types/clvalue/{ => Numeric}/Uint64.ts (61%) create mode 100644 src/types/clvalue/Numeric/Uint8.ts create mode 100644 src/types/clvalue/Numeric/index.ts delete mode 100644 src/types/clvalue/Uint128.ts delete mode 100644 src/types/clvalue/Uint256.ts delete mode 100644 src/types/clvalue/Uint32.ts delete mode 100644 src/types/clvalue/Uint512.ts delete mode 100644 src/types/clvalue/Uint8.ts diff --git a/src/types/Deploy.test.ts b/src/types/Deploy.test.ts index 20f347689..f4b4424ab 100644 --- a/src/types/Deploy.test.ts +++ b/src/types/Deploy.test.ts @@ -6,8 +6,7 @@ import { TransferDeployItem } from './ExecutableDeployItem'; import { Deploy, DeployHeader } from './Deploy'; -import { PrivateKey } from './keypair/PrivateKey'; -import { KeyAlgorithm } from './keypair/Algorithm'; +import { KeyAlgorithm, PrivateKey } from './keypair'; import { Duration, Timestamp } from './Time'; import { Hash } from './key'; import { dehumanizerTTL, humanizerTTL } from './SerializationUtils'; diff --git a/src/types/EraEnd.ts b/src/types/EraEnd.ts index cf4970622..9f98268a2 100644 --- a/src/types/EraEnd.ts +++ b/src/types/EraEnd.ts @@ -6,11 +6,8 @@ import { } from 'typedjson'; import { PublicKey } from './keypair'; import { ValidatorWeightEraEnd } from './ValidatorWeight'; -import { - CLValueUInt512, - deserializeRewards, - serializeRewards -} from './clvalue'; +import { CLValueUInt512 } from './clvalue'; +import { deserializeRewards, serializeRewards } from './SerializationUtils'; /** * Class representing the rewards associated with a validator in a given era. @@ -252,7 +249,7 @@ export class EraEnd { @jsonMapMember(String, CLValueUInt512, { name: 'rewards', deserializer: deserializeRewards, - serializer: (map: Map) => serializeRewards(map), + serializer: (map: Map) => serializeRewards(map) }) public rewards: Map; diff --git a/src/types/PricingMode.ts b/src/types/PricingMode.ts index e27eed321..a2adbc0d9 100644 --- a/src/types/PricingMode.ts +++ b/src/types/PricingMode.ts @@ -40,7 +40,7 @@ export class PaymentLimitedMode { ); calltableSerializer.addField( 3, - CLValueBool.fromBoolean(this.standardPayment).bytes() + CLValueBool.newCLValueBool(this.standardPayment).bytes() ); return calltableSerializer.toBytes(); diff --git a/src/types/SerializationUtils.ts b/src/types/SerializationUtils.ts index d3d3e5593..b4f64b2e4 100644 --- a/src/types/SerializationUtils.ts +++ b/src/types/SerializationUtils.ts @@ -2,6 +2,7 @@ import { TypedJSON } from 'typedjson'; import humanizeDuration from 'humanize-duration'; import { Args } from './Args'; import { Conversions } from './Conversions'; +import { CLValueUInt512 } from './clvalue'; /** * Serializes a `Uint8Array` into a hexadecimal string. @@ -172,3 +173,38 @@ export const serializeArgs = (ra: Args, asNamed = false) => { return argsArray; }; + +/** + * 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]) => { + const valuesArray = value.map((item: any) => + CLValueUInt512.fromJSON(item) + ); + return [key, valuesArray]; + }) + ); + + if (parsed.size !== Array.from(arr).length) { + throw Error(`Duplicate key exists.`); + } + + 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()); + return [key, serializedValue]; + }); +}; diff --git a/src/types/clvalue/Bool.test.ts b/src/types/clvalue/Bool.test.ts index afe9c65c8..c4c2706a1 100644 --- a/src/types/clvalue/Bool.test.ts +++ b/src/types/clvalue/Bool.test.ts @@ -31,7 +31,7 @@ describe('CLBool', () => { }); it('toJSON() / fromJSON() do proper bytes serialization', () => { - const myBool = CLValueBool.fromBoolean(false); + const myBool = CLValueBool.newCLValueBool(false); const json = CLValueParser.toJSON(myBool); const expectedJson = JSON.parse('{"bytes":"00","cl_type":"Bool"}'); diff --git a/src/types/clvalue/Bool.ts b/src/types/clvalue/Bool.ts index 2a58d96bf..f35fababb 100644 --- a/src/types/clvalue/Bool.ts +++ b/src/types/clvalue/Bool.ts @@ -54,7 +54,7 @@ export class CLValueBool { * @param val - The boolean value to be stored in the CLValue. * @returns A new CLValue instance encapsulating the boolean value. */ - public static fromBoolean(val: boolean): CLValue { + public static newCLValueBool(val: boolean): CLValue { const res = new CLValue(CLTypeBool); res.bool = new CLValueBool(val); return res; diff --git a/src/types/clvalue/CLValue.ts b/src/types/clvalue/CLValue.ts index a48a0a7ea..70b640c16 100644 --- a/src/types/clvalue/CLValue.ts +++ b/src/types/clvalue/CLValue.ts @@ -8,15 +8,17 @@ import { } from './cltype'; import { URef, Key } from '../key'; import { PublicKey } from '../keypair'; -import { CLValueUInt8 } from './Uint8'; -import { CLValueInt64 } from './Int64'; -import { CLValueInt32 } from './Int32'; +import { + CLValueUInt8, + CLValueInt64, + CLValueInt32, + CLValueUInt32, + CLValueUInt64, + CLValueUInt128, + CLValueUInt256, + CLValueUInt512 +} from './Numeric'; import { CLValueBool } from './Bool'; -import { CLValueUInt32 } from './Uint32'; -import { CLValueUInt64 } from './Uint64'; -import { CLValueUInt128 } from './Uint128'; -import { CLValueUInt256 } from './Uint256'; -import { CLValueUInt512 } from './Uint512'; import { CLValueUnit } from './Unit'; import { CLValueOption } from './Option'; import { CLValueList } from './List'; diff --git a/src/types/clvalue/List.test.ts b/src/types/clvalue/List.test.ts index 13ee12b0e..46cb7d2a5 100644 --- a/src/types/clvalue/List.test.ts +++ b/src/types/clvalue/List.test.ts @@ -2,7 +2,7 @@ import { expect } from 'chai'; import { CLTypeBool, CLTypeList, CLTypeUInt32 } from './cltype'; import { concat } from '@ethersproject/bytes'; import { toBytesU32 } from '../ByteConverters'; -import { CLValueUInt32 } from './Uint32'; +import { CLValueUInt32 } from './Numeric/Uint32'; import { CLValueList } from './List'; import { BigNumber } from '@ethersproject/bignumber'; import { CLValue } from './CLValue'; @@ -108,8 +108,8 @@ describe('CLValueList with boolean values', () => { beforeEach(() => { boolTypeList = new CLTypeList(CLTypeBool); - trueElement = CLValueBool.fromBoolean(true); - falseElement = CLValueBool.fromBoolean(false); + trueElement = CLValueBool.newCLValueBool(true); + falseElement = CLValueBool.newCLValueBool(false); clValueBoolList = new CLValueList(boolTypeList, [ trueElement, falseElement @@ -135,7 +135,7 @@ describe('CLValueList with boolean values', () => { }); it('should add a boolean element to the list when calling append()', () => { - const newElement = CLValueBool.fromBoolean(true); + const newElement = CLValueBool.newCLValueBool(true); clValueBoolList.append(newElement); expect(clValueBoolList.elements).to.deep.equal([ trueElement, @@ -151,7 +151,7 @@ describe('CLValueList with boolean values', () => { }); it('should throw error if index is out of bounds in set() for boolean list', () => { - const newElement = CLValueBool.fromBoolean(false); + const newElement = CLValueBool.newCLValueBool(false); expect(() => clValueBoolList.set(2, newElement)).to.throw( 'List index out of bounds.' ); diff --git a/src/types/clvalue/List.ts b/src/types/clvalue/List.ts index 7a64e1ff0..90e2563dd 100644 --- a/src/types/clvalue/List.ts +++ b/src/types/clvalue/List.ts @@ -2,7 +2,7 @@ import { concat } from '@ethersproject/bytes'; import { CLType, CLTypeList } from './cltype'; import { CLValue, IResultWithBytes } from './CLValue'; -import { CLValueUInt32 } from './Uint32'; +import { CLValueUInt32 } from './Numeric'; import { CLValueParser } from './Parser'; import { toBytesU32 } from '../ByteConverters'; @@ -152,7 +152,7 @@ export class CLValueList { clType: CLTypeList ): IResultWithBytes { const { result: u32, bytes: u32Bytes } = CLValueUInt32.fromBytes(source); - const size = u32.getValue().toNumber(); + const size = u32.toNumber(); let remainder = u32Bytes; const elements: CLValue[] = []; diff --git a/src/types/clvalue/Map.ts b/src/types/clvalue/Map.ts index 3146aad74..e0666cbb1 100644 --- a/src/types/clvalue/Map.ts +++ b/src/types/clvalue/Map.ts @@ -3,7 +3,7 @@ import { concat } from '@ethersproject/bytes'; import { CLType, CLTypeMap } from './cltype'; import { CLValue, IResultWithBytes } from './CLValue'; import { CLValueTuple2 } from './Tuple2'; -import { CLValueUInt32 } from './Uint32'; +import { CLValueUInt32 } from './Numeric'; import { CLValueParser } from './Parser'; import { toBytesU32 } from '../ByteConverters'; @@ -194,7 +194,7 @@ export class CLValueMap { const mapResult = new CLValueMap(mapType); const { result: u32, bytes: u32Bytes } = CLValueUInt32.fromBytes(bytes); - const size = u32.getValue().toNumber(); + const size = u32.toNumber(); let remainder = u32Bytes; if (size === 0) { diff --git a/src/types/clvalue/Numeric/Abstract.ts b/src/types/clvalue/Numeric/Abstract.ts new file mode 100644 index 000000000..6faef7dc6 --- /dev/null +++ b/src/types/clvalue/Numeric/Abstract.ts @@ -0,0 +1,56 @@ +import { BigNumber, BigNumberish } from '@ethersproject/bignumber'; + +/** + * Abstract class representing a numeric value in the Casper type system. + * Provides common methods and properties for numeric types. + */ +export abstract class CLValueNumeric { + protected value: BigNumberish; + + /** + * The constructor is protected to ensure this class cannot be instantiated directly. + * Subclasses can call this constructor using `super`. + */ + protected constructor(value: BigNumberish) { + this.value = value; + } + + /** + * Converts the numeric value to its byte representation. + * Must be implemented by subclasses. + */ + public abstract bytes(): Uint8Array; + + /** + * Provides a string representation of the numeric value. + * @returns The string representation of the value. + */ + public toString(): string { + return this.value.toString(); + } + + /** + * Converts the numeric value to a JavaScript number. + * @returns The numeric value as a JavaScript number. + */ + public toNumber(): number { + const bigNumber = BigNumber.from(this.value); + return bigNumber.toNumber(); + } + + /** + * Converts the instance to a JSON-compatible string. + * @returns {string} The string representation of the instance. + */ + public toJSON(): string { + return this.toString(); + } + + /** + * Retrieves the numeric value. + * @returns The numeric representation of the value. + */ + public getValue(): BigNumberish { + return this.value; + } +} diff --git a/src/types/clvalue/Int32.ts b/src/types/clvalue/Numeric/Int32.ts similarity index 63% rename from src/types/clvalue/Int32.ts rename to src/types/clvalue/Numeric/Int32.ts index d705d0602..b4bcde3f6 100644 --- a/src/types/clvalue/Int32.ts +++ b/src/types/clvalue/Numeric/Int32.ts @@ -1,22 +1,17 @@ import { BigNumber, BigNumberish } from '@ethersproject/bignumber'; -import { CLTypeInt32, Int32ByteSize } from './cltype'; -import { CLValue, IResultWithBytes } from './CLValue'; -import { toBytesI32 } from '../ByteConverters'; +import { CLTypeInt32, Int32ByteSize } from '../cltype'; +import { CLValue, IResultWithBytes } from '../CLValue'; +import { toBytesI32 } from '../../ByteConverters'; +import { CLValueNumeric } from './Abstract'; /** * 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; - - /** - * Initializes a new instance of the CLValueInt32 class. - * @param value - The 32-bit integer value to be stored in the CLValueInt32. - */ +export class CLValueInt32 extends CLValueNumeric { constructor(value: BigNumberish) { - this.value = value; + super(value); } /** @@ -27,31 +22,6 @@ export class CLValueInt32 { return toBytesI32(this.value); } - /** - * Provides a string representation of the Int32 value. - * @returns The string representation of the stored value. - */ - public toString(): string { - return this.value.toString(); - } - - /** - * Converts the instance to a JSON-compatible string. - * - * @returns {string} The string representation of the instance. - */ - public toJSON(): string { - return this.toString(); - } - - /** - * Retrieves the numeric value of the Int32. - * @returns The numeric representation of the value. - */ - public getValue(): BigNumberish { - return this.value; - } - /** * Creates a new CLValue instance with an Int32 value. * @param val - The 32-bit integer to be encapsulated in a CLValue. diff --git a/src/types/clvalue/Int64.ts b/src/types/clvalue/Numeric/Int64.ts similarity index 64% rename from src/types/clvalue/Int64.ts rename to src/types/clvalue/Numeric/Int64.ts index bbccbbe3a..a201b299b 100644 --- a/src/types/clvalue/Int64.ts +++ b/src/types/clvalue/Numeric/Int64.ts @@ -1,22 +1,17 @@ import { BigNumber, BigNumberish } from '@ethersproject/bignumber'; -import { CLTypeInt64, Int64ByteSize } from './cltype'; -import { CLValue, IResultWithBytes } from './CLValue'; -import { toBytesI64 } from '../ByteConverters'; +import { CLTypeInt64, Int64ByteSize } from '../cltype'; +import { CLValue, IResultWithBytes } from '../CLValue'; +import { toBytesI64 } from '../../ByteConverters'; +import { CLValueNumeric } from './Abstract'; /** * 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; - - /** - * Initializes a new instance of the CLValueInt64 class. - * @param value - The value to be stored in the CLValueInt64. Accepts any BigNumberish type. - */ +export class CLValueInt64 extends CLValueNumeric { constructor(value: BigNumberish) { - this.value = value; + super(value); } /** @@ -27,31 +22,6 @@ export class CLValueInt64 { return toBytesI64(this.value); } - /** - * Provides a string representation of the Int64 value. - * @returns The string representation of the stored value. - */ - public toString(): string { - return this.value.toString(); - } - - /** - * Converts the instance to a JSON-compatible string. - * - * @returns {string} The string representation of the instance. - */ - public toJSON(): string { - return this.toString(); - } - - /** - * Retrieves the bigint value of the Int64. - * @returns The bigint representation of the stored value. - */ - public getValue(): BigNumberish { - return this.value; - } - /** * Creates a new CLValue instance with an Int64 value. * @param val - The value to be stored in the Int64. Accepts any BigNumberish type. diff --git a/src/types/clvalue/Numeric/Uint128.ts b/src/types/clvalue/Numeric/Uint128.ts new file mode 100644 index 000000000..ba81fc6f5 --- /dev/null +++ b/src/types/clvalue/Numeric/Uint128.ts @@ -0,0 +1,47 @@ +import { BigNumberish } from '@ethersproject/bignumber'; + +import { CLTypeUInt128 } from '../cltype'; +import { fromBytesUInt128 } from '../UintBig'; +import { CLValue, IResultWithBytes } from '../CLValue'; +import { toBytesU128 } from '../../ByteConverters'; +import { CLValueNumeric } from './Abstract'; + +/** + * Represents a 128-bit unsigned integer value in the Casper type system. + */ +export class CLValueUInt128 extends CLValueNumeric { + constructor(value: BigNumberish) { + super(value); + } + + /** + * Converts the UInt128 value to its byte representation. + * @returns A Uint8Array representing the bytes of the UInt128 value. + */ + public bytes(): Uint8Array { + return toBytesU128(this.value); + } + + /** + * Creates a new CLValue instance with a UInt128 value. + * @param value - The value to initialize the UInt128 with. + * @returns A new CLValue instance containing CLTypeUInt128 and a CLValueUInt128. + */ + public static newCLUInt128(value: BigNumberish): CLValue { + const res = new CLValue(CLTypeUInt128); + res.ui128 = new CLValueUInt128(value); + return res; + } + + /** + * 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 An object containing the new CLValueUInt128 instance and any remaining bytes. + */ + public static fromBytes( + source: Uint8Array + ): IResultWithBytes { + return fromBytesUInt128(source); + } +} diff --git a/src/types/clvalue/Numeric/Uint256.ts b/src/types/clvalue/Numeric/Uint256.ts new file mode 100644 index 000000000..23491a5f9 --- /dev/null +++ b/src/types/clvalue/Numeric/Uint256.ts @@ -0,0 +1,47 @@ +import { BigNumberish } from '@ethersproject/bignumber'; + +import { fromBytesUInt256 } from '../UintBig'; +import { CLValue, IResultWithBytes } from '../CLValue'; +import { CLTypeUInt256 } from '../cltype'; +import { toBytesU256 } from '../../ByteConverters'; +import { CLValueNumeric } from './Abstract'; + +/** + * Represents a 256-bit unsigned integer value in the Casper type system. + */ +export class CLValueUInt256 extends CLValueNumeric { + constructor(value: BigNumberish) { + super(value); + } + + /** + * Converts the UInt256 value to its byte representation. + * @returns A Uint8Array representing the bytes of the UInt256 value. + */ + public bytes(): Uint8Array { + return toBytesU256(this.value); + } + + /** + * Creates a new CLValue instance with a UInt256 value. + * @param value - The value to initialize the UInt256 with. + * @returns A new CLValue instance containing CLTypeUInt256 and a CLValueUInt256. + */ + public static newCLUInt256(value: BigNumberish): CLValue { + const res = new CLValue(CLTypeUInt256); + res.ui256 = new CLValueUInt256(value); + return res; + } + + /** + * 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 An object containing the new CLValueUInt256 instance and any remaining bytes. + */ + public static fromBytes( + source: Uint8Array + ): IResultWithBytes { + return fromBytesUInt256(source); + } +} diff --git a/src/types/clvalue/Numeric/Uint32.ts b/src/types/clvalue/Numeric/Uint32.ts new file mode 100644 index 000000000..bf782d9a8 --- /dev/null +++ b/src/types/clvalue/Numeric/Uint32.ts @@ -0,0 +1,51 @@ +import { BigNumber, BigNumberish } from '@ethersproject/bignumber'; + +import { CLTypeUInt32, Int32ByteSize } from '../cltype'; +import { CLValue, IResultWithBytes } from '../CLValue'; +import { toBytesU32 } from '../../ByteConverters'; +import { CLValueNumeric } from './Abstract'; + +/** + * Represents a 32-bit unsigned integer value in the Casper type system. + */ +export class CLValueUInt32 extends CLValueNumeric { + constructor(value: BigNumberish) { + super(value); + } + + /** + * 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); + } + + /** + * Creates a new CLValue instance with a UInt32 value. + * @param value - The value to initialize the UInt32 with. + * @returns A new CLValue instance containing CLTypeUInt32 and a CLValueUInt32. + */ + public static newCLUInt32(value: BigNumberish): CLValue { + const res = new CLValue(CLTypeUInt32); + res.ui32 = new CLValueUInt32(value); + return res; + } + + /** + * 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 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) { + throw new Error('Buffer size is too small for UInt32'); + } + const u32Bytes = Uint8Array.from(source.subarray(0, 4)); + const u32 = BigNumber.from(u32Bytes.slice().reverse()); + + return { result: new CLValueUInt32(u32), bytes: source.subarray(4) }; + } +} diff --git a/src/types/clvalue/Numeric/Uint512.ts b/src/types/clvalue/Numeric/Uint512.ts new file mode 100644 index 000000000..836ae5973 --- /dev/null +++ b/src/types/clvalue/Numeric/Uint512.ts @@ -0,0 +1,63 @@ +import { BigNumber, BigNumberish } from '@ethersproject/bignumber'; + +import { fromBytesUInt512 } from '../UintBig'; +import { CLValue, IResultWithBytes } from '../CLValue'; +import { CLTypeUInt512 } from '../cltype'; +import { toBytesU512 } from '../../ByteConverters'; +import { CLValueNumeric } from './Abstract'; + +/** + * Represents a 512-bit unsigned integer value in the Casper type system. + */ +export class CLValueUInt512 extends CLValueNumeric { + constructor(value: BigNumberish) { + super(value); + } + + /** + * Converts the UInt512 value to its byte representation. + * @returns A Uint8Array representing the bytes of the UInt512 value. + */ + public bytes(): Uint8Array { + return toBytesU512(this.value); + } + + /** + * Creates a CLValueUInt512 instance from a JSON representation. + * @param json - The JSON representation of the UInt512 value. Can be a string or a number. + * @returns A new CLValueUInt512 instance. + * @throws Will throw an error if the input is not a valid integer or is negative. + */ + public static fromJSON(json: string | number): CLValueUInt512 { + const num = BigNumber.from(json); + + if (!num.mod(1).isZero() || num.isNegative()) { + throw new Error(`Invalid integer string: ${json}`); + } + + return new CLValueUInt512(num); + } + + /** + * 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 An object containing the new CLValueUInt512 instance and any remaining bytes. + */ + public static fromBytes( + source: Uint8Array + ): IResultWithBytes { + return fromBytesUInt512(source); + } + + /** + * Creates a new CLValue instance with a UInt512 value. + * @param value - The value to initialize the UInt512 with. + * @returns A new CLValue instance containing CLTypeUInt512 and a CLValueUInt512. + */ + public static newCLUInt512(value: BigNumberish): CLValue { + const res = new CLValue(CLTypeUInt512); + res.ui512 = new CLValueUInt512(value); + return res; + } +} diff --git a/src/types/clvalue/Uint64.ts b/src/types/clvalue/Numeric/Uint64.ts similarity index 61% rename from src/types/clvalue/Uint64.ts rename to src/types/clvalue/Numeric/Uint64.ts index e098bad71..5d557d515 100644 --- a/src/types/clvalue/Uint64.ts +++ b/src/types/clvalue/Numeric/Uint64.ts @@ -1,20 +1,16 @@ import { BigNumber, BigNumberish } from '@ethersproject/bignumber'; -import { CLTypeUInt64, Int64ByteSize } from './cltype'; -import { CLValue, IResultWithBytes } from './CLValue'; -import { toBytesU64 } from '../ByteConverters'; + +import { CLTypeUInt64, Int64ByteSize } from '../cltype'; +import { CLValue, IResultWithBytes } from '../CLValue'; +import { toBytesU64 } from '../../ByteConverters'; +import { CLValueNumeric } from './Abstract'; /** * Represents a 64-bit unsigned integer value in the Casper type system. */ -export class CLValueUInt64 { - private value: BigNumberish; - - /** - * Initializes a new instance of the CLValueUInt64 class. - * @param value - The value to initialize the CLValueUInt64 with. Can be any BigNumberish type. - */ +export class CLValueUInt64 extends CLValueNumeric { constructor(value: BigNumberish) { - this.value = value; + super(value); } /** @@ -25,31 +21,6 @@ export class CLValueUInt64 { return toBytesU64(this.value); } - /** - * Provides a string representation of the UInt64 value. - * @returns The string representation of the value. - */ - public toString(): string { - return this.value.toString(); - } - - /** - * Retrieves the BigNumberish value of the UInt64. - * @returns The BigNumberish representation of the value. - */ - public getValue(): BigNumberish { - return this.value; - } - - /** - * Converts the instance to a JSON-compatible string. - * - * @returns {string} The string representation of the instance. - */ - public toJSON(): string { - return this.toString(); - } - /** * Creates a new CLValue instance with a UInt64 value. * @param val - The value to initialize the UInt64 with. Can be any BigNumberish type. diff --git a/src/types/clvalue/Numeric/Uint8.ts b/src/types/clvalue/Numeric/Uint8.ts new file mode 100644 index 000000000..7d97e5a78 --- /dev/null +++ b/src/types/clvalue/Numeric/Uint8.ts @@ -0,0 +1,49 @@ +import { BigNumberish } from '@ethersproject/bignumber'; + +import { CLValue, IResultWithBytes } from '../CLValue'; +import { CLTypeUInt8 } from '../cltype'; +import { toBytesU8 } from '../../ByteConverters'; +import { CLValueNumeric } from './Abstract'; + +/** + * Represents an 8-bit unsigned integer value in the Casper type system. + */ +export class CLValueUInt8 extends CLValueNumeric { + constructor(value: BigNumberish) { + super(value); + } + + /** + * Converts the UInt8 value to its byte representation. + * @returns A Uint8Array containing a single byte representing the UInt8 value. + */ + public bytes(): Uint8Array { + return toBytesU8(this.value); + } + + /** + * Creates a new CLValue instance with a UInt8 value. + * @param value - 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(value: BigNumberish): CLValue { + const res = new CLValue(CLTypeUInt8); + res.ui8 = new CLValueUInt8(value); + return res; + } + + /** + * 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 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) { + throw new Error('Insufficient buffer length for UInt8'); + } + + return { result: new CLValueUInt8(source[0]), bytes: source.subarray(1) }; + } +} diff --git a/src/types/clvalue/Numeric/index.ts b/src/types/clvalue/Numeric/index.ts new file mode 100644 index 000000000..e3e38a89c --- /dev/null +++ b/src/types/clvalue/Numeric/index.ts @@ -0,0 +1,8 @@ +export * from './Uint256'; +export * from './Uint128'; +export * from './Uint512'; +export * from './Uint64'; +export * from './Uint8'; +export * from './Uint32'; +export * from './Int32'; +export * from './Int64'; diff --git a/src/types/clvalue/Option.ts b/src/types/clvalue/Option.ts index db9e87a5d..cb65d767f 100644 --- a/src/types/clvalue/Option.ts +++ b/src/types/clvalue/Option.ts @@ -3,7 +3,7 @@ import { concat } from '@ethersproject/bytes'; import { CLType, CLTypeAny, CLTypeOption } from './cltype'; import { CLValue, IResultWithBytes } from './CLValue'; import { CLValueParser } from './Parser'; -import { CLValueUInt8 } from './Uint8'; +import { CLValueUInt8 } from './Numeric'; /** * Represents an optional value in the Casper type system. @@ -125,7 +125,7 @@ export class CLValueOption { clType: CLTypeOption ): IResultWithBytes { const { result: u8, bytes: u8Bytes } = CLValueUInt8.fromBytes(source); - const optionTag = u8.getValue(); + const optionTag = u8.toNumber(); if (optionTag === 0) { return { result: new CLValueOption(null, clType), bytes: u8Bytes }; diff --git a/src/types/clvalue/Parser.ts b/src/types/clvalue/Parser.ts index 98e877d82..80688dd4a 100644 --- a/src/types/clvalue/Parser.ts +++ b/src/types/clvalue/Parser.ts @@ -16,18 +16,20 @@ import { CLTypeTuple3, TypeID } from './cltype'; -import { CLValueUInt32 } from './Uint32'; +import { + CLValueUInt32, + CLValueUInt512, + CLValueUInt256, + CLValueUInt128, + CLValueUInt64, + CLValueUInt8, + CLValueInt32, + CLValueInt64 +} from './Numeric'; import { CLValueBool } from './Bool'; import { CLValueAny } from './Any'; import { CLValueUnit } from './Unit'; import { CLValueString } from './String'; -import { CLValueUInt512 } from './Uint512'; -import { CLValueUInt256 } from './Uint256'; -import { CLValueUInt128 } from './Uint128'; -import { CLValueUInt64 } from './Uint64'; -import { CLValueUInt8 } from './Uint8'; -import { CLValueInt32 } from './Int32'; -import { CLValueInt64 } from './Int64'; import { CLValueOption } from './Option'; import { CLValueList } from './List'; import { CLValueByteArray } from './ByteArray'; @@ -250,7 +252,7 @@ export class CLValueParser { bytes: Uint8Array ): IResultWithBytes { const u32 = CLValueUInt32.fromBytes(bytes); - const length = u32.result.getValue().toNumber(); + const length = u32.result.toNumber(); if (!length) { throw new Error(`Invalid length for bytes: ${length}`); diff --git a/src/types/clvalue/Result.ts b/src/types/clvalue/Result.ts index 7796e5426..66e01a42b 100644 --- a/src/types/clvalue/Result.ts +++ b/src/types/clvalue/Result.ts @@ -3,7 +3,7 @@ import { concat } from '@ethersproject/bytes'; import { CLType, CLTypeResult } from './cltype'; import { CLValue, IResultWithBytes } from './CLValue'; import { CLValueParser } from './Parser'; -import { CLValueUInt8 } from './Uint8'; +import { CLValueUInt8 } from './Numeric'; /** * Represents a Result type in the Casper type system. diff --git a/src/types/clvalue/String.ts b/src/types/clvalue/String.ts index e2f417bc0..4ea250d87 100644 --- a/src/types/clvalue/String.ts +++ b/src/types/clvalue/String.ts @@ -2,7 +2,7 @@ import { concat } from '@ethersproject/bytes'; import { CLTypeString } from './cltype'; import { CLValue, IResultWithBytes } from './CLValue'; -import { CLValueUInt32 } from './Uint32'; +import { CLValueUInt32 } from './Numeric'; import { fromBytesString } from '../ByteConverters'; /** @@ -78,7 +78,7 @@ export class CLValueString { */ public static fromBytes(source: Uint8Array): IResultWithBytes { const uint32Value = CLValueUInt32.fromBytes(source); - const size = uint32Value?.result?.getValue()?.toNumber(); + const size = uint32Value?.result?.toNumber(); const value = fromBytesString(uint32Value?.bytes?.subarray(0, size)); return { diff --git a/src/types/clvalue/Tuple3.ts b/src/types/clvalue/Tuple3.ts index 259d346ef..c9ba6db8c 100644 --- a/src/types/clvalue/Tuple3.ts +++ b/src/types/clvalue/Tuple3.ts @@ -1,13 +1,14 @@ -import { CLTypeTuple3, CLType } from './cltype'; +import { concat } from '@ethersproject/bytes'; + +import { CLTypeTuple3 } from './cltype'; import { CLValueParser } from './Parser'; import { CLValue, IResultWithBytes } from './CLValue'; -import { concat } from '@ethersproject/bytes'; /** * Represents a tuple containing three CLValues in the Casper type system. */ export class CLValueTuple3 { - public innerType: CLType; + public innerType: CLTypeTuple3; public inner1: CLValue; public inner2: CLValue; public inner3: CLValue; @@ -20,7 +21,7 @@ export class CLValueTuple3 { * @param inner3 - The third CLValue in the tuple. */ constructor( - innerType: CLType, + innerType: CLTypeTuple3, inner1: CLValue, inner2: CLValue, inner3: CLValue diff --git a/src/types/clvalue/Uint128.ts b/src/types/clvalue/Uint128.ts deleted file mode 100644 index a05f801b4..000000000 --- a/src/types/clvalue/Uint128.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { BigNumber } from '@ethersproject/bignumber'; - -import { CLTypeUInt128 } from './cltype'; -import { fromBytesUInt128 } from './UintBig'; -import { CLValue, IResultWithBytes } from './CLValue'; -import { toBytesU128 } from '../ByteConverters'; - -/** - * Represents a 128-bit unsigned integer value in the Casper type system. - */ -export class CLValueUInt128 { - private val: BigNumber; - - /** - * 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); - } - - /** - * Converts the UInt128 value to its byte representation. - * @returns A Uint8Array representing the bytes of the UInt128 value. - */ - public bytes(): Uint8Array { - return toBytesU128(this.val); - } - - /** - * Provides a string representation of the UInt128 value. - * @returns The string representation of the value. - */ - public toString(): string { - return this.val.toString(); - } - - /** - * Retrieves the BigNumber value of the UInt128. - * @returns The BigNumber representation of the value. - */ - public getValue(): BigNumber { - return this.val; - } - - /** - * Converts the instance to a JSON-compatible string. - * - * @returns {string} The string representation of the instance. - */ - public toJSON(): string { - return this.toString(); - } - - /** - * 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 containing CLTypeUInt128 and a CLValueUInt128. - */ - public static newCLUInt128(val: BigNumber | string): CLValue { - const res = new CLValue(CLTypeUInt128); - res.ui128 = new CLValueUInt128(val); - return res; - } - - /** - * 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 An object containing the new CLValueUInt128 instance and any remaining bytes. - */ - public static fromBytes( - source: Uint8Array - ): IResultWithBytes { - return fromBytesUInt128(source); - } -} diff --git a/src/types/clvalue/Uint256.ts b/src/types/clvalue/Uint256.ts deleted file mode 100644 index 430a4c810..000000000 --- a/src/types/clvalue/Uint256.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { BigNumber } from '@ethersproject/bignumber'; - -import { fromBytesUInt256 } from './UintBig'; -import { CLValue, IResultWithBytes } from './CLValue'; -import { CLTypeUInt256 } from './cltype'; -import { toBytesU256 } from '../ByteConverters'; - -/** - * Represents a 256-bit unsigned integer value in the Casper type system. - */ -export class CLValueUInt256 { - private val: BigNumber; - - /** - * 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); - } - - /** - * Converts the UInt256 value to its byte representation. - * @returns A Uint8Array representing the bytes of the UInt256 value. - */ - public bytes(): Uint8Array { - return toBytesU256(this.val); - } - - /** - * Provides a string representation of the UInt256 value. - * @returns The string representation of the value. - */ - public toString(): string { - return this.val.toString(); - } - - /** - * Retrieves the BigNumber value of the UInt256. - * @returns The BigNumber representation of the value. - */ - public getValue(): BigNumber { - return this.val; - } - - /** - * 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 containing CLTypeUInt256 and a CLValueUInt256. - */ - public static newCLUInt256(val: BigNumber | string): CLValue { - const res = new CLValue(CLTypeUInt256); - res.ui256 = new CLValueUInt256(val); - return res; - } - - /** - * Converts the instance to a JSON-compatible string. - * - * @returns {string} The string representation of the instance. - */ - public toJSON(): string { - return this.toString(); - } - - /** - * 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 An object containing the new CLValueUInt256 instance and any remaining bytes. - */ - public static fromBytes( - source: Uint8Array - ): IResultWithBytes { - return fromBytesUInt256(source); - } -} diff --git a/src/types/clvalue/Uint32.ts b/src/types/clvalue/Uint32.ts deleted file mode 100644 index 2c6b4834a..000000000 --- a/src/types/clvalue/Uint32.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { BigNumber } from '@ethersproject/bignumber'; - -import { CLTypeUInt32, Int32ByteSize } from './cltype'; -import { CLValue, IResultWithBytes } from './CLValue'; -import { toBytesU32 } from '../ByteConverters'; - -/** - * Represents a 32-bit unsigned integer value in the Casper type system. - */ -export class CLValueUInt32 { - private value: BigNumber; - - /** - * Initializes a new instance of the CLValueUInt32 class. - * @param value - The value to initialize the CLValueUInt32 with. - */ - constructor(value: BigNumber) { - this.value = value; - } - - /** - * 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); - } - - /** - * Provides a string representation of the UInt32 value. - * @returns The string representation of the value. - */ - public toString(): string { - return this.value.toString(); - } - - /** - * Converts the instance to a JSON-compatible string. - * - * @returns {string} The string representation of the instance. - */ - public toJSON(): string { - return this.toString(); - } - - /** - * Retrieves the numeric value of the UInt32. - * @returns The BigNumber representation of the value. - */ - public getValue(): BigNumber { - return this.value; - } - - /** - * Creates a new CLValue instance with a UInt32 value. - * @param val - The value to initialize the UInt32 with. - * @returns A new CLValue instance containing CLTypeUInt32 and a CLValueUInt32. - */ - public static newCLUInt32(val: BigNumber): CLValue { - const res = new CLValue(CLTypeUInt32); - res.ui32 = new CLValueUInt32(val); - return res; - } - - /** - * 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 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) { - throw new Error('Buffer size is too small for UInt32'); - } - const u32Bytes = Uint8Array.from(source.subarray(0, 4)); - const u32 = BigNumber.from(u32Bytes.slice().reverse()); - - return { result: new CLValueUInt32(u32), bytes: source.subarray(4) }; - } - - /** - * 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 { - return new CLValueUInt32(val).bytes(); - } -} diff --git a/src/types/clvalue/Uint512.ts b/src/types/clvalue/Uint512.ts deleted file mode 100644 index 9b9da6572..000000000 --- a/src/types/clvalue/Uint512.ts +++ /dev/null @@ -1,132 +0,0 @@ -import { BigNumber } from '@ethersproject/bignumber'; - -import { fromBytesUInt512 } from './UintBig'; -import { CLValue, IResultWithBytes } from './CLValue'; -import { CLTypeUInt512 } from './cltype'; -import { toBytesU512 } from '../ByteConverters'; - -/** - * Represents a 512-bit unsigned integer value in the Casper type system. - */ -export class CLValueUInt512 { - public val: BigNumber; - public isStringFmt: boolean; - - /** - * 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); - this.isStringFmt = typeof val === 'string'; - } - - /** - * Converts the UInt512 value to its byte representation. - * @returns A Uint8Array representing the bytes of the UInt512 value. - */ - public bytes(): Uint8Array { - return toBytesU512(this.val); - } - - /** - * Provides a string representation of the UInt512 value. - * @returns The string representation of the value. - */ - public toString(): string { - return this.val.toString(); - } - - /** - * Retrieves the BigNumber value of the UInt512. - * @returns The BigNumber representation of the value. - */ - public value(): BigNumber { - return this.val; - } - - /** - * Returns a JSON representation of the UInt512 value. - * @returns A string if the value was originally provided as a string, otherwise a number. - */ - public toJSON(): string | number { - return this.isStringFmt ? this.toString() : this.val.toNumber(); - } - - /** - * Creates a CLValueUInt512 instance from a JSON representation. - * @param json - The JSON representation of the UInt512 value. Can be a string or a number. - * @returns A new CLValueUInt512 instance. - * @throws Will throw an error if the input is not a valid integer or is negative. - */ - public static fromJSON(json: string | number): CLValueUInt512 { - const num = BigNumber.from(json); - - if (!num.mod(1).isZero() || num.isNegative()) { - throw new Error(`Invalid integer string: ${json}`); - } - - const isStringFmt = typeof json === 'string'; - const result = new CLValueUInt512(num); - result.isStringFmt = isStringFmt; - return result; - } - - /** - * 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 An object containing the new CLValueUInt512 instance and any remaining bytes. - */ - public static fromBytes( - source: Uint8Array - ): IResultWithBytes { - return fromBytesUInt512(source); - } - - /** - * 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 containing CLTypeUInt512 and a CLValueUInt512. - */ - public static newCLUInt512(val: BigNumber | string): CLValue { - const res = new CLValue(CLTypeUInt512); - res.ui512 = new CLValueUInt512(val); - return res; - } -} - -/** - * 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]) => { - const valuesArray = value.map((item: any) => - CLValueUInt512.fromJSON(item) - ); - return [key, valuesArray]; - }) - ); - - if (parsed.size !== Array.from(arr).length) { - throw Error(`Duplicate key exists.`); - } - - 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()); - return [key, serializedValue]; - }); -}; diff --git a/src/types/clvalue/Uint8.ts b/src/types/clvalue/Uint8.ts deleted file mode 100644 index 633f8c2b3..000000000 --- a/src/types/clvalue/Uint8.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { CLValue, IResultWithBytes } from './CLValue'; -import { CLTypeUInt8 } from './cltype'; -import { toBytesU8 } from '../ByteConverters'; - -/** - * Represents an 8-bit unsigned integer value in the Casper type system. - */ -export class CLValueUInt8 { - private value: number; - - /** - * 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; - } - - /** - * Converts the UInt8 value to its byte representation. - * @returns A Uint8Array containing a single byte representing the UInt8 value. - */ - public bytes(): Uint8Array { - return toBytesU8(this.value); - } - - /** - * Provides a string representation of the UInt8 value. - * @returns The string representation of the value. - */ - public toString(): string { - return this.value.toString(); - } - - /** - * Converts the instance to a JSON-compatible string. - * - * @returns {string} The string representation of the instance. - */ - public toJSON(): string { - return this.toString(); - } - - /** - * Retrieves the number value of the UInt8. - * @returns The number representation of the value. - */ - public getValue(): number { - return this.value; - } - - /** - * Creates a new CLValue instance with a UInt8 value. - * @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); - res.ui8 = new CLValueUInt8(val); - return res; - } - - /** - * 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 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) { - throw new Error('Insufficient buffer length for UInt8'); - } - - return { result: new CLValueUInt8(source[0]), bytes: source.subarray(1) }; - } -} diff --git a/src/types/clvalue/UintBig.ts b/src/types/clvalue/UintBig.ts index cd26593ce..76bbd088e 100644 --- a/src/types/clvalue/UintBig.ts +++ b/src/types/clvalue/UintBig.ts @@ -1,8 +1,6 @@ import { BigNumber } from '@ethersproject/bignumber'; -import { CLValueUInt128 } from './Uint128'; -import { CLValueUInt256 } from './Uint256'; -import { CLValueUInt512 } from './Uint512'; +import { CLValueUInt128, CLValueUInt256, CLValueUInt512 } from './Numeric'; import { IResultWithBytes } from './CLValue'; /** diff --git a/src/types/clvalue/index.ts b/src/types/clvalue/index.ts index 8916219c6..df89d58e5 100644 --- a/src/types/clvalue/index.ts +++ b/src/types/clvalue/index.ts @@ -2,8 +2,7 @@ export * from './Any'; export * from './Bool'; export * from './ByteArray'; export * from './CLValue'; -export * from './Int32'; -export * from './Int64'; +export * from './Numeric'; export * from './List'; export * from './Map'; export * from './Option'; @@ -15,10 +14,4 @@ export * from './Tuple2'; export * from './Tuple3'; export * from './UintBig'; export * from './Unit'; -export * from './Uint256'; -export * from './Uint128'; -export * from './Uint512'; -export * from './Uint64'; -export * from './Uint8'; -export * from './Uint32'; export * from './cltype'; diff --git a/src/utils/cep-nft-transfer.ts b/src/utils/cep-nft-transfer.ts index 2dc69eb58..e7af0b177 100644 --- a/src/utils/cep-nft-transfer.ts +++ b/src/utils/cep-nft-transfer.ts @@ -11,7 +11,9 @@ import { Deploy, DeployHeader, Duration, - ExecutableDeployItem, Key, KeyTypeID, + ExecutableDeployItem, + Key, + KeyTypeID, PublicKey, StoredVersionedContractByHash } from '../types'; @@ -76,17 +78,17 @@ export const makeNftTransferDeploy = ({ const senderPublicKey = PublicKey.newPublicKey(senderPublicKeyHex); if (!(tokenId || tokenHash)) { - throw new Error('Specify either tokenId or tokenHash to make a transfer') + throw new Error('Specify either tokenId or tokenHash to make a transfer'); } let args: Args | null = null; if (nftStandard === NFTTokenStandard.CEP47) { if (!tokenId) { - throw new Error('TokenId is required for CEP-47 transfer') + throw new Error('TokenId is required for CEP-47 transfer'); } - args = getRuntimeArgsForCep47Transfer({ tokenId, recipientPublicKeyHex }) + args = getRuntimeArgsForCep47Transfer({ tokenId, recipientPublicKeyHex }); } if (nftStandard === NFTTokenStandard.CEP78) { @@ -99,7 +101,7 @@ export const makeNftTransferDeploy = ({ } if (!args) { - throw new Error('Deploy arguments error. Check provided token data') + throw new Error('Deploy arguments error. Check provided token data'); } const session = new ExecutableDeployItem(); @@ -130,14 +132,28 @@ export const getRuntimeArgsForCep78Transfer = ({ 'tokenId' | 'recipientPublicKeyHex' | 'tokenHash' | 'senderPublicKeyHex' >) => { const runtimeArgs = Args.fromMap({ - target_key: CLValue.newCLKey(Key.createByType(PublicKey.fromHex(recipientPublicKeyHex).accountHash().toPrefixedString(), KeyTypeID.Account)), - source_key: CLValue.newCLKey(Key.createByType(PublicKey.fromHex(senderPublicKeyHex).accountHash().toPrefixedString(), KeyTypeID.Account)) + target_key: CLValue.newCLKey( + Key.createByType( + PublicKey.fromHex(recipientPublicKeyHex) + .accountHash() + .toPrefixedString(), + KeyTypeID.Account + ) + ), + source_key: CLValue.newCLKey( + Key.createByType( + PublicKey.fromHex(senderPublicKeyHex) + .accountHash() + .toPrefixedString(), + KeyTypeID.Account + ) + ) }); if (tokenId) { runtimeArgs.insert( 'is_hash_identifier_mode', - CLValueBool.fromBoolean(false) + CLValueBool.newCLValueBool(false) ); runtimeArgs.insert('token_id', CLValueUInt64.newCLUint64(tokenId)); } @@ -145,7 +161,7 @@ export const getRuntimeArgsForCep78Transfer = ({ if (tokenHash) { runtimeArgs.insert( 'is_hash_identifier_mode', - CLValueBool.fromBoolean(true) + CLValueBool.newCLValueBool(true) ); runtimeArgs.insert('token_id', CLValueUInt64.newCLUint64(tokenHash)); } @@ -160,7 +176,14 @@ export function getRuntimeArgsForCep47Transfer({ Pick >) { return Args.fromMap({ - recipient: CLValue.newCLKey(Key.createByType(PublicKey.fromHex(recipientPublicKeyHex).accountHash().toPrefixedString(), KeyTypeID.Account)), + recipient: CLValue.newCLKey( + Key.createByType( + PublicKey.fromHex(recipientPublicKeyHex) + .accountHash() + .toPrefixedString(), + KeyTypeID.Account + ) + ), token_ids: CLValueList.newCLList(CLTypeUInt256, [ CLValueUInt256.newCLUInt256(tokenId) ]) From ef81a1eeff327d1141b9126b3452ec78e23ab772 Mon Sep 17 00:00:00 2001 From: Oleksandr Myshchyshyn Date: Mon, 23 Dec 2024 14:01:51 +0200 Subject: [PATCH 2/2] Aligned casing for fromJSON and toJSON, updated type for chain name for utils --- src/sse/event.ts | 8 ++++---- src/types/Deploy.test.ts | 2 +- src/types/Deploy.ts | 2 +- src/types/Transaction.ts | 4 ++-- src/utils/cep-18-transfer.ts | 23 +++++++++++++++-------- src/utils/cep-nft-transfer.ts | 2 +- src/utils/cspr-transfer.ts | 5 ++--- 7 files changed, 26 insertions(+), 20 deletions(-) diff --git a/src/sse/event.ts b/src/sse/event.ts index 84dbde961..718da3fba 100644 --- a/src/sse/event.ts +++ b/src/sse/event.ts @@ -114,14 +114,14 @@ export class RawEvent { parseAsTransactionProcessedEvent(): TransactionProcessedEvent { return this.parseEvent( TransactionProcessedEvent, - TransactionProcessedEvent.fromJson + TransactionProcessedEvent.fromJSON ); } parseAsTransactionAcceptedEvent(): TransactionAcceptedEvent { return this.parseEvent( TransactionAcceptedEvent, - TransactionAcceptedEvent.fromJson + TransactionAcceptedEvent.fromJSON ); } @@ -340,7 +340,7 @@ export class TransactionAcceptedEvent { }) transactionAcceptedPayload: TransactionAcceptedPayload; - public static fromJson(data: unknown): TransactionAcceptedEvent | Error { + public static fromJSON(data: unknown): TransactionAcceptedEvent | Error { try { const transactionEvent = TypedJSON.parse(data, TransactionAcceptedEvent); if (!transactionEvent) throw new Error('TransactionAcceptedEvent is nil'); @@ -475,7 +475,7 @@ export class TransactionProcessedEvent { }) transactionProcessedPayload: TransactionProcessedPayload; - public static fromJson(data: any): TransactionProcessedEvent | Error { + public static fromJSON(data: any): TransactionProcessedEvent | Error { try { const transactionEvent = TypedJSON.parse(data, TransactionProcessedEvent); if (!transactionEvent) diff --git a/src/types/Deploy.test.ts b/src/types/Deploy.test.ts index f4b4424ab..bf9502acd 100644 --- a/src/types/Deploy.test.ts +++ b/src/types/Deploy.test.ts @@ -62,7 +62,7 @@ describe('Deploy', () => { await deploy.sign(senderKey); await deploy.sign(recipientKey); - const json = Deploy.toJson(deploy); + const json = Deploy.toJSON(deploy); deploy = Deploy.fromJSON(json); diff --git a/src/types/Deploy.ts b/src/types/Deploy.ts index 50bb6b47c..ddcfefc8f 100644 --- a/src/types/Deploy.ts +++ b/src/types/Deploy.ts @@ -464,7 +464,7 @@ export class Deploy { * @param deploy The deploy object to convert to JSON. * @returns A JSON representation of the deploy. */ - public static toJson = (deploy: Deploy) => { + public static toJSON = (deploy: Deploy) => { const serializer = new TypedJSON(Deploy); return serializer.toPlainJson(deploy); }; diff --git a/src/types/Transaction.ts b/src/types/Transaction.ts index 0e4435d66..ab3b6cbbd 100644 --- a/src/types/Transaction.ts +++ b/src/types/Transaction.ts @@ -265,7 +265,7 @@ export class TransactionV1 { * @param transaction The `TransactionV1` object. * @returns A JSON version of the `TransactionV1`. */ - public static toJson = (transaction: TransactionV1) => { + public static toJSON = (transaction: TransactionV1) => { const serializer = new TypedJSON(TransactionV1); return serializer.toPlainJson(transaction); @@ -550,7 +550,7 @@ export class Transaction { return Deploy.newTransactionFromDeploy(deploy); } - static fromJson(json: any): Transaction { + static fromJSON(json: any): Transaction { try { const txV1 = TransactionV1.fromJSON(json); diff --git a/src/utils/cep-18-transfer.ts b/src/utils/cep-18-transfer.ts index 2a8daa2c6..caa3d7489 100644 --- a/src/utils/cep-18-transfer.ts +++ b/src/utils/cep-18-transfer.ts @@ -7,19 +7,21 @@ import { Deploy, DeployHeader, Duration, - ExecutableDeployItem, Key, KeyTypeID, + ExecutableDeployItem, + Key, + KeyTypeID, PublicKey, StoredContractByHash } from '../types'; import { CasperNetworkName } from '../@types'; export interface IMakeCep18TransferDeployParams { - contractHash: string, + contractHash: string; senderPublicKeyHex: string; recipientPublicKeyHex: string; transferAmount: string; - paymentAmount: string, - chainName?: CasperNetworkName; + paymentAmount: string; + chainName?: string; ttl?: number; } @@ -36,8 +38,7 @@ export interface IMakeCep18TransferDeployParams { * For example, to transfer 2.5 CSPR, provide the value `2500000000` (2.5 * 10^9 motes). * @param params.paymentAmount - The amount of CSPR to pay a network fee. * This value must be represented in its smallest unit (motes). - * @param params.chainName - (Optional) The name of the Casper network chain - {CasperNetworkName}. - * Must be either `'casper'` (mainnet) or `'casper-test'` (testnet). + * @param params.chainName - (Optional) The name of the Casper network chain. * Defaults to `'CasperNetworkName.Mainnet'` if not specified. * @param params.ttl - (Optional) The time-to-live (TTL) for the `Deploy` in milliseconds. * Specifies how long the `Deploy` is valid before it expires. @@ -59,6 +60,7 @@ export interface IMakeCep18TransferDeployParams { * console.log('Created Deploy:', deploy); * ``` */ + export const makeCep18TransferDeploy = ({ contractHash, senderPublicKeyHex, @@ -66,7 +68,7 @@ export const makeCep18TransferDeploy = ({ transferAmount, paymentAmount, chainName = CasperNetworkName.Mainnet, - ttl = DEFAULT_DEPLOY_TTL, + ttl = DEFAULT_DEPLOY_TTL }: IMakeCep18TransferDeployParams): Deploy => { const senderPublicKey = PublicKey.newPublicKey(senderPublicKeyHex); const recipientPublicKey = PublicKey.newPublicKey(recipientPublicKeyHex); @@ -77,7 +79,12 @@ export const makeCep18TransferDeploy = ({ ContractHash.newContract(contractHash), 'transfer', Args.fromMap({ - recipient: CLValue.newCLKey(Key.createByType(recipientPublicKey.accountHash().toPrefixedString(), KeyTypeID.Account)), + recipient: CLValue.newCLKey( + Key.createByType( + recipientPublicKey.accountHash().toPrefixedString(), + KeyTypeID.Account + ) + ), amount: CLValueUInt256.newCLUInt256(transferAmount) }) ); diff --git a/src/utils/cep-nft-transfer.ts b/src/utils/cep-nft-transfer.ts index e7af0b177..325729b0d 100644 --- a/src/utils/cep-nft-transfer.ts +++ b/src/utils/cep-nft-transfer.ts @@ -25,7 +25,7 @@ export interface IMakeNftTransferDeployParams { senderPublicKeyHex: string; recipientPublicKeyHex: string; paymentAmount: string; - chainName?: CasperNetworkName; + chainName?: string; ttl?: number; tokenId?: string; tokenHash?: string; diff --git a/src/utils/cspr-transfer.ts b/src/utils/cspr-transfer.ts index d49facb3c..89cd41775 100644 --- a/src/utils/cspr-transfer.ts +++ b/src/utils/cspr-transfer.ts @@ -13,7 +13,7 @@ export interface IMakeCsprTransferDeployParams { senderPublicKeyHex: string; recipientPublicKeyHex: string; transferAmount: string; - chainName?: CasperNetworkName; + chainName?: string; memo?: string; ttl?: number; } @@ -29,8 +29,7 @@ export interface IMakeCsprTransferDeployParams { * @param params.transferAmount - The amount of CSPR to transfer. * This value must be represented in its smallest unit (motes). * For example, to transfer 2.5 CSPR, provide the value `2500000000` (2.5 * 10^9 motes). - * @param params.chainName - (Optional) The name of the Casper network chain - {CasperNetworkName}. - * Must be either `'casper'` (mainnet) or `'casper-test'` (testnet). + * @param params.chainName - (Optional) The name of the Casper network chain. * Defaults to `'CasperNetworkName.Mainnet'` if not specified. * @param params.memo - (Optional) Tag/Memo (Comment/Note/Remark) * Most exchanges require a Tag/Memo for CSPR deposits to be credited correctly.