Socket
Socket
Sign inDemoInstall

@vechain/sdk-core

Package Overview
Dependencies
Maintainers
8
Versions
32
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.29 to 1.0.0-beta.30

src/hash/Blake2b256.ts

14

package.json
{
"name": "@vechain/sdk-core",
"version": "1.0.0-beta.29",
"version": "1.0.0-beta.30",
"description": "Includes modules for fundamental operations like hashing and cryptography",

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

"scripts": {
"build": "rm -rf ./dist && tsup src/index.ts --format cjs,esm --dts",
"build": "rm -rf ./dist && tsup src/index.ts --format cjs,esm --external @noble/hashes --dts",
"lint": "eslint --ext .ts src --ext .ts tests",

@@ -42,12 +42,12 @@ "format": "prettier --write src/**/*.ts tests/**/*.ts",

"@ethereumjs/rlp": "^5.0.2",
"@noble/ciphers": "^0.5.2",
"@noble/ciphers": "^0.6.0",
"@scure/bip32": "^1.4.0",
"@scure/bip39": "^1.3.0",
"@types/elliptic": "^6.4.18",
"@vechain/sdk-errors": "1.0.0-beta.29",
"@vechain/sdk-logging": "1.0.0-beta.29",
"@vechain/sdk-errors": "1.0.0-beta.30",
"@vechain/sdk-logging": "1.0.0-beta.30",
"bignumber.js": "^9.1.2",
"blakejs": "^1.2.1",
"elliptic": "^6.5.6",
"ethers": "6.13.1",
"elliptic": "^6.5.7",
"ethers": "6.13.2",
"fast-json-stable-stringify": "^2.1.0"

@@ -54,0 +54,0 @@ },

@@ -13,3 +13,3 @@ # @vechain/sdk-core

- **Hash Functions and Public Key Cryptography**: VeChain SDK Core provides fundamental hash functions and methods for public key cryptography, ensuring the security of blockchain operations. Notable functions include blake2b256, keccak256, and secp256k.
- **Hash Functions and Public Key Cryptography**: VeChain SDK Core provides fundamental hash functions and methods for public key cryptography, ensuring the security of blockchain operations. Notable functions include Blake2b256.of, Keccak256.of, and Secp256k.of.
- **Accounts Handling**: Facilitating seamless account management, the package offers tools for private key generation, mnemonic handling, and keystore encryption/decryption. Users can efficiently manage accounts with mnemonics and keystore functionalities.

@@ -16,0 +16,0 @@ - **Transactions**: Empowering users to interact with the VeChainThor blockchain, VeChainSDK Core enables the construction, signing, and manipulation of transactions. Users can customize transactions with various clauses and gas settings, enhancing flexibility and control.

@@ -29,7 +29,18 @@ import { type Fragment } from 'ethers';

// For each input, if it is indexed, push the value to encode, otherwise push null
for (const input of eventInputs) {
input.indexed === true
? sanitizedValuesToEncode.push(valuesToEncode.shift())
: sanitizedValuesToEncode.push(null);
// push the value if it is indexed and not undefined
if (
input.indexed === true &&
valuesToEncode.length > 0 &&
valuesToEncode[0] !== undefined
) {
sanitizedValuesToEncode.push(valuesToEncode.shift());
} else {
// shift the value if it is not indexed and undefined
if (valuesToEncode.length > 0 && valuesToEncode[0] === undefined) {
valuesToEncode.shift();
}
// push a null value if the value is not indexed and undefined
sanitizedValuesToEncode.push(null);
}
}

@@ -36,0 +47,0 @@

@@ -0,7 +1,6 @@

import { CertificateSignature } from '@vechain/sdk-errors';
import fastJsonStableStringify from 'fast-json-stable-stringify';
import { CertificateSignature } from '@vechain/sdk-errors';
import { Hex, Txt } from '../vcdm';
import { addressUtils } from '../address-utils';
import { blake2b256 } from '../hash';
import { Blake2b256 } from '../hash';
import { secp256k1 } from '../secp256k1';
import { Address, Hex, Txt } from '../vcdm';
import { type Certificate } from './types';

@@ -65,3 +64,3 @@

* Secure audit function.
* - {@link blake2b256};
* - {@link Blake2b256.of};
* - {@link secp256k1.sign}.

@@ -82,3 +81,3 @@ *

signature: Hex.of(
secp256k1.sign(blake2b256(encode(cert)), privateKey)
secp256k1.sign(Blake2b256.of(encode(cert)).bytes, privateKey)
).toString()

@@ -100,3 +99,3 @@ };

* Secure audit function.
* - {@link blake2b256};
* - {@link Blake2b256.of};
* - {@link secp256k1.recover}.

@@ -132,6 +131,6 @@ *

const sign = Hex.of(cert.signature).bytes;
const hash = blake2b256(encode(cert));
const hash = Blake2b256.of(encode(cert)).bytes;
// The signer address is compared in lowercase to avoid
const signer = addressUtils
.fromPublicKey(secp256k1.recover(hash, sign))
const signer = Address.ofPublicKey(secp256k1.recover(hash, sign))
.toString()
.toLowerCase();

