ethereumjs-util
- Version 7.1.5
- Published
- 310 kB
- 5 dependencies
- MPL-2.0 license
Install
npm i ethereumjs-util
yarn add ethereumjs-util
pnpm add ethereumjs-util
Overview
A collection of utility functions for Ethereum
Index
Variables
Functions
- addHexPrefix()
- arrayContainsArray()
- arrToBufArr()
- baToJSON()
- bnToHex()
- bnToRlp()
- bnToUnpaddedBuffer()
- bufArrToArr()
- bufferToHex()
- bufferToInt()
- defineProperties()
- ecrecover()
- ecsign()
- fromAscii()
- fromRpcSig()
- fromSigned()
- fromUtf8()
- generateAddress()
- generateAddress2()
- getBinarySize()
- getKeys()
- hashPersonalMessage()
- importPublic()
- intToBuffer()
- intToHex()
- isHexPrefixed()
- isHexString()
- isValidAddress()
- isValidChecksumAddress()
- isValidPrivate()
- isValidPublic()
- isValidSignature()
- isZeroAddress()
- keccak()
- keccak256()
- keccakFromArray()
- keccakFromHexString()
- keccakFromString()
- padToEven()
- privateToAddress()
- privateToPublic()
- publicToAddress()
- pubToAddress()
- ripemd160()
- ripemd160FromArray()
- ripemd160FromString()
- rlphash()
- setLengthLeft()
- setLengthRight()
- sha256()
- sha256FromArray()
- sha256FromString()
- stripHexPrefix()
- toAscii()
- toBuffer()
- toChecksumAddress()
- toCompactSig()
- toRpcSig()
- toType()
- toUnsigned()
- toUtf8()
- unpadArray()
- unpadBuffer()
- unpadHexString()
- validateNoLeadingZeroes()
- zeroAddress()
- zeros()
Classes
Interfaces
Enums
Type Aliases
Variables
variable KECCAK256_NULL
const KECCAK256_NULL: Buffer;
Keccak-256 hash of null
variable KECCAK256_NULL_S
const KECCAK256_NULL_S: string;
Keccak-256 hash of null
variable KECCAK256_RLP
const KECCAK256_RLP: Buffer;
Keccak-256 hash of the RLP of null
variable KECCAK256_RLP_ARRAY
const KECCAK256_RLP_ARRAY: Buffer;
Keccak-256 of an RLP of an empty array
variable KECCAK256_RLP_ARRAY_S
const KECCAK256_RLP_ARRAY_S: string;
Keccak-256 of an RLP of an empty array
variable KECCAK256_RLP_S
const KECCAK256_RLP_S: string;
Keccak-256 hash of the RLP of null
variable MAX_INTEGER
const MAX_INTEGER: BN;
The max integer that the evm can handle (2^256-1)
variable MAX_UINT64
const MAX_UINT64: BN;
2^64-1
variable TWO_POW256
const TWO_POW256: BN;
2^256
Functions
function addHexPrefix
addHexPrefix: (str: string) => string;
Adds "0x" to a given
String
if it does not already start with "0x".
function arrayContainsArray
arrayContainsArray: ( superset: unknown[], subset: unknown[], some?: boolean) => boolean;
Returns TRUE if the first specified array contains all elements from the second one. FALSE otherwise.
Parameter superset
Parameter subset
function arrToBufArr
arrToBufArr: { (arr: Uint8Array): Buffer; (arr: NestedUint8Array): NestedBufferArray; (arr: Uint8Array | NestedUint8Array): any;};
Converts a Uint8Array or NestedUint8Array to Buffer or NestedBufferArray
function baToJSON
baToJSON: (ba: any) => any;
Converts a
Buffer
orArray
to JSON.Parameter ba
(Buffer|Array) (Array|String|null)
function bnToHex
bnToHex: (value: BN) => PrefixedHexString;
Convert BN to 0x-prefixed hex string.
function bnToRlp
bnToRlp: (value: BN) => Buffer;
Deprecated alias for bnToUnpaddedBuffer
Deprecated
function bnToUnpaddedBuffer
bnToUnpaddedBuffer: (value: BN) => Buffer;
Convert value from BN to an unpadded Buffer (useful for RLP transport)
Parameter value
value to convert
function bufArrToArr
bufArrToArr: { (arr: Buffer): Uint8Array; (arr: NestedBufferArray): NestedUint8Array; (arr: any): Uint8Array | NestedUint8Array;};
Converts a Buffer or NestedBufferArray to Uint8Array or NestedUint8Array
function bufferToHex
bufferToHex: (buf: Buffer) => string;
Converts a
Buffer
into a0x
-prefixed hexString
.Parameter buf
Buffer
object to convert
function bufferToInt
bufferToInt: (buf: Buffer) => number;
Converts a
Buffer
to aNumber
.Parameter buf
Buffer
object to convertThrows
If the input number exceeds 53 bits.
function defineProperties
defineProperties: (self: any, fields: any, data?: any) => void;
Defines properties on a
Object
. It make the assumption that underlying data is binary.Parameter self
the
Object
to define properties onParameter fields
an array fields to define. Fields can contain: *
name
- the name of the properties *length
- the number of bytes the field can have *allowLess
- if the field can be less than the length *allowEmpty
Parameter data
data to be validated against the definitions
Deprecated
function ecrecover
ecrecover: ( msgHash: Buffer, v: BNLike, r: Buffer, s: Buffer, chainId?: BNLike) => Buffer;
ECDSA public key recovery from signature. NOTE: Accepts
v == 0 | v == 1
for EIP1559 transactionsReturns
Recovered public key
function ecsign
ecsign: { (msgHash: Buffer, privateKey: Buffer, chainId?: number): ECDSASignature; (msgHash: Buffer, privateKey: Buffer, chainId: any): ECDSASignatureBuffer;};
Returns the ECDSA signature of a message hash.
function fromAscii
fromAscii: (stringValue: string) => string;
Should be called to get hex representation (prefixed by 0x) of ascii string
Parameter string
Parameter optional
padding
Returns
hex representation of input string
function fromRpcSig
fromRpcSig: (sig: string) => ECDSASignature;
Convert signature format of the
eth_sign
RPC method to signature parameters NOTE: all because of a bug in geth: https://github.com/ethereum/go-ethereum/issues/2053 NOTE: After EIP1559,v
could be0
or1
but this function assumes it's a signed message (EIP-191 or EIP-712) adding27
at the end. Remove if needed.
function fromSigned
fromSigned: (num: Buffer) => BN;
Interprets a
Buffer
as a signed integer and returns aBN
. Assumes 256-bit numbers.Parameter num
Signed integer value
function fromUtf8
fromUtf8: (stringValue: string) => string;
Should be called to get hex representation (prefixed by 0x) of utf8 string
Parameter string
Parameter optional
padding
Returns
hex representation of input string
function generateAddress
generateAddress: (from: Buffer, nonce: Buffer) => Buffer;
Generates an address of a newly created contract.
Parameter from
The address which is creating this new address
Parameter nonce
The nonce of the from account
function generateAddress2
generateAddress2: (from: Buffer, salt: Buffer, initCode: Buffer) => Buffer;
Generates an address for a contract created using CREATE2.
Parameter from
The address which is creating this new address
Parameter salt
A salt
Parameter initCode
The init code of the contract being created
function getBinarySize
getBinarySize: (str: string) => number;
Get the binary size of a string
Parameter str
Returns
the number of bytes contained within the string
function getKeys
getKeys: ( params: Record<string, string>[], key: string, allowEmpty?: boolean) => string[];
Returns the keys from an array of objects.
Parameter params
Parameter key
Parameter allowEmpty
Returns
output just a simple array of output keys
Example 1
getKeys([{a: '1', b: '2'}, {a: '3', b: '4'}], 'a') => ['1', '3']`
function hashPersonalMessage
hashPersonalMessage: (message: Buffer) => Buffer;
Returns the keccak-256 hash of
message
, prefixed with the header used by theeth_sign
RPC call. The output of this function can be fed intoecsign
to produce the same signature as theeth_sign
call for a givenmessage
, or fed toecrecover
along with a signature to recover the public key used to produce the signature.
function importPublic
importPublic: (publicKey: Buffer) => Buffer;
Converts a public key to the Ethereum format.
function intToBuffer
intToBuffer: (i: number) => Buffer;
Converts an
Number
to aBuffer
Parameter i
{Buffer}
function intToHex
intToHex: (i: number) => string;
Converts a
Number
into a hexString
Parameter i
{String}
function isHexPrefixed
isHexPrefixed: (str: string) => boolean;
Returns a
Boolean
on whether or not the aString
starts with '0x'Parameter str
the string input value a boolean if it is or is not hex prefixed
Throws
if the str input is not a string
function isHexString
isHexString: (value: string, length?: number) => boolean;
Is the string a hex string.
Parameter value
Parameter length
Returns
output the string is a hex string
function isValidAddress
isValidAddress: (hexAddress: string) => boolean;
Checks if the address is a valid. Accepts checksummed addresses too.
function isValidChecksumAddress
isValidChecksumAddress: (hexAddress: string, eip1191ChainId?: BNLike) => boolean;
Checks if the address is a valid checksummed address.
See toChecksumAddress' documentation for details about the eip1191ChainId parameter.
function isValidPrivate
isValidPrivate: (privateKey: Buffer) => boolean;
Checks if the private key satisfies the rules of the curve secp256k1.
function isValidPublic
isValidPublic: (publicKey: Buffer, sanitize?: boolean) => boolean;
Checks if the public key satisfies the rules of the curve secp256k1 and the requirements of Ethereum.
Parameter publicKey
The two points of an uncompressed key, unless sanitize is enabled
Parameter sanitize
Accept public keys in other formats
function isValidSignature
isValidSignature: ( v: BNLike, r: Buffer, s: Buffer, homesteadOrLater?: boolean, chainId?: BNLike) => boolean;
Validate a ECDSA signature. NOTE: Accepts
v == 0 | v == 1
for EIP1559 transactionsParameter homesteadOrLater
Indicates whether this is being used on either the homestead hardfork or a later one
function isZeroAddress
isZeroAddress: (hexAddress: string) => boolean;
Checks if a given address is the zero address.
function keccak
keccak: (a: Buffer, bits?: number) => Buffer;
Creates Keccak hash of a Buffer input
Parameter a
The input data (Buffer)
Parameter bits
(number = 256) The Keccak width
function keccak256
keccak256: (a: Buffer) => Buffer;
Creates Keccak-256 hash of the input, alias for keccak(a, 256).
Parameter a
The input data (Buffer)
function keccakFromArray
keccakFromArray: (a: number[], bits?: number) => Buffer;
Creates Keccak hash of a number array input
Parameter a
The input data (number[])
Parameter bits
(number = 256) The Keccak width
function keccakFromHexString
keccakFromHexString: (a: string, bits?: number) => Buffer;
Creates Keccak hash of an 0x-prefixed string input
Parameter a
The input data (String)
Parameter bits
(number = 256) The Keccak width
function keccakFromString
keccakFromString: (a: string, bits?: number) => Buffer;
Creates Keccak hash of a utf-8 string input
Parameter a
The input data (String)
Parameter bits
(number = 256) The Keccak width
function padToEven
padToEven: (value: string) => string;
Pads a
String
to have an even lengthParameter value
output
function privateToAddress
privateToAddress: (privateKey: Buffer) => Buffer;
Returns the ethereum address of a given private key.
Parameter privateKey
A private key must be 256 bits wide
function privateToPublic
privateToPublic: (privateKey: Buffer) => Buffer;
Returns the ethereum public key of a given private key.
Parameter privateKey
A private key must be 256 bits wide
function publicToAddress
publicToAddress: (pubKey: Buffer, sanitize?: boolean) => Buffer;
function pubToAddress
pubToAddress: (pubKey: Buffer, sanitize?: boolean) => Buffer;
Returns the ethereum address of a given public key. Accepts "Ethereum public keys" and SEC1 encoded keys.
Parameter pubKey
The two points of an uncompressed key, unless sanitize is enabled
Parameter sanitize
Accept public keys in other formats
function ripemd160
ripemd160: (a: Buffer, padded: boolean) => Buffer;
Creates RIPEMD160 hash of a Buffer input.
Parameter a
The input data (Buffer)
Parameter padded
Whether it should be padded to 256 bits or not
function ripemd160FromArray
ripemd160FromArray: (a: number[], padded: boolean) => Buffer;
Creates RIPEMD160 hash of a number[] input.
Parameter a
The input data (number[])
Parameter padded
Whether it should be padded to 256 bits or not
function ripemd160FromString
ripemd160FromString: (a: string, padded: boolean) => Buffer;
Creates RIPEMD160 hash of a string input.
Parameter a
The input data (String)
Parameter padded
Whether it should be padded to 256 bits or not
function rlphash
rlphash: (a: rlp.Input) => Buffer;
Creates SHA-3 hash of the RLP encoded version of the input.
Parameter a
The input data
function setLengthLeft
setLengthLeft: (msg: Buffer, length: number) => Buffer;
Left Pads a
Buffer
with leading zeros till it haslength
bytes. Or it truncates the beginning if it exceeds.Parameter msg
the value to pad (Buffer)
Parameter length
the number of bytes the output should be (Buffer)
function setLengthRight
setLengthRight: (msg: Buffer, length: number) => Buffer;
Right Pads a
Buffer
with trailing zeros till it haslength
bytes. it truncates the end if it exceeds.Parameter msg
the value to pad (Buffer)
Parameter length
the number of bytes the output should be (Buffer)
function sha256
sha256: (a: Buffer) => Buffer;
Creates SHA256 hash of a Buffer input.
Parameter a
The input data (Buffer)
function sha256FromArray
sha256FromArray: (a: number[]) => Buffer;
Creates SHA256 hash of a number[] input.
Parameter a
The input data (number[])
function sha256FromString
sha256FromString: (a: string) => Buffer;
Creates SHA256 hash of a string input.
Parameter a
The input data (string)
function stripHexPrefix
stripHexPrefix: (str: string) => string;
Removes '0x' from a given
String
if presentParameter str
the string value
Returns
the string without 0x prefix
function toAscii
toAscii: (hex: string) => string;
Should be called to get ascii from its hex representation
Parameter string
in hex
Returns
ascii string representation of hex value
function toBuffer
toBuffer: (v: ToBufferInputTypes) => Buffer;
Attempts to turn a value into a
Buffer
. Inputs supported:Buffer
,String
(hex-prefixed),Number
, null/undefined,BN
and other objects with atoArray()
ortoBuffer()
method.Parameter v
the value
function toChecksumAddress
toChecksumAddress: (hexAddress: string, eip1191ChainId?: BNLike) => string;
Returns a checksummed address.
If an eip1191ChainId is provided, the chainId will be included in the checksum calculation. This has the effect of checksummed addresses for one chain having invalid checksums for others. For more details see [EIP-1191](https://eips.ethereum.org/EIPS/eip-1191).
WARNING: Checksums with and without the chainId will differ and the EIP-1191 checksum is not backwards compatible to the original widely adopted checksum format standard introduced in [EIP-55](https://eips.ethereum.org/EIPS/eip-55), so this will break in existing applications. Usage of this EIP is therefore discouraged unless you have a very targeted use case.
function toCompactSig
toCompactSig: (v: BNLike, r: Buffer, s: Buffer, chainId?: BNLike) => string;
Convert signature parameters into the format of Compact Signature Representation (EIP-2098). NOTE: Accepts
v == 0 | v == 1
for EIP1559 transactionsReturns
Signature
function toRpcSig
toRpcSig: (v: BNLike, r: Buffer, s: Buffer, chainId?: BNLike) => string;
Convert signature parameters into the format of
eth_sign
RPC method. NOTE: Acceptsv == 0 | v == 1
for EIP1559 transactionsReturns
Signature
function toType
toType: { <T extends TypeOutput>(input: null, outputType: T): null; <T extends TypeOutput>(input: undefined, outputType: T): undefined; <T extends TypeOutput>(input: any, outputType: T): TypeOutputReturnType[T];};
Convert an input to a specified type. Input of null/undefined returns null/undefined regardless of the output type.
Parameter input
value to convert
Parameter outputType
type to output
function toUnsigned
toUnsigned: (num: BN) => Buffer;
Converts a
BN
to an unsigned integer and returns it as aBuffer
. Assumes 256-bit numbers.Parameter num
function toUtf8
toUtf8: (hex: string) => string;
Returns the utf8 string representation from a hex string.
Examples:
Input 1: '657468657265756d000000000000000000000000000000000000000000000000' Input 2: '657468657265756d' Input 3: '000000000000000000000000000000000000000000000000657468657265756d'
Output (all 3 input variants): 'ethereum'
Note that this method is not intended to be used with hex strings representing quantities in both big endian or little endian notation.
Parameter string
Hex string, should be
0x
prefixed Utf8 string
function unpadArray
unpadArray: (a: number[]) => number[];
Trims leading zeros from an
Array
(of numbers).Parameter a
(number[]) (number[])
function unpadBuffer
unpadBuffer: (a: Buffer) => Buffer;
Trims leading zeros from a
Buffer
.Parameter a
(Buffer) (Buffer)
function unpadHexString
unpadHexString: (a: string) => string;
Trims leading zeros from a hex-prefixed
String
.Parameter a
(String) (String)
function validateNoLeadingZeroes
validateNoLeadingZeroes: (values: { [key: string]: any }) => void;
Checks provided Buffers for leading zeroes and throws if found.
Examples:
Valid values: 0x1, 0x, 0x01, 0x1234 Invalid values: 0x0, 0x00, 0x001, 0x0001
Note: This method is useful for validating that RLP encoded integers comply with the rule that all integer values encoded to RLP must be in the most compact form and contain no leading zero bytes
Parameter values
An object containing string keys and Buffer values
Throws
if any provided value is found to have leading zero bytes
function zeroAddress
zeroAddress: () => string;
Returns the zero address.
function zeros
zeros: (bytes: number) => Buffer;
Returns a buffer filled with 0s.
Parameter bytes
the number of bytes the buffer should be
Classes
class Account
class Account {}
constructor
constructor(nonce?: BN, balance?: BN, stateRoot?: Buffer, codeHash?: Buffer);
This constructor assigns and validates the values. Use the static factory methods to assist in creating an Account from varying data types.
property balance
balance: BN;
property codeHash
codeHash: Buffer;
property nonce
nonce: BN;
property stateRoot
stateRoot: Buffer;
method fromAccountData
static fromAccountData: (accountData: AccountData) => Account;
method fromRlpSerializedAccount
static fromRlpSerializedAccount: (serialized: Buffer) => Account;
method fromValuesArray
static fromValuesArray: (values: Buffer[]) => Account;
method isContract
isContract: () => boolean;
Returns a
Boolean
determining if the account is a contract.
method isEmpty
isEmpty: () => boolean;
Returns a
Boolean
determining if the account is empty complying to the definition of account emptiness in [EIP-161](https://eips.ethereum.org/EIPS/eip-161): "An account is considered empty when it has no code and zero nonce and zero balance."
method raw
raw: () => Buffer[];
Returns a Buffer Array of the raw Buffers for the account, in order.
method serialize
serialize: () => Buffer;
Returns the RLP serialization of the account as a
Buffer
.
class Address
class Address {}
constructor
constructor(buf: Buffer);
property buf
readonly buf: Buffer;
method equals
equals: (address: Address) => boolean;
Is address equal to another.
method fromPrivateKey
static fromPrivateKey: (privateKey: Buffer) => Address;
Returns an address for a given private key.
Parameter privateKey
A private key must be 256 bits wide
method fromPublicKey
static fromPublicKey: (pubKey: Buffer) => Address;
Returns an address for a given public key.
Parameter pubKey
The two points of an uncompressed key
method fromString
static fromString: (str: string) => Address;
Returns an Address object from a hex-encoded string.
Parameter str
Hex-encoded address
method generate
static generate: (from: Address, nonce: BN) => Address;
Generates an address for a newly created contract.
Parameter from
The address which is creating this new address
Parameter nonce
The nonce of the from account
method generate2
static generate2: (from: Address, salt: Buffer, initCode: Buffer) => Address;
Generates an address for a contract created using CREATE2.
Parameter from
The address which is creating this new address
Parameter salt
A salt
Parameter initCode
The init code of the contract being created
method isPrecompileOrSystemAddress
isPrecompileOrSystemAddress: () => boolean;
True if address is in the address range defined by EIP-1352
method isZero
isZero: () => boolean;
Is address zero.
method toBuffer
toBuffer: () => Buffer;
Returns Buffer representation of address.
method toString
toString: () => string;
Returns hex encoding of address.
method zero
static zero: () => Address;
Returns the zero address.
Interfaces
interface AccountData
interface AccountData {}
interface ECDSASignature
interface ECDSASignature {}
interface ECDSASignatureBuffer
interface ECDSASignatureBuffer {}
interface TransformableToArray
interface TransformableToArray {}
interface TransformableToBuffer
interface TransformableToBuffer {}
Enums
enum TypeOutput
enum TypeOutput { Number = 0, BN = 1, Buffer = 2, PrefixedHexString = 3,}
Type output options
member BN
BN = 1
member Buffer
Buffer = 2
member Number
Number = 0
member PrefixedHexString
PrefixedHexString = 3
Type Aliases
type AddressLike
type AddressLike = Address | Buffer | PrefixedHexString;
A type that represents an Address-like value. To convert to address, use
new Address(toBuffer(value))
type BNLike
type BNLike = BN | PrefixedHexString | number | Buffer;
type BufferLike
type BufferLike = | Buffer | Uint8Array | number[] | number | BN | TransformableToBuffer | PrefixedHexString;
type NestedBufferArray
type NestedBufferArray = Array<Buffer | NestedBufferArray>;
type NestedUint8Array
type NestedUint8Array = Array<Uint8Array | NestedUint8Array>;
type PrefixedHexString
type PrefixedHexString = string;
type ToBufferInputTypes
type ToBufferInputTypes = | PrefixedHexString | number | BN | Buffer | Uint8Array | number[] | TransformableToArray | TransformableToBuffer | null | undefined;
type TypeOutputReturnType
type TypeOutputReturnType = { [TypeOutput.Number]: number; [TypeOutput.BN]: BN; [TypeOutput.Buffer]: Buffer; [TypeOutput.PrefixedHexString]: PrefixedHexString;};
Package Files (10)
Dependencies (5)
Dev Dependencies (15)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/ethereumjs-util
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/ethereumjs-util)
- HTML<a href="https://www.jsdocs.io/package/ethereumjs-util"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 6310 ms. - Missing or incorrect documentation? Open an issue for this package.