Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@vechain/sdk-core

Package Overview
Dependencies
Maintainers
8
Versions
34
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@vechain/sdk-core - npm Package Compare versions

Comparing version 1.0.0-beta.32 to 1.0.0-rc.1

18

package.json
{
"name": "@vechain/sdk-core",
"version": "1.0.0-beta.32",
"version": "1.0.0-rc.1",
"description": "This module is crafted for dApp development and various blockchain operations that seamlessly unfold offline",

@@ -31,3 +31,3 @@ "author": "VeChain Foundation",

"build": "rm -rf ./dist && tsup-node src/index.ts --format cjs,esm --dts",
"check:circular-dependencies": "npx madge --exclude 'transaction/Clause.ts' --circular --extensions ts src",
"check:circular-dependencies": "npx madge --circular --extensions ts src",
"lint": "eslint --ext .ts src --ext .ts tests",

@@ -45,15 +45,13 @@ "format": "prettier --write src/**/*.ts tests/**/*.ts",

"@scure/bip39": "^1.4.0",
"@types/elliptic": "^6.4.18",
"@vechain/sdk-errors": "1.0.0-beta.32",
"@vechain/sdk-logging": "1.0.0-beta.32",
"bignumber.js": "^9.1.2",
"blakejs": "^1.2.1",
"ethers": "6.13.2",
"@vechain/sdk-errors": "1.0.0-rc.1",
"@vechain/sdk-logging": "1.0.0-rc.1",
"ethers": "6.13.4",
"fast-json-stable-stringify": "^2.1.0",
"viem": "^2.21.14"
"viem": "^2.21.19"
},
"devDependencies": {
"bignumber.js": "^9.1.2",
"thor-devkit": "^2.0.9"
"thor-devkit": "^2.0.9",
"tsd": "^0.31.2"
}
}

@@ -87,3 +87,3 @@ import fastJsonStableStringify from 'fast-json-stable-stringify';

*/
signature?: string | undefined;
signature?: string;

@@ -90,0 +90,0 @@ /**

@@ -0,4 +1,5 @@

import { InvalidDataType } from '@vechain/sdk-errors';
import { ERC721_ABI, VIP180_ABI } from '../utils';
import {
abi,
ABI,
ABIContract,

@@ -14,6 +15,5 @@ FixedPointNumber,

import { HexInt } from '../vcdm/HexInt';
import { InvalidDataType } from '@vechain/sdk-errors';
import type { ClauseOptions } from './ClauseOptions';
import type { DeployParams } from './DeployParams';
import type { TransactionClause } from './TransactionClause';
import type { ClauseOptions } from './ClauseOptions';

@@ -173,4 +173,5 @@ /**

? contractBytecode.digits +
abi
.encodeParams(deployParams.types, deployParams.values)
ABI.of(deployParams.types, deployParams.values)
.toHex()
.toString()
.replace(Hex.PREFIX, '')

@@ -177,0 +178,0 @@ : contractBytecode.digits;

@@ -1,2 +0,2 @@

import { type ParamType } from 'ethers';
import { type AbiParameter } from 'viem';

@@ -10,5 +10,5 @@ /**

* An array of types associated with the deployment parameters.
* @type {string[] | ParamType[]}
* @type {string | AbiParameter[]}
*/
types: string[] | ParamType[];
types: string | AbiParameter[];

@@ -15,0 +15,0 @@ /**

@@ -186,3 +186,3 @@ import * as nc_utils from '@noble/curves/abstract/utils';

* - {@link Secp256k1.recover};
* - {@link Transaction.getSignatureHash}.
* - {@link Transaction.getTransactionHash}.
*/