@@ -138,0 +137,0 @@

@@ -10,3 +10,3 @@ import { abi, coder, type FunctionFragment } from '../abi';

import { InvalidDataType } from '@vechain/sdk-errors';
import { addressUtils } from '../address-utils';
import { Address } from '../vcdm';

@@ -207,3 +207,3 @@ /**

if (!addressUtils.isAddress(senderAddress)) {
if (!Address.isValid(senderAddress)) {
throw new InvalidDataType(

@@ -216,3 +216,3 @@ 'transferNFT()',

if (!addressUtils.isAddress(contractAddress)) {
if (!Address.isValid(contractAddress)) {
throw new InvalidDataType(

@@ -219,0 +219,0 @@ 'transferNFT()',

@@ -5,7 +5,3 @@ import { ethers } from 'ethers';

export * from './abi';
export * from './address-utils';
export * from './bloom';
export * from './bloom';
export * from './certificate';
export * from './certificate';
export * from './clause';

@@ -17,3 +13,2 @@ export * from './contract';

export * from './keystore';
export * from './mnemonic';
export * from './secp256k1';

@@ -20,0 +15,0 @@ export * from './transaction';

import { dataUtils } from '../../../utils';
import { InvalidRLP } from '@vechain/sdk-errors';
import { Hex } from '../../../vcdm/Hex';
import { Hex } from '../../../vcdm';
import { type RLPInput } from '../types';

@@ -174,3 +174,3 @@

if (bi === 0n) return Buffer.alloc(0);
const hex = Hex.of(bi).hex;
const hex = Hex.of(bi).digits;

@@ -177,0 +177,0 @@ if (maxBytes !== undefined && hex.length > maxBytes * 2) {

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

import { Hex } from '../../../../vcdm/Hex';
import { Hex } from '../../../../vcdm';
import { ScalarKind } from '../scalarkind.abstract';

@@ -3,0 +3,0 @@ import {

@@ -1,4 +0,3 @@

export * from './types.d';
export * from './blake2b256';
export * from './sha256';
export * from './keccak256';
export * from './Blake2b256';
export * from './Keccak256';
export * from './Sha256';

@@ -11,3 +11,3 @@ import * as n_bip32 from '@scure/bip32';

import { secp256k1 } from '../secp256k1';
import { sha256 } from '../hash';
import { Sha256 } from '../hash';
import { VET_DERIVATION_PATH, X_PRIV_PREFIX, X_PUB_PREFIX } from '../utils';

@@ -86,3 +86,6 @@

privateKey.fill(0); // Clear the private key from memory.
const checksum = sha256(sha256(header)).subarray(0, 4);
const checksum = Sha256.of(Sha256.of(header).bytes).bytes.subarray(
0,
4
);
const expandedPrivateKey = n_utils.concatBytes(header, checksum);

@@ -130,3 +133,6 @@ try {

);
const checksum = sha256(sha256(header)).subarray(0, 4);
const checksum = Sha256.of(Sha256.of(header).bytes).bytes.subarray(
0,
4
);
const expandedPublicKey = n_utils.concatBytes(header, checksum);

@@ -133,0 +139,0 @@ try {

@@ -6,3 +6,2 @@ /**

import { SCRYPT_PARAMS } from './const';
import { addressUtils } from '../../../address-utils';
import { ethers } from 'ethers';

@@ -16,2 +15,3 @@ import { secp256k1 } from '../../../secp256k1';

import { type Keystore, type KeystoreAccount } from '../../types';
import { Address } from '../../../vcdm';

@@ -31,5 +31,5 @@ /**

const derivePublicKey = secp256k1.derivePublicKey(privateKey);
const deriveAddress = addressUtils.fromPublicKey(
const deriveAddress = Address.ofPublicKey(
Buffer.from(derivePublicKey)
);
).toString();

@@ -36,0 +36,0 @@ // Create keystore account compatible with ethers

@@ -6,10 +6,9 @@ /**

*/
import { ctr } from '@noble/ciphers/aes';
import * as n_utils from '@noble/curves/abstract/utils';
import { Hex } from '../../../vcdm/Hex';
import { scrypt } from '@noble/hashes/scrypt';
import { InvalidKeystoreParams, stringifyData } from '@vechain/sdk-errors';
import { ctr } from '@noble/ciphers/aes';
import { addressUtils } from '../../../address-utils';
import { keccak256 } from '../../../hash';
import { scrypt } from '@noble/hashes/scrypt';
import { Keccak256 } from '../../../hash';
import { secp256k1 } from '../../../secp256k1';
import { Address, Hex } from '../../../vcdm';
import { type Keystore, type KeystoreAccount } from '../../types';

@@ -282,3 +281,3 @@

*
* @remark **The private key must not be represented as string to avoid the
* @remarks **The private key must not be represented as string to avoid the
* [Memory Dumping](https://github.com/paulmillr/noble-hashes?tab=readme-ov-file#memory-dumping)

@@ -313,3 +312,3 @@ * attack**.

* - [ctr](https://github.com/paulmillr/noble-ciphers?tab=readme-ov-file#aes).
* - {@link keccak256}
* - {@link Keccak256.of}
* - `password` wiped after use.

@@ -327,3 +326,3 @@ * - `privateKey` wiped after use.

*
* @remark **The private key must not be represented as string to avoid the
* @remarks **The private key must not be represented as string to avoid the
* [Memory Dumping](https://github.com/paulmillr/noble-hashes?tab=readme-ov-file#memory-dumping)

@@ -372,13 +371,9 @@ * attack**.

return {
address: Hex.of(
addressUtils.fromPublicKey(
secp256k1.derivePublicKey(privateKey)
)
).hex,
address: Address.ofPrivateKey(privateKey).toString(),
crypto: {
cipher: KEYSTORE_CRYPTO_CIPHER,
cipherparams: {
iv: Hex.of(iv).hex
iv: Hex.of(iv).digits
},
ciphertext: Hex.of(ciphertext).hex,
ciphertext: Hex.of(ciphertext).digits,
kdf: 'scrypt',

@@ -390,8 +385,7 @@ kdfparams: {

r: kdf.r,
salt: Hex.of(kdf.salt).hex
salt: Hex.of(kdf.salt).digits
},
// Compute the message authentication code, used to check the password.
mac: Hex.of(
keccak256(n_utils.concatBytes(macPrefix, ciphertext))
).hex
mac: Keccak256.of(n_utils.concatBytes(macPrefix, ciphertext))
.digits
},

@@ -466,3 +460,3 @@ id: uuidV4(uuidRandom),

* Secure audit function.
* - {@link addressUtils.fromPrivateKey}
* - {@link Address.ofPrivateKey}
* - [ctr](https://github.com/paulmillr/noble-ciphers?tab=readme-ov-file#aes).

@@ -516,5 +510,4 @@ * - `password` wiped after use.

keystore.crypto.mac !==
Hex.of(
keccak256(n_utils.concatBytes(key.slice(16, 32), ciphertext))
).hex
Keccak256.of(n_utils.concatBytes(key.slice(16, 32), ciphertext))
.digits
) {

@@ -534,9 +527,6 @@ throw new InvalidKeystoreParams(

).decrypt(ciphertext);
const address = addressUtils.fromPrivateKey(privateKey);
const address = Address.ofPrivateKey(privateKey).toString();
if (
keystore.address !== '' &&
address !==
addressUtils.toERC55Checksum(
Hex.of(keystore.address).toString()
)
address !== Address.checksum(Hex.of(keystore.address))
) {

@@ -603,3 +593,3 @@ throw new InvalidKeystoreParams(

bytes[8] = (bytes[8] & 0x3f) | 0x80;
const value = Hex.of(bytes).hex;
const value = Hex.of(bytes).digits;
return [

@@ -606,0 +596,0 @@ value.substring(0, 8),

@@ -62,3 +62,3 @@ /**

*
* @remark **Differently from
* @remarks **Differently from
* [ethers KeystoreAccount](https://github.com/ethers-io/ethers.js/blob/main/src.ts/wallet/json-keystore.ts),

@@ -65,0 +65,0 @@ * this type represents the private key as a buffer of bytes to avoid

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

const p = n_secp256k1.ProjectivePoint.fromAffine(
n_secp256k1.ProjectivePoint.fromHex(Hex.of(x).hex).toAffine()
n_secp256k1.ProjectivePoint.fromHex(Hex.of(x).digits).toAffine()
);

@@ -120,0 +120,0 @@ return p.toRawBytes(false);

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

import { addressUtils } from '../../address-utils';
import { secp256k1 } from '../../secp256k1';

@@ -10,2 +9,3 @@ import { Transaction } from '../transaction';

import { type TransactionBody } from '../types';
import { Address } from '../../vcdm';

@@ -98,5 +98,5 @@ /**

const delegatedHash = transactionToSign.getSignatureHash(
addressUtils.fromPublicKey(
Address.ofPublicKey(
Buffer.from(secp256k1.derivePublicKey(signerPrivateKey))
)
).toString()
);

@@ -103,0 +103,0 @@ const signature = Buffer.concat([

@@ -1,4 +0,9 @@

import { addressUtils } from '../address-utils';
import {
InvalidSecp256k1Signature,
InvalidTransactionField,
NotDelegatedTransaction,
UnavailableTransactionField
} from '@vechain/sdk-errors';
import { type RLPValidObject } from '../encoding';
import { blake2b256 } from '../hash';
import { Blake2b256 } from '../hash';
import { secp256k1 } from '../secp256k1';

@@ -13,10 +18,4 @@ import {

} from '../utils';
import { Address, Hex } from '../vcdm';
import { type TransactionBody } from './types';
import {
InvalidSecp256k1Signature,
InvalidTransactionField,
NotDelegatedTransaction,
UnavailableTransactionField
} from '@vechain/sdk-errors';
import { Hex } from '../vcdm/Hex';

@@ -136,3 +135,3 @@ /**

// Address from public key
return addressUtils.fromPublicKey(Buffer.from(delegatorPublicKey));
return Address.ofPublicKey(Buffer.from(delegatorPublicKey)).toString();
}

@@ -200,3 +199,3 @@

// Correct delegateFor address
if (delegateFor !== undefined && !addressUtils.isAddress(delegateFor)) {
if (delegateFor !== undefined && !Address.isValid(delegateFor)) {
throw new InvalidTransactionField(

@@ -210,3 +209,3 @@ 'Transaction.getSignatureHash()',

// Encode transaction
const transactionHash = blake2b256(this._encode(false));
const transactionHash = Blake2b256.of(this._encode(false)).bytes;

@@ -216,3 +215,3 @@ // There is a delegateFor address (@note we already know that it is a valid address)

return Buffer.from(
blake2b256(
Blake2b256.of(
Buffer.concat([

@@ -222,3 +221,3 @@ Buffer.from(transactionHash),

])
)
).bytes
);

@@ -265,3 +264,3 @@ }

// Address from public key
return addressUtils.fromPublicKey(Buffer.from(originPublicKey));
return Address.ofPublicKey(Buffer.from(originPublicKey)).toString();
}

@@ -285,9 +284,8 @@

// Return transaction ID
return blake2b256(
return Blake2b256.of(
Buffer.concat([
this.getSignatureHash(),
Buffer.from(this.origin.slice(2), 'hex')
]),
'hex'
);
])
).toString();
}

@@ -294,0 +292,0 @@

@@ -0,6 +1,5 @@

export * from './abi';
export * from './data';
export * from './hdnode';
export * from './mnemonic';
export * from './secp256k1';
export * from './transaction';
export * from './abi';

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

const decodeBytes32String = (hex: string): string => {
if (!Hex.isValid(hex) || Hex.of(hex).hex.length !== 64)
if (!Hex.isValid(hex) || Hex.of(hex).digits.length !== 64)
throw new InvalidDataType(

@@ -20,0 +20,0 @@ 'dataUtils.decodeBytes32String()',

export * from './const';
export * from './bloom';
export * from './data';

@@ -7,2 +6,1 @@ export * from './hdnode';

export * from './units';
export * from './revision';

@@ -0,6 +1,6 @@

import { InvalidDataType } from '@vechain/sdk-errors';
import { type TransactionClause } from '../../transaction';
import { Address } from '../../vcdm';
import { Hex } from '../../vcdm/Hex';
import { TRANSACTIONS_GAS_CONSTANTS } from '../const';
import { addressUtils } from '../../address-utils';
import { InvalidDataType } from '@vechain/sdk-errors';
import { type TransactionClause } from '../../transaction';

@@ -29,3 +29,3 @@ /**

// Invalid address or no vet.domains name
if (!addressUtils.isAddress(clause.to) && !clause.to.includes('.'))
if (!Address.isValid(clause.to) && !clause.to.includes('.'))
throw new InvalidDataType(

@@ -32,0 +32,0 @@ 'TransactionUtils.intrinsicGas()',

@@ -172,3 +172,3 @@ import { BigNumber } from 'bignumber.js';

*
* @remark This function is a drop-in replacement for
* @remarks This function is a drop-in replacement for
* [ethers.formatUnits](https://docs.ethers.org/v6/api/utils/#formatUnits).

@@ -241,3 +241,3 @@ *

*
* @remark This function is a drop-in replacement for
* @remarks This function is a drop-in replacement for
* [ethers.parseUnits](https://docs.ethers.org/v6/api/utils/#parseUnits).

@@ -244,0 +244,0 @@ */

@@ -0,4 +1,8 @@

import * as nc_utils from '@noble/curves/abstract/utils';
import * as nh_utils from '@noble/hashes/utils';
import * as nc_utils from '@noble/curves/abstract/utils';
import { InvalidCastType, InvalidDataType } from '@vechain/sdk-errors';
import {
InvalidOperation,
InvalidDataType,
type ObjectErrorData
} from '@vechain/sdk-errors';
import { type VeChainDataModel } from './VeChainDataModel';

@@ -20,5 +24,5 @@

*/
class Hex extends String implements VeChainDataModel<Hex> {
class Hex implements VeChainDataModel<Hex> {
/**
* Negative multiplier of the {@link hex} absolute value.
* Negative multiplier of the {@link digits} absolute value.
*

@@ -30,3 +34,3 @@ * @type {number}

/**
* Positive multiplier of the {@link hex} absolute value.
* Positive multiplier of the {@link digits} absolute value.
*

@@ -57,3 +61,3 @@ * @type {number}

*/
protected static readonly REGEX_PREFIX: RegExp = /^-?0x/i;
protected static readonly REGEX_HEX_PREFIX: RegExp = /^-?0x/i;

@@ -63,5 +67,5 @@ /**

* @remark An empty content results in an empty string returned.
* @remarks An empty content results in an empty string returned.
*/
public readonly hex: string;
public readonly digits: string;

@@ -88,5 +92,3 @@ /**

) {
const normalizedDigits = normalize(digits);
super((sign < 0 ? '-0x' : '0x') + normalizedDigits);
this.hex = normalizedDigits;
this.digits = normalize(digits);
this.sign = sign;

@@ -101,3 +103,3 @@ }

public get abs(): Hex {
return new Hex(Hex.POSITIVE, this.hex);
return new Hex(Hex.POSITIVE, this.digits);
}

@@ -111,3 +113,3 @@

get bi(): bigint {
return BigInt(this.sign) * nc_utils.hexToNumber(this.hex);
return BigInt(this.sign) * nc_utils.hexToNumber(this.digits);
}

@@ -121,11 +123,11 @@

get bytes(): Uint8Array {
return nc_utils.hexToBytes(this.alignToBytes().hex);
return nc_utils.hexToBytes(this.alignToBytes().digits);
}
/**
* Retrieves the value of n.
* Returns the value of n.
*
* @return {number} The value of n.
*
* @throws {InvalidCastType<Hex>} Throws an error if this instance doesn't represent
* @throws {InvalidOperation<Hex>} Throws an error if this instance doesn't represent
* an [IEEE 754 double precision 64 bits floating point format](https://en.wikipedia.org/wiki/Double-precision_floating-point_format).

@@ -138,7 +140,6 @@ */

}
throw new InvalidCastType<Hex>(
'Hex.n',
'not an IEEE 754 float 64 number',
this
);
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
throw new InvalidOperation('Hex.n', 'not an IEEE 754 float 64 number', {
hex: this.toString()
});
}

@@ -152,5 +153,5 @@

public alignToBytes(): Hex {
return this.hex.length % 2 === 0
return this.digits.length % 2 === 0
? this
: new Hex(this.sign, '0' + this.hex);
: new Hex(this.sign, '0' + this.digits);
}

@@ -168,3 +169,3 @@

if (this.sign === that.sign) {
const digits = Math.max(this.hex.length, that.hex.length);
const digits = Math.max(this.digits.length, that.digits.length);
const thisBytes = this.fit(digits).bytes;

@@ -193,10 +194,13 @@ const thatBytes = that.fit(digits).bytes;

public fit(digits: number): Hex {
if (digits < this.hex.length) {
if (digits < this.digits.length) {
// Cut.
let cue = 0;
while (this.hex.length - cue > digits && this.hex.at(cue) === '0') {
while (
this.digits.length - cue > digits &&
this.digits.at(cue) === '0'
) {
cue++;
}
if (this.hex.length - cue === digits) {
return new Hex(this.sign, this.hex.slice(cue));
if (this.digits.length - cue === digits) {
return new Hex(this.sign, this.digits.slice(cue));
}

@@ -209,7 +213,7 @@ throw new InvalidDataType(

}
if (digits > this.hex.length) {
if (digits > this.digits.length) {
// Pad.
return new Hex(
this.sign,
'0'.repeat(digits - this.hex.length) + this.hex
'0'.repeat(digits - this.digits.length) + this.digits
);

@@ -239,3 +243,3 @@ }

isNumber(): boolean {
return this.hex.length === 32;
return this.digits.length === 32;
}

@@ -262,3 +266,3 @@

public static isValid0x(exp: string): boolean {
return Hex.REGEX_PREFIX.test(exp) && Hex.isValid(exp);
return Hex.REGEX_HEX_PREFIX.test(exp) && Hex.isValid(exp);
}

@@ -269,7 +273,7 @@

*
* @param {bigint | number | string | Uint8Array} exp - The value to convert to a Hex instance:
* * bigint, converted to a signed hexadecimal expression of its absolute value;
* @param {bigint | number | string | Uint8Array} exp - The value to represent in a Hex instance:
* * bigint is always representable in hexadecimal base notation;
* * number, encoded as [IEEE 754 double precision 64 bits floating point format](https://en.wikipedia.org/wiki/Double-precision_floating-point_format);
* * string, parsed as a hexadecimal expression, optionally signed `-`, optionally tagged with `0x`;
* * Uint8Array, encoded as hexadecimal expression of the bytes represented in the provided expression;
* * string is parsed as the hexadecimal expression of a bigint value, optionally tagged with `0x`;
* * Uint8Array is interpreted as the sequence of bytes.
*

@@ -307,3 +311,3 @@ * @returns {Hex} - A Hex instance representing the input value.

this.NEGATIVE,
this.REGEX_PREFIX.test(exp)
this.REGEX_HEX_PREFIX.test(exp)
? exp.slice(3)

@@ -315,3 +319,3 @@ : exp.slice(1)

this.POSITIVE,
this.REGEX_PREFIX.test(exp) ? exp.slice(2) : exp
this.REGEX_HEX_PREFIX.test(exp) ? exp.slice(2) : exp
);

@@ -340,3 +344,3 @@ }

*
* @remark Security auditable method, depends on
* @remarks Security auditable method, depends on
* * [`nh_utils.randomBytes`](https://github.com/paulmillr/noble-hashes?tab=readme-ov-file#utils).

@@ -352,4 +356,35 @@ */

}
/**
* Error handler for Hex and its subclasses so we do not hide them.
* To be used only for nested errors.
*
* @param error - The error to handle from the subclass.
* @param methodName - The name of the method that threw the error.
* @param {string} errorMessage - The error message to throw.
* @param {ObjectErrorData} data - The data to include in the error.
* @throws {InvalidDataType} - Throws an error with the given message and data.
*/
protected static throwInvalidDataType(
error: unknown,
methodName: string,
errorMessage: string,
data: ObjectErrorData
): never {
if (error instanceof InvalidDataType) {
throw error;
}
throw new InvalidDataType(methodName, errorMessage, data, error);
}
/**
* Returns a string representation of the object.
*
* @return {string} The string representation of the object.
*/
public toString(): string {
return (this.sign < 0 ? '-0x' : '0x') + this.digits;
}
}
export { Hex };

@@ -7,7 +7,4 @@ import { Hex } from './Hex';

*
* @description
* Any non-meaningful zero digits are removed from the hexadecimal expression of this instance.
* @remarks This class makes equal instances created from the same value as number or as bigint.
*
* @remark This class makes equal instances created from the same value as number or as bigint.
*
* @extends {Hex}

@@ -17,19 +14,2 @@ */

/**
* Creates a new instance of this class to represent the `hex` value,
* not meaningful zero digits are remved from the hexadecimal representation.
*
* @param {Hex} hex - The Hex object to be used for constructing a new instance.
*/
protected constructor(hex: Hex) {
let cue = 0;
while (cue < hex.hex.length && hex.hex.at(cue) === '0') {
cue++;
}
super(
hex.sign,
cue === hex.hex.length ? '0' : hex.hex.slice(cue, hex.hex.length)
);
}
/**
* Retrieves the value of n cast from this instance interpreted as the hexadecimal expression of a bigint value.

@@ -42,3 +22,3 @@ *

*
* @remark This class makes equal instances created from the same value as number or as bigint.
* @remarks This class makes equal instances created from the same value as number or as bigint.
*/

@@ -50,3 +30,3 @@ public override get n(): number {

}
throw new InvalidDataType('HexInt.of', 'not in the safe number range', {
throw new InvalidDataType('HexInt.n', 'not in the safe number range', {
bi: `${bi}`,

@@ -60,17 +40,16 @@ hex: this.toString()

*
* @param {bigint | number | string | Uint8Array | Hex} exp - The value to convert to a HexInt instance:
* * bigint is converted to its hexadecimal expression,
* * number is cast to a bigint then converted to its hexadecimal expression,
* it throws {@link InvalidDataType} if not an integer value,
* * string is parsed as a bigint hexadecimal expression,
* * Uint8Array is interpreted as the sequence of bytes expressing a bigint value,
* then concerted to its hexadecimal expression,
* @param {bigint | number | string | Uint8Array | Hex} exp - The expression to be interpreted as an integer:
* * bigint is always representable in hexadecimal base notation;
* * number is converted to a bigint then represented in hexadecimal base notation;
* it throws {@link InvalidDataType} if not an integer value;
* * string is parsed as the hexadecimal expression of a bigint value, optionally tagged with `0x`;
* * Uint8Array is interpreted as the sequence of bytes expressing a bigint value;
* * {@link Hex} is interpreted as expressing a bigint value.
*
* @returns {HexInt} - The converted HexInt object.
* @returns {HexInt} - The new HexInt object representing the given `exp`.
*
* @throws {InvalidDataType} - If the value is not a valid hexadecimal integer expression,
* @throws {InvalidDataType} - If the given `exp` is not a valid hexadecimal integer expression,
* if `exp` is a not integer number.
*
* @remark This class makes equal instances created from the same value as number or as bigint.
* @remarks This class makes equal instances created from the same value as number or as bigint.
*/

@@ -80,7 +59,8 @@ public static of(exp: bigint | number | string | Uint8Array | Hex): HexInt {

if (exp instanceof Hex) {
return new HexInt(exp);
return new HexInt(exp.sign, exp.digits);
}
if (typeof exp === 'number') {
if (Number.isInteger(exp)) {
return new HexInt(Hex.of(BigInt(exp)));
const hex = Hex.of(BigInt(exp));
return new HexInt(hex.sign, hex.digits);
}

@@ -92,3 +72,4 @@ // noinspection ExceptionCaughtLocallyJS

}
return new HexInt(Hex.of(exp));
const hex = Hex.of(exp);
return new HexInt(hex.sign, hex.digits);
} catch (e) {

@@ -95,0 +76,0 @@ throw new InvalidDataType(

@@ -6,3 +6,3 @@ import { HexInt } from './HexInt';

/**
* Represents a hexadecimal unsigned integer.
* Represents a hexadecimal unsigned integer value.
*

@@ -13,25 +13,54 @@ * @extends HexInt

/**
* Creates a new instance of this class to represent the absolute `hi` value.
* Regular expression for matching hexadecimal strings.
* An empty input is represented as a empty digits.
*
* @param {HexInt} hi - The HexInt object representing the hexadecimal value.
* @type {RegExp}
*/
private static readonly REGEX_HEXUINT: RegExp = /^(0x)?[0-9a-f]*$/i;
/**
* Regular expression pattern to match a prefix indicating hexadecimal number.
*
* @throws {InvalidDataType} Throws an error if the sign of hi is not positive.
* @type {RegExp}
*/
protected constructor(hi: HexInt) {
if (hi.sign >= Hex.POSITIVE) {
super(hi);
} else {
throw new InvalidDataType('HexUInt.constructor', 'not positive', {
hi
});
}
protected static readonly REGEX_HEXUINT_PREFIX: RegExp = /^0x/i;
/**
* Checks if the given string expression is a valid unsigned hexadecimal value.
*
* @param {string} exp - The string representation of a hexadecimal value.
*
* @return {boolean} - True if the expression is a valid unsigned hexadecimal value, case-insensitive,
* optionally prefixed with `0x`; false otherwise.
*/
public static isValid(exp: string): boolean {
return HexUInt.REGEX_HEXUINT.test(exp);
}
/**
* Create a HexUInt instance from the given expression interprete as an unsigned integer.
* Determines whether the given string is a valid unsigned hexadecimal number prefixed with '0x'.
*
* @param exp The expression to convert. It can be of type bigint, number, string, Uint8Array, or HexInt.
* @param {string} exp - The string to be evaluated.
* @return {boolean} - True if the string is a valid unsigned hexadecimal number prefixed with '0x', otherwise false.
*/
public static isValid0x(exp: string): boolean {
return HexUInt.REGEX_HEX_PREFIX.test(exp) && Hex.isValid(exp);
}
/**
* Create a HexUInt instance from a bigint, number, string, Uint8Array, or {@link HexInt}.
*
* @returns {HexUInt} The converted hexadecimal unsigned integer.
* @param {bigint | number | string | Uint8Array | HexInt} exp - The expression to be interpreted as an unsigned integer:
* * bigint is always representable in hexadecimal base notation,
* it throws {@link InvalidDataType} if not positive;
* * number is converted to a bigint then represented in hexadecimal base notation,
* it throws {@link InvalidDataType} if not a positive integer value;
* * string is parsed as the hexadecimal expression of a bigint value, optionally tagged with `0x`;
* it throws {@link InvalidDataType} if not positive;
* * Uint8Array is interpreted as the sequence of bytes expressing a positive bigint value;
* * {@link HexInt} is interpreted as expressing a bigint value,
* it throws {@link InvalidDataType} if not positive.
*
* @returns {HexUInt} he new HexInt object representing the given `exp`.
*
* @throws {InvalidDataType} If the given expression is not a valid hexadecimal positive integer expression.

@@ -43,3 +72,11 @@ */

try {
return new HexUInt(HexInt.of(exp));
const hint = HexInt.of(exp);
if (hint.sign >= Hex.POSITIVE) {
return new HexUInt(hint.sign, hint.digits);
}
throw new InvalidDataType(
'HexUInt.of',
'not positive',
{ exp: `${exp}` } // Needed to serialize bigint values.
);
} catch (e) {

@@ -49,3 +86,3 @@ throw new InvalidDataType(

'not a hexadecimal positive integer expression',
{ exp },
{ exp: `${exp}`, e }, // Needed to serialize bigint values.
e

@@ -52,0 +89,0 @@ );

@@ -0,6 +1,14 @@

export * from './account';
export * from './Address';
export * from './BloomFilter';
export * from './Currency';
export * from './Hash';
export * from './Hex';
export * from './HexInt';
export * from './HexUInt';
export * from './Mnemonic';
export * from './Quantity';
export * from './Revision';
export * from './ThorId';
export * from './Txt';
export * from './VeChainDataModel';
import { Hex } from './Hex';
import { HexUInt } from './HexUInt';
import { InvalidDataType } from '@vechain/sdk-errors';
/**
* Represents a ThorId.
* @experiemntal
* The ThorId class represents a Thor ID value, which is a hexadecimal positive integer having 64 digits.
*
* @extends HexInt
*/
class ThorId extends Hex {
class ThorId extends HexUInt {
/**
* Number of digits to represent a Thor ID value.
*
* @remarks The `0x` prefix is excluded.
*
* @type {number}

@@ -19,10 +23,9 @@ */

*
* @param {Hex} hex - The hexadecimal value representing the ThorId.
* @param {HexUInt} huint - The hexadecimal value representing the ThorId.
*
* @throws {InvalidDataType} - If the provided value is not a valid ThorId expression.
* @experiemntal
*/
protected constructor(hex: Hex) {
if (ThorId.isValid(hex.hex)) {
super(Hex.POSITIVE, hex.hex);
protected constructor(huint: HexUInt) {
if (ThorId.isValid(huint.digits)) {
super(Hex.POSITIVE, huint.digits);
} else {

@@ -32,3 +35,3 @@ throw new InvalidDataType(

'not a ThorId expression',
{ hex }
{ hex: huint }
);

@@ -42,7 +45,7 @@ }

* @param {string} exp - The expression to be validated.
*
* @return {boolean} Returns true if the expression is a valid ThorId, false otherwise.
* @experimental
*/
public static isValid(exp: string): boolean {
return Hex.isValid(exp) && Hex.REGEX_PREFIX.test(exp)
return Hex.isValid(exp) && HexUInt.REGEX_HEXUINT_PREFIX.test(exp)
? exp.length === ThorId.DIGITS + 2

@@ -56,7 +59,7 @@ : exp.length === ThorId.DIGITS;

* @param {string} exp - The hex number to be checked.
* @returns {boolean} - True if the hex number is valid, false otherwise.
* @experimental
*
* @returns {boolean} - True if the hex number is valid, false otherwise.
*/
public static isValid0x(exp: string): boolean {
return Hex.REGEX_PREFIX.test(exp) && ThorId.isValid(exp);
return HexUInt.REGEX_HEXUINT_PREFIX.test(exp) && ThorId.isValid(exp);
}

@@ -72,12 +75,25 @@

* - string: A string value that represents the ThorId.
* - Hex: A Hex object that represents the ThorId.
* - HexUInt: A HexUInt object that represents the ThorId.
* - Uint8Array: A Uint8Array object that represents the ThorId.
*
* @returns {ThorId} - A new ThorId object created from the given expression.
* @experimntal
*
* @throws {InvalidDataType} If the given expression is not a valid hexadecimal positive integer expression.
*/
public static of(exp: bigint | number | string | Hex | Uint8Array): ThorId {
if (exp instanceof Hex) {
return new ThorId(exp.fit(this.DIGITS));
public static of(
exp: bigint | number | string | Uint8Array | HexUInt
): ThorId {
try {
if (exp instanceof Hex) {
return new ThorId(exp.fit(this.DIGITS));
}
return new ThorId(HexUInt.of(exp).fit(ThorId.DIGITS));
} catch (e) {
throw new InvalidDataType(
'ThorId.of',
'not a ThorId expression',
{ exp: `${exp}` }, // Needed to serialize bigint values.
e
);
}
return new ThorId(Hex.of(exp).fit(ThorId.DIGITS));
}

@@ -84,0 +100,0 @@ }

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

import { InvalidCastType } from '@vechain/sdk-errors';
import { InvalidOperation } from '@vechain/sdk-errors';
import { type VeChainDataModel } from './VeChainDataModel';

@@ -53,3 +53,4 @@

* @returns {bigint} The BigInt representation of the Txt string.
* @throws {InvalidCastType} If the conversion to BigInt fails because this Txt string doesn't represent an integer.
*
* @throws {InvalidOperation} If the conversion to BigInt fails because this Txt string doesn't represent an integer.
*/

@@ -61,6 +62,6 @@ get bi(): bigint {

// eslint-disable-next-line @typescript-eslint/no-unsafe-call
throw new InvalidCastType<Txt>(
throw new InvalidOperation(
'Txt.bi()',
"Can't cast to big integer",
this,
{ txt: this.toString() },
e

@@ -89,3 +90,4 @@ );

* @returns {number} The numeric value of the Txt string.
* @throws {InvalidCastType} If the conversion to number fails because this Txt string doesn't represent a decimal number.
*
* @throws {InvalidOperation} If the conversion to number fails because this Txt string doesn't represent a decimal number.
*/

@@ -100,2 +102,3 @@ get n(): number {

* @param {Txt} that - The instance to compare with.
*
* @return {number} - A negative number if the current instance is less than the specified instance,

@@ -112,3 +115,4 @@ * zero if they are equal, or a positive number if the current instance is greater.

* @param {Txt} that - The Txt object to compare with.
* @return {boolean} - True if the objects are equal, false otherwise.
*
* @return {boolean} - True if the objects are equal, false otherwise.
*/

@@ -136,2 +140,3 @@ public isEqual(that: Txt): boolean {

* * {@link Uint8Array} is {@link NFC} decoded to a string.
*
* @returns {Txt} - A new Txt instance.

@@ -138,0 +143,0 @@ */

/**
* Root interface for all the classes part of the `VeChain Data Model`
* to provide a coherent API to represent, encode, and cast data among data types.
*
* @interface
*/

@@ -9,3 +11,3 @@ export interface VeChainDataModel<T> {

* Return this instance cast to a big integer value
* @throws InvalidCastType if this object can't cast to a big integer.
* @throws InvalidOperation if this object can't cast to a big integer.
*/

@@ -21,3 +23,3 @@ get bi(): bigint;

* Return this object cast to number value.
* @throws InvalidCastType if this object can't cast to a big integer.
* @throws InvalidOperation if this object can't cast to a big integer.
*/

@@ -24,0 +26,0 @@ get n(): number;

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