@@ -199,3 +199,3 @@ public get delegator(): Address {

const delegatorPublicKey = Secp256k1.recover(
this.getSignatureHash(this.origin).bytes,
this.getTransactionHash(this.origin).bytes,
delegator

@@ -249,3 +249,3 @@ );

nc_utils.concatBytes(
this.getSignatureHash().bytes,
this.getTransactionHash().bytes,
this.origin.bytes

@@ -307,3 +307,3 @@ )

Secp256k1.recover(
this.getSignatureHash().bytes,
this.getTransactionHash().bytes,
// Get the (r, s) of ECDSA digital signature without delegator params.

@@ -377,6 +377,6 @@ this.signature.slice(0, Secp256k1.SIGNATURE_LENGTH)

/**
* Computes the signature hash, optionally incorporating a delegator's address.
* Computes the transaction hash, optionally incorporating a delegator's address.
*
* @param {Address} [delegator] - Optional delegator's address to include in the hash computation.
* @return {Blake2b256} - The computed signature hash.
* @return {Blake2b256} - The computed transaction hash.
*

@@ -389,3 +389,3 @@ * @remarks

*/
public getSignatureHash(delegator?: Address): Blake2b256 {
public getTransactionHash(delegator?: Address): Blake2b256 {
const txHash = Blake2b256.of(this.encode(false));

@@ -527,3 +527,3 @@ if (delegator !== undefined) {

const signature = Secp256k1.sign(
this.getSignatureHash().bytes,
this.getTransactionHash().bytes,
signerPrivateKey

@@ -571,4 +571,4 @@ );

if (this.isDelegated) {
const transactionHash = this.getSignatureHash().bytes;
const delegatedHash = this.getSignatureHash(
const transactionHash = this.getTransactionHash().bytes;
const delegatedHash = this.getTransactionHash(
Address.ofPublicKey(

@@ -575,0 +575,0 @@ Secp256k1.derivePublicKey(signerPrivateKey)

@@ -5,3 +5,2 @@ import {

} from '@vechain/sdk-errors';
import { ParamType, type BytesLike } from 'ethers';
import {

@@ -235,39 +234,2 @@ decodeAbiParameters,

// Backwards compatibility, ethersAbi should be removed as part of #1184
const ethersAbi = {
encode: <ValueType>(type: string | ParamType, value: ValueType): string =>
ABI.of(
type instanceof ParamType
? // This condition is here to enable compatibility with ethers regarding tuple[] types.
type.format('full').replace(' list', '')
: type,
[value]
)
.toHex()
.toString(),
encodeParams: (types: string[] | ParamType[], values: string[]): string => {
const stringTypes =
types instanceof ParamType
? types.map((type) =>
(type as ParamType).format('full').replace(' list', '')
)
: types;
const typesParam = parseAbiParameters(stringTypes.join(', '));
return ABI.of([...typesParam], values)
.toHex()
.toString();
},
decode: <ReturnType>(
types: string | ParamType,
data: BytesLike
): ReturnType =>
ABI.ofEncoded(
types instanceof ParamType
? // This condition is here to enable compatibility with ethers regarding tuple[] types.
types.format('full').replace(' list', '')
: types,
data
).getFirstDecodedValue()
};
export { ABI, ethersAbi };
export { ABI };

@@ -7,5 +7,6 @@ import {

getAbiItem,
parseAbi,
type AbiEvent,
type AbiFunction,
type ContractEventName,
type ContractFunctionName,
type DecodeEventLogReturnType,

@@ -21,8 +22,8 @@ type DecodeFunctionDataReturnType,

class ABIContract extends ABI {
private readonly abi: ViemABI;
class ABIContract<TAbi extends ViemABI> extends ABI {
private readonly viemABI: ViemABI;
constructor(abi: ViemABI) {
constructor(readonly abi: TAbi) {
super();
this.abi = abi;
this.viemABI = abi as ViemABI;
}

@@ -35,3 +36,3 @@

*/
public static ofAbi(abi: ViemABI): ABIContract {
public static ofAbi<TAbi extends ViemABI>(abi: TAbi): ABIContract<TAbi> {
return new ABIContract(abi);

@@ -41,11 +42,2 @@ }

/**
* Creates an ABIContract instance from an ABI string.
* @param {string} abi representation of the contract.
* @returns New instance of ABIContract.
*/
public static ofStringAbi(abi: string): ABIContract {
return new ABIContract(parseAbi([abi]));
}
/**
* Returns the function with the given name.

@@ -56,6 +48,8 @@ * @param {string} name The function's name.

*/
public getFunction(name: string): ABIFunction {
public getFunction<TFunctionName extends ContractFunctionName<TAbi>>(
name: TFunctionName | string
): ABIFunction<TAbi, TFunctionName> {
const functionAbiItem = getAbiItem({
abi: this.abi,
name
abi: this.viemABI,
name: name as string
});

@@ -72,3 +66,5 @@ if (functionAbiItem === null || functionAbiItem === undefined) {

}
return new ABIFunction(functionAbiItem as AbiFunction);
return new ABIFunction<TAbi, TFunctionName>(
functionAbiItem as AbiFunction
);
}

@@ -82,6 +78,8 @@

*/
public getEvent(name: string): ABIEvent {
public getEvent<TEventName extends ContractEventName<TAbi>>(
name: TEventName | string
): ABIEvent<TAbi, TEventName> {
const eventAbiItem = getAbiItem({
abi: this.abi,
name
abi: this.viemABI,
name: name as string
});

@@ -98,3 +96,3 @@ if (eventAbiItem === null || eventAbiItem === undefined) {

}
return new ABIEvent(eventAbiItem as AbiEvent);
return new ABIEvent<TAbi, TEventName>(eventAbiItem as AbiEvent);
}

@@ -109,12 +107,13 @@

*/
public encodeFunctionInput(
functionName: string,
functionData?: unknown[]
): Hex {
public encodeFunctionInput<
TFunctionName extends ContractFunctionName<TAbi>
>(functionName: TFunctionName | string, functionData?: unknown[]): Hex {
try {
const functionAbiItem = getAbiItem({
abi: this.abi,
name: functionName
abi: this.viemABI,
name: functionName as string
});
const functionAbi = new ABIFunction(functionAbiItem as AbiFunction);
const functionAbi = new ABIFunction<TAbi, TFunctionName>(
functionAbiItem as AbiFunction
);

@@ -139,12 +138,16 @@ return functionAbi.encodeData(functionData);

*/
public decodeFunctionInput(
functionName: string,
public decodeFunctionInput<
TFunctionName extends ContractFunctionName<TAbi>
>(
functionName: TFunctionName | string,
encodedFunctionInput: Hex
): DecodeFunctionDataReturnType {
): DecodeFunctionDataReturnType<TAbi, TFunctionName> {
try {
const functionAbiItem = getAbiItem({
abi: this.abi,
name: functionName
abi: this.viemABI,
name: functionName as string
});
const functionAbi = new ABIFunction(functionAbiItem as AbiFunction);
const functionAbi = new ABIFunction<TAbi, TFunctionName>(
functionAbiItem as AbiFunction
);

@@ -177,12 +180,16 @@ return functionAbi.decodeData(encodedFunctionInput);

*/
public decodeFunctionOutput(
functionName: string,
public decodeFunctionOutput<
TFunctionName extends ContractFunctionName<TAbi>
>(
functionName: TFunctionName | string,
encodedFunctionOutput: Hex
): DecodeFunctionResultReturnType {
): DecodeFunctionResultReturnType<TAbi, TFunctionName> {
try {
const functionAbiItem = getAbiItem({
abi: this.abi,
name: functionName
abi: this.viemABI,
name: functionName as string
});
const functionAbi = new ABIFunction(functionAbiItem as AbiFunction);
const functionAbi = new ABIFunction<TAbi, TFunctionName>(
functionAbiItem as AbiFunction
);

@@ -207,4 +214,4 @@ return functionAbi.decodeResult(encodedFunctionOutput);

*/
public encodeEventLog(
eventName: string,
public encodeEventLog<TEventName extends ContractEventName<TAbi>>(
eventName: TEventName | string,
eventArgs: unknown[]

@@ -214,6 +221,8 @@ ): ABIEventData {

const eventAbiItem = getAbiItem({
abi: this.abi,
name: eventName
abi: this.viemABI,
name: eventName as string
});
const eventAbi = new ABIEvent(eventAbiItem as AbiEvent);
const eventAbi = new ABIEvent<TAbi, TEventName>(
eventAbiItem as AbiEvent
);
return eventAbi.encodeEventLog(eventArgs);

@@ -237,12 +246,14 @@ } catch (error) {

*/
public decodeEventLog(
eventName: string,
public decodeEventLog<TEventName extends ContractEventName<TAbi>>(
eventName: TEventName | string,
eventToDecode: ABIEventData
): DecodeEventLogReturnType {
): DecodeEventLogReturnType<TAbi, TEventName> {
try {
const eventAbiItem = getAbiItem({
abi: this.abi,
name: eventName
abi: this.viemABI,
name: eventName as string
});
const eventAbi = new ABIEvent(eventAbiItem as AbiEvent);
const eventAbi = new ABIEvent<TAbi, TEventName>(
eventAbiItem as AbiEvent
);
return eventAbi.decodeEventLog(eventToDecode);

@@ -272,5 +283,11 @@ } catch (error) {

*/
public parseLog(data: Hex, topics: Hex[]): DecodeEventLogReturnType {
public parseLog<TEventName extends ContractEventName<TAbi>>(
data: Hex,
topics: Hex[]
): DecodeEventLogReturnType<TAbi, TEventName> {
try {
return ABIEvent.parseLog(this.abi, { data, topics });
return ABIEvent.parseLog(this.abi, {
data,
topics
});
} catch (e) {

@@ -298,7 +315,7 @@ throw new InvalidAbiDataToEncodeOrDecode(

return [];
} else if (eventLogDecoded.args instanceof Object) {
return Object.values(eventLogDecoded.args);
}
return eventLogDecoded.args;
return this.parseObjectValues(
eventLogDecoded.args as unknown as object
);
}

@@ -305,0 +322,0 @@ }

@@ -8,2 +8,3 @@ import {

type AbiEvent,
type ContractEventName,
type DecodeEventLogReturnType,

@@ -31,3 +32,6 @@ encodeEventTopics,

*/
class ABIEvent extends ABIItem {
class ABIEvent<
TAbi extends ViemABI = ViemABI,
TEventName extends ContractEventName<TAbi> = ContractEventName<TAbi>
> extends ABIItem {
private readonly abiEvent: AbiEvent;

@@ -60,6 +64,9 @@ public constructor(signature: string);

*/
public static parseLog(
abi: ViemABI,
public static parseLog<
TAbi extends ViemABI,
TEventName extends ContractEventName<TAbi>
>(
abi: TAbi,
eventData: ABIEventData
): DecodeEventLogReturnType {
): DecodeEventLogReturnType<TAbi, TEventName> {
try {

@@ -101,5 +108,7 @@ return viemDecodeEventLog({

*/
public decodeEventLog(event: ABIEventData): DecodeEventLogReturnType {
public decodeEventLog(
event: ABIEventData
): DecodeEventLogReturnType<TAbi, TEventName> {
try {
return ABIEvent.parseLog([this.abiEvent], event);
return ABIEvent.parseLog([this.abiEvent] as ViemABI, event);
} catch (error) {

@@ -121,19 +130,9 @@ throw new InvalidAbiDataToEncodeOrDecode(

public decodeEventLogAsArray(event: ABIEventData): unknown[] {
try {
const rawDecodedData = this.decodeEventLog(event);
const rawDecodedData = this.decodeEventLog(event);
if (rawDecodedData.args === undefined) {
return [];
} else if (rawDecodedData.args instanceof Object) {
return Object.values(rawDecodedData.args);
}
return rawDecodedData.args as unknown[];
} catch (error) {
throw new InvalidAbiDataToEncodeOrDecode(
'ABIEvent.decodeEventLogAsArray',
'Decoding failed: Data must be a valid hex string encoding a compliant ABI type.',
{ data: event },
error
);
if (rawDecodedData.args === undefined) {
return [];
}
return this.parseObjectValues(rawDecodedData.args as unknown as object);
}

@@ -140,0 +139,0 @@

@@ -7,2 +7,3 @@ import {

type AbiFunction,
type ContractFunctionName,
decodeFunctionData,

@@ -13,2 +14,3 @@ type DecodeFunctionDataReturnType,

encodeFunctionData,
type Abi as ViemABI,
type Hex as ViemHex

@@ -23,3 +25,7 @@ } from 'viem';

*/
class ABIFunction extends ABIItem {
class ABIFunction<
TAbi extends ViemABI = ViemABI,
TFunctionName extends
ContractFunctionName<TAbi> = ContractFunctionName<TAbi>
> extends ABIItem {
private readonly abiFunction: AbiFunction;

@@ -61,3 +67,5 @@ public constructor(signature: string);

*/
public decodeData(data: Hex): DecodeFunctionDataReturnType {
public decodeData(
data: Hex
): DecodeFunctionDataReturnType<TAbi, TFunctionName> {
try {

@@ -117,8 +125,15 @@ return decodeFunctionData({

*/
public decodeResult(data: Hex): DecodeFunctionResultReturnType {
public decodeResult(
data: Hex
): DecodeFunctionResultReturnType<TAbi, TFunctionName> {
try {
return decodeFunctionResult({
const result = decodeFunctionResult({
abi: [this.abiFunction],
data: data.toString() as ViemHex
});
return result as DecodeFunctionResultReturnType<
TAbi,
TFunctionName
>;
} catch (error) {

@@ -125,0 +140,0 @@ throw new InvalidAbiDataToEncodeOrDecode(

@@ -10,4 +10,2 @@ import {

type ABIItemType = AbiFunction | AbiEvent;
/**

@@ -18,3 +16,3 @@ * Represents an ABI (Application Binary Interface) item.

abstract class ABIItem extends ABI {
public readonly signature: ABIItemType;
public readonly signature: AbiFunction | AbiEvent;
public readonly stringSignature: string;

@@ -24,5 +22,5 @@ /**

*
* @param {string | ViemABI} signature - The signature of the ABI item (Function, Event...).
* @param {string | AbiFunction | AbiEvent} signature - The signature of the ABI item (Function, Event...).
**/
public constructor(signature: string | ABIItemType) {
public constructor(signature: string | AbiFunction | AbiEvent) {
super();

@@ -51,15 +49,22 @@ switch (typeof signature) {

public static ofSignature<T extends ABIItem>(
ABIItemConstructor: new (signature: ABIItemType) => T,
signature: ABIItemType
ABIItemConstructor: new (signature: AbiFunction) => T,
signature: AbiFunction
): T;
public static ofSignature<T extends ABIItem>(
ABIItemConstructor: new (signature: AbiEvent) => T,
signature: AbiEvent
): T;
/**
* Returns and instance of an ABIItem from a signature.
* @param ABIItemConstructor ABIItem constructor.
* @param {string | ABIItemType} signature Signature of the ABIIItem.
* @param {string | AbiFunction | AbiEvent} signature Signature of the ABIIItem.
* @returns {T} An instance of the ABIItem.
*/
public static ofSignature<T extends ABIItem>(
ABIItemConstructor: new (signature: string | ABIItemType) => T,
signature: string | ABIItemType
ABIItemConstructor: new (
signature: string | AbiFunction | AbiEvent
) => T,
signature: string | AbiFunction | AbiEvent
): T {

@@ -95,3 +100,3 @@ return new ABIItemConstructor(signature);

**/
public compareTo(that: ABIItem): number {
public override compareTo(that: ABIItem): number {
if (super.compareTo(that) !== 0) {

@@ -104,2 +109,2 @@ return -1;

export { ABIItem, type ABIItemType };
export { ABIItem };

@@ -1,2 +0,2 @@

import { ethersAbi } from './ABI';
import { ABI } from './ABI';
import { ABIContract } from './ABIContract';

@@ -7,2 +7,2 @@ import { ABIEvent } from './ABIEvent';

export { ethersAbi as abi, ABIContract, ABIEvent, ABIFunction, ABIItem };
export { ABI, ABIContract, ABIEvent, ABIFunction, ABIItem };

@@ -189,15 +189,2 @@ import { Keccak256 } from './hash/Keccak256';

// Backwards compatibility, remove when it is matured enough #1184
const addressUtils = {
fromPrivateKey: (privateKey: Uint8Array): string =>
Address.ofPrivateKey(privateKey).toString(),
fromPublicKey: (publicKey: Uint8Array): string =>
Address.ofPublicKey(publicKey).toString(),
isAddress: (addressToVerify: string): boolean =>
Address.isValid(addressToVerify),
toERC55Checksum: (address: string): string =>
Address.checksum(HexUInt.of(address)).toString()
};
export { Address, addressUtils };
export { Address };

@@ -32,3 +32,3 @@ import { Coin } from './Coin';

*/
public readonly wei: bigint = this.value.dp(VET.WEI_FD).sv;
public readonly wei: bigint = this.value.dp(VET.WEI_FD).scaledValue;

@@ -35,0 +35,0 @@ /**

@@ -33,3 +33,3 @@ import { Coin } from './Coin';

*/
public readonly wei: bigint = this.value.dp(VTHO.WEI_FD).sv;
public readonly wei: bigint = this.value.dp(VTHO.WEI_FD).scaledValue;

@@ -36,0 +36,0 @@ /**

@@ -5,4 +5,12 @@ import { InvalidDataType, InvalidOperation } from '@vechain/sdk-errors';

/**
* Represents a fixed-point number for precision arithmetic.
*/
class FixedPointNumber implements VeChainDataModel<FixedPointNumber> {
/**
* Base of value notation.
*/
private static readonly BASE = 10n;
/**
* The default number of decimal places to use for fixed-point math.

@@ -20,3 +28,3 @@ *

*
* @remarks {@link fd} and {@link sv} not meaningful.
* @remarks {@link fractionalDigits} and {@link scaledValue} not meaningful.
*

@@ -31,3 +39,3 @@ * @see [Number.NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN)

*
* @remarks {@link fd} and {@link sv} not meaningful.
* @remarks {@link fractionalDigits} and {@link scaledValue} not meaningful.
*

@@ -43,5 +51,10 @@ * @see [Number.NEGATIVE_INFINITY](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY)

/**
* Represents the one constant.
*/
public static readonly ONE = FixedPointNumber.of(1n);
/**
* The positive Infinite value.
*
* @remarks {@link fd} and {@link sv} not meaningful.
* @remarks {@link fractionalDigits} and {@link scaledValue} not meaningful.
*

@@ -80,15 +93,17 @@ * @see [Number.POSITIVE_INFINITY](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/POSITIVE_INFINITY)

*
* @remarks If `ef` is not zero, {@link fd} and {@link sv} are not meaningful.
* @remarks If `ef` is not zero, {@link fractionalDigits} and {@link scaledValue} are not meaningful.
*/
protected readonly ef: number;
protected readonly edgeFlag: number;
/**
* Fractional Digits or decimal places.
*
* @see [bignumber.js precision](https://mikemcl.github.io/bignumber.js/#sd)
*/
protected readonly fd: bigint;
public readonly fractionalDigits: bigint;
/**
* Scaled Value = value * 10 ^ {@link fd}.
* Scaled Value = value * 10 ^ {@link fractionalDigits}.
*/
public readonly sv: bigint;
public readonly scaledValue: bigint;

@@ -104,3 +119,6 @@ /**

if (this.isFinite()) {
return this.sv / 10n ** this.fd;
return (
this.scaledValue /
FixedPointNumber.BASE ** this.fractionalDigits
);
}

@@ -131,3 +149,3 @@ throw new InvalidOperation(

if (this.isZero()) return 0;
return Number(this.sv) * 10 ** -Number(this.fd);
return Number(this.scaledValue) * 10 ** -Number(this.fractionalDigits);
}

@@ -143,5 +161,5 @@

protected constructor(fd: bigint, sv: bigint, ef: number = 0) {
this.fd = fd;
this.ef = ef;
this.sv = sv;
this.fractionalDigits = fd;
this.edgeFlag = ef;
this.scaledValue = sv;
}

@@ -161,5 +179,5 @@

return new FixedPointNumber(
this.fd,
this.sv < 0n ? -this.sv : this.sv,
this.ef
this.fractionalDigits,
this.scaledValue < 0n ? -this.scaledValue : this.scaledValue,
this.edgeFlag
);

@@ -196,4 +214,4 @@ }

if (that.isPositiveInfinite()) return -1;
const fd = this.fd > that.fd ? this.fd : that.fd; // Max common fractional decimals.
const delta = this.dp(fd).sv - that.dp(fd).sv;
const fd = this.maxFractionalDigits(that, this.fractionalDigits); // Max common fractional decimals.
const delta = this.dp(fd).scaledValue - that.dp(fd).scaledValue;
return delta < 0n ? -1 : delta === 0n ? 0 : 1;

@@ -267,7 +285,11 @@ }

: FixedPointNumber.POSITIVE_INFINITY;
const fd = this.fd > that.fd ? this.fd : that.fd; // Max common fractional decimals.
const fd = this.maxFractionalDigits(that, this.fractionalDigits); // Max common fractional decimals.
return new FixedPointNumber(
fd,
FixedPointNumber.div(fd, this.dp(fd).sv, that.dp(fd).sv)
);
FixedPointNumber.div(
fd,
this.dp(fd).scaledValue,
that.dp(fd).scaledValue
)
).dp(this.fractionalDigits); // Minimize fractional decimals without precision loss.
}

@@ -285,20 +307,37 @@

private static div(fd: bigint, dividend: bigint, divisor: bigint): bigint {
return (10n ** fd * dividend) / divisor;
return (FixedPointNumber.BASE ** fd * dividend) / divisor;
}
/**
* Adjusts the precision of the floating-point number by the specified
* Adjust the precision of the floating-point number by the specified
* number of decimal places.
*
* @param {bigint | number} decimalPlaces - The number of decimal places to adjust to.
* @param decimalPlaces The number of decimal places to adjust to,
* it must be a positive value.
* @return {FixedPointNumber} A new FixedPointNumber instance with the adjusted precision.
* @throws InvalidDataType if `decimalPlaces` is negative.
*/
public dp(decimalPlaces: bigint | number): FixedPointNumber {
const fp = BigInt(decimalPlaces);
const dd = fp - this.fd; // Fractional Decimals Difference.
if (dd < 0) {
return new FixedPointNumber(fp, this.sv / 10n ** -dd);
} else {
return new FixedPointNumber(fp, this.sv * 10n ** dd);
const dp = BigInt(decimalPlaces);
if (dp >= 0) {
let fd = this.fractionalDigits;
let sv = this.scaledValue;
if (dp > fd) {
// Scale up.
sv *= FixedPointNumber.BASE ** (dp - fd);
fd = dp;
} else {
// Scale down.
while (fd > dp && sv % FixedPointNumber.BASE === 0n) {
fd--;
sv /= FixedPointNumber.BASE;
}
}
return new FixedPointNumber(fd, sv, this.edgeFlag);
}
throw new InvalidDataType(
'FixedPointNumber.scale',
'negative `dp` arg',
{ dp: `${dp}` }
);
}

@@ -325,3 +364,3 @@

*
* @param {FixedPointNumber} - that The FixedPointNumber to compare against.
* @param {FixedPointNumber} that The FixedPointNumber to compare against.
* @return {boolean} `true` if this FixedPointNumber is greater than `that` FixedPointNumber, otherwise `false`.

@@ -394,7 +433,11 @@ *

: FixedPointNumber.POSITIVE_INFINITY;
const fd = this.fd > that.fd ? this.fd : that.fd; // Max common fractional decimals.
const fd = this.maxFractionalDigits(that, this.fractionalDigits); // Max common fractional decimals.
return new FixedPointNumber(
fd,
FixedPointNumber.idiv(fd, this.dp(fd).sv, that.dp(fd).sv)
);
FixedPointNumber.idiv(
fd,
this.dp(fd).scaledValue,
that.dp(fd).scaledValue
)
).dp(this.fractionalDigits); // Minimize fractional decimals without precision loss.
}

@@ -411,3 +454,3 @@

private static idiv(fd: bigint, dividend: bigint, divisor: bigint): bigint {
return (dividend / divisor) * 10n ** fd;
return (dividend / divisor) * FixedPointNumber.BASE ** fd;
}

@@ -439,10 +482,10 @@

public isFinite(): boolean {
return this.ef === 0;
return this.edgeFlag === 0;
}
/**
* Return `true` if the value of this FixedPointNumber is {@link NEGATIVE_INFINITY} and {@link POSITIVE_INFINITY},
* Return `true` if the value of this FixedPointNumber is {@link NEGATIVE_INFINITY} or {@link POSITIVE_INFINITY},
* otherwise returns false.
*
* @return true` if the value of this FixedPointNumber is {@link NEGATIVE_INFINITY} and {@link POSITIVE_INFINITY},
* @return true` if the value of this FixedPointNumber is {@link NEGATIVE_INFINITY} or {@link POSITIVE_INFINITY},
*/

@@ -463,3 +506,7 @@ public isInfinite(): boolean {

if (this.isFinite()) {
return this.sv % 10n ** this.fd === 0n;
return (
this.scaledValue %
FixedPointNumber.BASE ** this.fractionalDigits ===
0n
);
}

@@ -490,3 +537,3 @@ return false;

public isNaN(): boolean {
return Number.isNaN(this.ef);
return Number.isNaN(this.edgeFlag);
}

@@ -515,3 +562,6 @@

public isNegative(): boolean {
return (this.isFinite() && this.sv < 0n) || this.isNegativeInfinite();
return (
(this.isFinite() && this.scaledValue < 0n) ||
this.isNegativeInfinite()
);
}

@@ -523,3 +573,3 @@

public isNegativeInfinite(): boolean {
return this.ef === Number.NEGATIVE_INFINITY;
return this.edgeFlag === Number.NEGATIVE_INFINITY;
}

@@ -558,3 +608,6 @@

public isPositive(): boolean {
return (this.isFinite() && this.sv >= 0n) || this.isPositiveInfinite();
return (
(this.isFinite() && this.scaledValue >= 0n) ||
this.isPositiveInfinite()
);
}

@@ -568,3 +621,3 @@

public isPositiveInfinite(): boolean {
return this.ef === Number.POSITIVE_INFINITY;
return this.edgeFlag === Number.POSITIVE_INFINITY;
}

@@ -580,3 +633,3 @@

public isZero(): boolean {
return this.isFinite() && this.sv === 0n;
return this.isFinite() && this.scaledValue === 0n;
}

@@ -618,2 +671,22 @@

/**
* Return the maximum between the fixed decimal value of this object and `that` one.
* If the maximum fixed digits value is less than `minFixedDigits`, return `minFixedDigits`.
*
* @param {FixedPointNumber} that to evaluate if `that` has the maximum fixed digits value.
* @param {bigint} minFixedDigits Min value of returned value, {@link FixedPointNumber.DEFAULT_FRACTIONAL_DECIMALS} by default.
*
* @return the greater fixed digits value among `this`, `that` and `minFixedDigits`.
*/
private maxFractionalDigits(
that: FixedPointNumber,
minFixedDigits: bigint = FixedPointNumber.DEFAULT_FRACTIONAL_DECIMALS
): bigint {
const fd =
this.fractionalDigits < that.fractionalDigits
? that.fractionalDigits
: this.fractionalDigits;
return fd > minFixedDigits ? fd : minFixedDigits;
}
/**
* Returns a FixedPointNumber whose value is the value of this FixedPointNumber minus `that` FixedPointNumber.

@@ -646,4 +719,7 @@ *

: FixedPointNumber.POSITIVE_INFINITY;
const fd = this.fd > that.fd ? this.fd : that.fd; // Max common fractional decimals.
return new FixedPointNumber(fd, this.dp(fd).sv - that.dp(fd).sv);
const fd = this.maxFractionalDigits(that, this.fractionalDigits); // Max common fractional decimals.
return new FixedPointNumber(
fd,
this.dp(fd).scaledValue - that.dp(fd).scaledValue
).dp(this.fractionalDigits); // Minimize fractional decimals without precision loss.
}

@@ -672,9 +748,9 @@

if (that.isZero()) return FixedPointNumber.NaN;
const fd = this.fd > that.fd ? this.fd : that.fd; // Max common fractional decimals.
let modulo = this.abs().dp(fd).sv;
const divisor = that.abs().dp(fd).sv;
const fd = this.maxFractionalDigits(that, this.fractionalDigits); // Max common fractional decimals.
let modulo = this.abs().dp(fd).scaledValue;
const divisor = that.abs().dp(fd).scaledValue;
while (modulo >= divisor) {
modulo -= divisor;
}
return new FixedPointNumber(fd, modulo);
return new FixedPointNumber(fd, modulo).dp(this.fractionalDigits); // Minimize fractional decimals without precision loss.
}

@@ -696,3 +772,3 @@

): bigint {
return (multiplicand * multiplicator) / 10n ** fd;
return (multiplicand * multiplicator) / FixedPointNumber.BASE ** fd;
}

@@ -711,3 +787,7 @@

return FixedPointNumber.NEGATIVE_INFINITY;
return new FixedPointNumber(this.fd, -this.sv, this.ef);
return new FixedPointNumber(
this.fractionalDigits,
-this.scaledValue,
this.edgeFlag
);
}

@@ -730,6 +810,13 @@

public static of(
exp: bigint | number | string,
exp: bigint | number | string | FixedPointNumber,
decimalPlaces: bigint = this.DEFAULT_FRACTIONAL_DECIMALS
): FixedPointNumber {
try {
if (exp instanceof FixedPointNumber) {
return new FixedPointNumber(
exp.fractionalDigits,
exp.scaledValue,
exp.edgeFlag
);
}
if (Number.isNaN(exp))

@@ -791,4 +878,7 @@ return new FixedPointNumber(decimalPlaces, 0n, Number.NaN);

: FixedPointNumber.POSITIVE_INFINITY;
const fd = this.fd > that.fd ? this.fd : that.fd; // Max common fractional decimals.
return new FixedPointNumber(fd, this.dp(fd).sv + that.dp(fd).sv);
const fd = this.maxFractionalDigits(that, this.fractionalDigits); // Max common fractional decimals.
return new FixedPointNumber(
fd,
this.dp(fd).scaledValue + that.dp(fd).scaledValue
).dp(this.fractionalDigits); // Minimize fractional decimals without precision loss.
}

@@ -799,2 +889,6 @@

*
* This method implements the
* [Exponentiation by Squaring](https://en.wikipedia.org/wiki/Exponentiation_by_squaring)
* algorithm.
*
* Limit cases

@@ -810,18 +904,13 @@ * * NaN ^ e = NaN

* @param {FixedPointNumber} that - The exponent as a fixed-point number.
* It can be negative, it can be not an integer value
* ([bignumber.js pow](https://mikemcl.github.io/bignumber.js/#pow)
* doesn't support not integer exponents).
* truncated to its integer component because **Exponentiation by Squaring** is not valid for rational exponents.
* @return {FixedPointNumber} - The result of raising this fixed-point number to the power of the given exponent.
*
* @remarks The precision is the greater of the precision of the two operands.
* @remarks In fixed-precision math, the comparisons between powers of operands having different fractional
* precision can lead to differences.
*
* @see [bignumber.js exponentiatedBy](https://mikemcl.github.io/bignumber.js/#pow)
*/
public pow(that: FixedPointNumber): FixedPointNumber {
// Limit cases
if (this.isNaN() || that.isNaN()) return FixedPointNumber.NaN;
if (this.isInfinite())
return that.isZero()
? FixedPointNumber.of(1)
? FixedPointNumber.ONE
: that.isNegative()

@@ -831,39 +920,21 @@ ? FixedPointNumber.ZERO

if (that.isNegativeInfinite()) return FixedPointNumber.ZERO;
if (that.isPositiveInfinite())
if (that.isPositiveInfinite()) {
return FixedPointNumber.POSITIVE_INFINITY;
const fd = this.fd > that.fd ? this.fd : that.fd; // Max common fractional decimals.
return new FixedPointNumber(
fd,
FixedPointNumber.pow(fd, this.dp(fd).sv, that.dp(fd).sv)
);
}
/**
* Computes the power of a given base raised to a specified exponent.
*
* @param {bigint} fd - The scale factor for decimal precision.
* @param {bigint} base - The base number to be raised to the power.
* @param {bigint} exponent - The exponent to which the base should be raised.
* @return {bigint} The result of base raised to the power of exponent, scaled by the scale factor.
*/
private static pow(fd: bigint, base: bigint, exponent: bigint): bigint {
const sf = 10n ** fd; // Scale factor.
if (exponent < 0n) {
return FixedPointNumber.pow(
fd,
FixedPointNumber.div(fd, sf, base),
-exponent
); // Recursive.
}
if (exponent === 0n) {
return 1n * sf;
if (that.isZero()) return FixedPointNumber.ONE;
// Exponentiation by squaring works for natural exponent value.
let exponent = that.abs().bi;
let base = FixedPointNumber.of(this);
let result = FixedPointNumber.ONE;
while (exponent > 0n) {
// If the exponent is odd, multiply the result by the current base.
if (exponent % 2n === 1n) {
result = result.times(base);
}
// Square the base and halve the exponent.
base = base.times(base);
exponent = exponent / 2n;
}
if (exponent === sf) {
return base;
}
return FixedPointNumber.pow(
fd,
this.mul(base, base, fd),
exponent - sf
); // Recursive.
// If exponent is negative, convert the problem to positive exponent.
return that.isNegative() ? FixedPointNumber.ONE.div(result) : result;
}

@@ -884,3 +955,3 @@

}
const sf = fd * 10n; // Scale Factor.
const sf = fd * FixedPointNumber.BASE; // Scale Factor.
let iteration = 0;

@@ -918,4 +989,4 @@ let actualResult = value;

return new FixedPointNumber(
this.fd,
FixedPointNumber.sqr(this.sv, this.fd)
this.fractionalDigits,
FixedPointNumber.sqr(this.scaledValue, this.fractionalDigits)
);

@@ -956,7 +1027,14 @@ // eslint-disable-next-line @typescript-eslint/no-unused-vars

: FixedPointNumber.POSITIVE_INFINITY;
const fd = this.fd > that.fd ? this.fd : that.fd; // Max common fractional decimals.
const fd =
this.fractionalDigits > that.fractionalDigits
? this.fractionalDigits
: that.fractionalDigits; // Max common fractional decimals.
return new FixedPointNumber(
fd,
FixedPointNumber.mul(this.dp(fd).sv, that.dp(fd).sv, fd)
);
FixedPointNumber.mul(
this.dp(fd).scaledValue,
that.dp(fd).scaledValue,
fd
)
).dp(this.fractionalDigits); // Minimize fractional decimals without precision loss.
}

@@ -971,8 +1049,13 @@

public toString(decimalSeparator = '.'): string {
if (this.ef === 0) {
const sign = this.sv < 0n ? '-' : '';
if (this.edgeFlag === 0) {
const sign = this.scaledValue < 0n ? '-' : '';
const digits =
this.sv < 0n ? (-this.sv).toString() : this.sv.toString();
const padded = digits.padStart(Number(this.fd), '0');
const decimals = this.fd > 0 ? padded.slice(Number(-this.fd)) : '';
this.scaledValue < 0n
? (-this.scaledValue).toString()
: this.scaledValue.toString();
const padded = digits.padStart(Number(this.fractionalDigits), '0');
const decimals =
this.fractionalDigits > 0
? padded.slice(Number(-this.fractionalDigits))
: '';
const integers = padded.slice(0, padded.length - decimals.length);

@@ -987,3 +1070,3 @@ const integersShow = integers.length < 1 ? '0' : integers;

}
return this.ef.toString();
return this.edgeFlag.toString();
}

@@ -1031,3 +1114,3 @@

}
const sf = 10n ** fd; // Scale Factor.
const sf = FixedPointNumber.BASE ** fd; // Scale Factor.
const di = exp.lastIndexOf(decimalSeparator); // Decimal Index.

@@ -1034,0 +1117,0 @@ if (di < 0) {

@@ -5,3 +5,2 @@ import { blake2b as nh_blake2b } from '@noble/hashes/blake2b';

import { HexUInt } from '../HexUInt';
import { Txt } from '../Txt';

@@ -44,21 +43,2 @@ /**

// Backwards compatibility, remove in future release #1184
function blake2b256(
data: string | Uint8Array,
returnType: 'buffer'
): Uint8Array;
function blake2b256(data: string | Uint8Array, returnType: 'hex'): string;
function blake2b256(
data: string | Uint8Array,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
returnType: 'buffer' | 'hex' = 'buffer'
): string | Uint8Array {
return returnType === 'buffer'
? Blake2b256.of(Txt.of(data).bytes).bytes
: Blake2b256.of(Txt.of(data).bytes).toString();
}
export { Blake2b256, blake2b256 };
export { Blake2b256 };

@@ -5,3 +5,2 @@ import { keccak_256 as nh_keccak_256 } from '@noble/hashes/sha3';

import { HexUInt } from '../HexUInt';
import { Txt } from '../Txt';

@@ -41,18 +40,2 @@ /**

// Backwards compatibility, remove in future release #1184
function keccak256(data: string | Uint8Array, returnType: 'buffer'): Uint8Array;
function keccak256(data: string | Uint8Array, returnType: 'hex'): string;
function keccak256(
data: string | Uint8Array,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
returnType: 'buffer' | 'hex' = 'buffer'
): string | Uint8Array {
return returnType === 'buffer'
? Keccak256.of(Txt.of(data).bytes).bytes
: Keccak256.of(Txt.of(data).bytes).toString();
}
export { Keccak256, keccak256 };
export { Keccak256 };

@@ -5,3 +5,2 @@ import * as nh_sha256 from '@noble/hashes/sha256';

import { HexUInt } from '../HexUInt';
import { Txt } from '../Txt';

@@ -40,18 +39,2 @@ /**

// Backwards compatibility, remove in future release #1184
function sha256(data: string | Uint8Array, returnType: 'buffer'): Uint8Array;
function sha256(data: string | Uint8Array, returnType: 'hex'): string;
function sha256(
data: string | Uint8Array,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
returnType: 'buffer' | 'hex' = 'buffer'
): string | Uint8Array {
return returnType === 'buffer'
? Sha256.of(Txt.of(data).bytes).bytes
: Sha256.of(Txt.of(data).bytes).toString();
}
export { Sha256, sha256 };
export { Sha256 };

@@ -14,3 +14,2 @@ import {

import { HDKey } from '../hdkey';
import { Address } from './Address';
import { type VeChainDataModel } from './VeChainDataModel';

@@ -233,19 +232,3 @@

// Backwards compatibility, remove in future versions #1184
const mnemonic = {
deriveAddress: (words: string[], path: string = 'm/0'): string =>
Address.ofMnemonic(words, path).toString(),
derivePrivateKey: (words: string[], path: string = 'm/0'): Uint8Array =>
Mnemonic.toPrivateKey(words, path),
generate: (
wordlistSize?: WordlistSizeType,
randomGenerator?: (
numberOfBytes: WordListRandomGeneratorSizeInBytes
) => Uint8Array
): string[] => Mnemonic.of(wordlistSize, randomGenerator),
isValid: (words: string[]): boolean => Mnemonic.isValid(words)
};
export { Mnemonic, mnemonic };
export { Mnemonic };
export type { WordListRandomGeneratorSizeInBytes, WordlistSizeType };

@@ -85,11 +85,2 @@ import { Txt } from './Txt';

// Backwards compatibility, remove when it is matured enough #1184
const revisionUtils = {
isRevisionAccount: (revision: string | number): boolean =>
Revision.isValid(revision),
isRevisionBlock: (revision: string | number): boolean =>
Revision.isValid(revision)
};
export { Revision, revisionUtils };
export { Revision };

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc