Utilities¶
The utility functions provide a large assortment of common utility functions required to write dapps, process user input, and format data.
Addresses¶
Wallet address is uses Bech32 format (BIP-173). There are several formats available to represent wallet addresses and they can be determined in various ways.
- utils . getAddress ( address ) => Address
Normalize any supported address-format to include checksum.
- utils . computeHexAddress ( address ) => Address
Convert the supported address-format to checksum hex-format.
- utils . getHash ( hash ) => string
Convert the hash to checksum hex-format.
let address = "manifold1x7tp9tt7mu0jm6qdmljgntvzzp53lrtndr7h8x";
console.log(manifold.utils.getAddress(address));
// manifold1x7tp9tt7mu0jm6qdmljgntvzzp53lrtndr7h8x
console.log(manifold.utils.computeHexAddress(address));
// 0x379612aD7EDf1f2de80DDFE489Ad8210691F8d73
let hash = "0x47bef4762a8b5646f03b346e64cebde005370a2d4c0610c833fa17828ad1878e";
console.log(manifold.utils.getHash(hash));
// 0x47bef4762a8B5646F03B346E64cEBdE005370a2D4C0610C833Fa17828Ad1878e
Arrayish¶
An arrayish object is used to describe binary data and has met the following conditions met:
has a length property
has a value for each index from 0 up to (but excluding) length
has a valid byte for each value; a byte is an integer in the range of 0 to 255
is not a string
Examples: Buffer, [ 1, 2, 3 ], Uint8Array
- utils . isArrayish ( object ) => boolean
Returns true if object can be treated as an arrayish object.
- utils . arrayify ( hexStringOrBigNumberOrArrayish ) => Uint8Array
Returns a Uint8Array of a hex string, BigNumber or of an Arrayish object.
- utils . concat ( arrayOfHexStringsAndArrayish ) => Uint8Array
Returns a Uint8Array of all arrayOfHexStringsAndArrayish concatenated.
- utils . padZeros ( typedUint8Array, length ) => Uint8Array
Returns a Uint8Array of typedUint8Array with zeros prepended to length bytes.
- utils . stripZeros ( hexStringOrArrayish ) => Uint8Array
Returns a Uint8Array with all leading zero bytes striped.
Big Numbers¶
A BigNumber is an immutable object which allows accurate math operations on values larger than JavaScript can accurately handle to be safely handled. See also: Constants
- prototype . add ( otherValue ) => BigNumber
Returns a new BigNumber of this plus otherValue.
- prototype . sub ( otherValue ) => BigNumber
Returns a new BigNumber of this minus otherValue.
- prototype . mul ( otherValue ) => BigNumber
Returns a new BigNumber of this times otherValue.
- prototype . div ( otherValue ) => BigNumber
Returns a new BigNumber of this divided by otherValue.
- prototype . mod ( otherValue ) => BigNumber
Returns a new BigNumber of this modulo otherValue.
- prototype . maskn ( bits ) => BigNumber
Returns a new BigNumber with the number of bits masked.
- prototype . eq ( otherValue ) => boolean
Returns true if this is equal to otherValue.
- prototype . lt ( otherValue ) => boolean
Returns true if this is less than otherValue.
- prototype . lte ( otherValue ) => boolean
Returns true if this is less than or equal to otherValue.
- prototype . gt ( otherValue ) => boolean
Returns true if this is greater than otherValue.
- prototype . gte ( otherValue ) => boolean
Returns true if this is greater than or equal to otherValue.
- prototype . isZero ( ) => boolean
Returns true if this is equal to zero.
- prototype . toNumber ( ) => number
Returns a JavaScript number of the value.
An error is thrown if the value is outside the safe range for JavaScript IEEE 754 64-bit floating point numbers (over 53 bits of mantissa).
- prototype . toString () => string
Returns a decimal string representation.
- prototype . toHexString ( ) => hex
Returns a hex string representation of the value.
Creating Instances¶
- utils . bigNumberify ( value ) => BigNumber
Returns a BigNumber instance of value. The value may be anything that can be reliably converted into a BigNumber:
Type
Examples
Notes
decimal string
"42","-42"hexadecimal string
"0x2a","-0x2a"case-insensitive
numbers
42,-42must be witin the safe range
[ 30, 252 ]big-endian encoding
BigNumber
any other BigNumber
returns the same instance
let value = utils.bigNumberify("12345678901234567890");
let rate = utils.bigNumberify(3000000);
let finalValue = value.mul(rate);
console.log("Final value: " + finalValue.toString());
// Final value: 37037036703703703670000000
console.log("Number: " + finalValue.toNumber());
// throws an error, the value is too large for JavaScript to handle safely
Bytes32 Strings¶
Often for short strings, it is far more efficient to store them as a fixed, null-terminated bytes32, instead of a dynamic length-prefixed bytes.
- utils . formatBytes32String ( text ) => hex
Returns a hex string representation of text, exactly 32 bytes wide. Strings must be 31 bytes or shorter, or an exception is thrown.
NOTE: Keep in mind that UTF-8 characters outside the ASCII range can be multiple bytes long.
- utils . parseBytes32String ( hexStringOrArrayish ) => string
Returns hexStringOrArrayish as the original string, as generated by
formatBytes32String.
let text = "Hello Blockchain!"
let bytes32 = utils.formatBytes32String(text)
// "0x48656c6c6f20426c6f636b636861696e21000000000000000000000000000000"
let originalText = utils.parseBytes32String(bytes32)
// "Hello Blockchain!"
Constants¶
- manifold . constants . AddressZero
The address
manifold1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqgcpfl3.- manifold . constants . HashZero
The bytes32
0x0000000000000000000000000000000000000000000000000000000000000000.- manifold . constants . MaxUint256
The bytes32
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff.- manifold . constants . NegativeOne
The BigNumber
bigNumberify(-1).- manifold . constants . Zero
The BigNumber
bigNumberify(0).- manifold . constants . One
The BigNumber
bigNumberify(1).- manifold . constants . Two
The BigNumber
bigNumberify(2).- manifold . constants . GweiPerMan
The BigNumber
bigNumberify("1000000000000000000").
Cryptographic Functions¶
Elliptic Curve¶
- utils . computeAddress ( publicOrPrivateKey ) => Address
Computes the address given a public key or private key.
- utils . computeHexAddress ( address ) => Address
Convert the supported address-format to checksum hex-format.
- utils . computePublicKey ( publicOrPrivateKey [ , compressed = false ] ) => hex
Computes the public key for publicOrPrivateKey, optionally compressed. If publicOrPrivateKey is a public key, it may be either compressed or uncompressed.
- utils . recoverAddress ( digest , signature [ , recoveryParam ] ) => Address
Returns the address by using ecrecover with the digest for the signature.
- utils . recoverPublicKey ( digest , signature [ , recoveryParam ] ) => hex
Returns the public key by using ecrecover with the digest for the signature.
- utils . verifyMessage ( messageStringOrArrayish , signature [ , recoveryParam ] ) => Addresss
Returns the address of the account that signed messageStringOrArrayish to generate signature.
- utils . verify ( messageStringOrArrayish , signature, address ) => Boolean
Returns true if the signature is signed by the address.
let privateKey = "0xca250aeca008d36b4b4ff83709343c9e4c4ea461e5aa5fa51d57a0fe11eb045e";
let wallet = new manifold.Wallet(privateKey);
let message = "Hello Blockchain!";
return wallet.signMessage(message, true).then((signature) => {
let address = utils.verifyMessage(message, signature);
console.log("Signed by:", address);
// manifold1x7tp9tt7mu0jm6qdmljgntvzzp53lrtndr7h8x
});
Hash Functions¶
- utils . sha256 ( hexStringOrArrayish ) => hex
Computes the SHA2-256 cryptographic hash of a value, returned as a hex string.
console.log(utils.sha256([ 0x12, 0x02 ]));
// "0xa8b1b4fe0930de4baff9b55286f7ba78edbcb3f2b18f6ad7e9336c541bf60515"
console.log(utils.sha256("0x1202"));
// "0xa8b1b4fe0930de4baff9b55286f7ba78edbcb3f2b18f6ad7e9336c541bf60515"
Hash Function Helpers¶
- utils . hashMessage ( stringOrArrayish ) => hex
Computes the SHA2-256 value by converting the message to bytes (as necessary).
- utils . id ( utf8String ) => hex
Computes the SHA2-256 cryptographic hash of a UTF-8 string, returned as a hex string.
// Convert the string to binary data
let message = "Hello Blockchain!";
let messageBytes = utils.toUtf8Bytes(message);
console.log(utils.sha256(messageBytes));
// "0xdc2a5349136fe31362ddca95d7f8d3adb35c8eb3261f39ff519b1e33988a3b1f"
// Which is equivalent to using the id function
console.log(utils.id("Hello Blockchain!"));
// "0xdc2a5349136fe31362ddca95d7f8d3adb35c8eb3261f39ff519b1e33988a3b1f"
Key Derivation¶
- utils . pbkdf2 ( password , salt , iterations , keylen , hashAlgorithm )
Returns the PBKDF2-derived key from password and salt with iterations of length using the hashAlgorithm. The supported hash algorithms are
sha256andsha512.
Random¶
- utils . randomBytes ( length ) => Uint8Array
Returns a Uint8Array of cryptographically secure random bytes.
let randomBytes3 = utils.randomBytes(3)
// Uint8Array [ 127, 203, 43 ]
let randomBytes32 = utils.randomBytes(32)
// Uint8Array [ 150, 131, 148, 78, 45, 225, 72, 89, 145, 104, 97, 29,
// 252, 55, 70, 88, 203, 255, 151, 106, 241, 106, 1, 87,
// 3, 109, 34, 166, 122, 132, 176, 209 ]
let randomNumber = utils.bigNumberify(utils.randomBytes(32));
// BigNumber { _hex: 0x5de9cfc233211c316be4a1eb0fd6d9f8244386a704681310a8f59a4b7cebe2a5 }
ERC Strings and Gwei¶
- utils . parseMan ( manifoldString ) => BigNumber
Parses the manifoldString representation of ERC into a BigNumber instance of the amount of gwei.
- utils . formatMan ( gwei ) => string
Formats an amount of gwei into a decimal string representing the amount of ERC. The output will always include at least one whole number and at least one decimal place, otherwise leading and trailing 0’s will be trimmed.
- utils . parseUnits ( valueString , decimalsOrUnitName ) => BigNumber
Parses the valueString representation of units into a BigNumber. The decimalsOrUnitsName may be a number of decimals between 3 and 18 (multiplication of 3).
- utils . formatUnits ( value , decimalsOrUnitName ) => string
Formats an amount of gwei into a decimal string representing the amount of units. The output will always include at least one whole number and at least one decimal place, otherwise leading and trailing 0’s will be trimmed. The decimalsOrUnitsName may be a number of decimals between 3 and 18 (multiplication of 3).
- utils . commify ( numberOrString ) => string
Returns numberOrString with commas placed at every third position within the whole component. If numberOrString contains a decimal point, the output will also contain at least one digit for both the whole and decimal components. If there no decimal, then the output will also not contain a decimal.
let value = utils.parseMan('1000.0');
console.log(value.toString());
// "1000000000000000000000"
console.log(utils.formatMan(0));
// "0.0"
let gwei = utils.bigNumberify("1000000000000000000000");
console.log(utils.formatMan(gwei));
// "1000.0"
console.log(utils.commify(gwei.toString()));
// "1,000,000,000,000,000,000,000"
Hex Strings¶
A hex string is always prefixed with “0x” and consists of the characters 0-9 and a-f. It is always returned lowercase with even length, but any hex string passed into a function may be any case and may be odd length.
- utils . hexlify ( numberOrBigNumberOrHexStringOrArrayish ) => hex
Converts any number, BigNumber, hex string, or Arrayish to a hex string. (Otherwise, throws an error)
- utils . isHexString ( value ) => boolean
Returns true if value is a valid hexstring.
- utils . hexDataLength ( hexString ) => number
Returns the length (in bytes) of hexString if it is a valid data hex string data (even length).
- utils . hexStripZeros ( hexString ) => hex
Returns hexString with all leading zeros removed, but retaining at least one nibble, even if zero (e.g.,
0x0). This may return an odd length string.- utils . hexZeroPad ( hexString , length ) => hex
Returns hexString padded (on the left) with zeros to length of bytes (each byte is two nibbles).
Signatures¶
There are two common formats for signatures in Manifold Finance. The flat-format, which is a hex string with 65 bytes (with recoveryParam); or 64 bytes (without recoveryParam); or an expanded-format, which is an object with the following properties:
r and s — the (r, s) public point of a signature
recoveryParam — the recovery parameter of a signautre (either
0or1)v — the recovery parameter nomalized (either
27or28)
- utils . splitSignature ( hexStringOrArrayishOrSignature ) => Signature
Returns an expanded-format signature object for hexStringOrArrayishOrSignature. Passing in an signature that is already in the expanded-format will ensure both recoveryParam and v are populated.
- utils . joinSignature ( signature [ , includeRecoveryParam ] ) => hex
Returns the flat-format signature hexstring of signature. The final v byte will always be normalized to
0x1bof0x1c. Optionally to include recovery parameter.
// Flat-format: this is the format provided by JSON-RPC responses
let flat = "0xd26c2cd5c6adb03046ac99e5d9badb798ca9b09f995191b5b906d6c26f8983e4" +
"1b7116df50a27a8c9e52fae512728ef75623da13320ca9b2e62ece0dcdd409e9" +
"1b";
let expanded = utils.splitSignature(flat);
console.log(expanded);
// { r: "0xd26c2cd5c6adb03046ac99e5d9badb798ca9b09f995191b5b906d6c26f8983e4",
// s: "0x1b7116df50a27a8c9e52fae512728ef75623da13320ca9b2e62ece0dcdd409e9",
// recoveryParam: 0,
// v: 27
// }
// Expanded-format: this is the format and other tools often require
let expanded = {
r: "0xd26c2cd5c6adb03046ac99e5d9badb798ca9b09f995191b5b906d6c26f8983e4",
s: "0x1b7116df50a27a8c9e52fae512728ef75623da13320ca9b2e62ece0dcdd409e9",
recoveryParam: 0,
v: 27
}
let flat = utils.joinSignature(expanded, true);
console.log(flat)
// "0xd26c2cd5c6adb03046ac99e5d9badb798ca9b09f995191b5b906d6c26f8983e4"
// "1b7116df50a27a8c9e52fae512728ef75623da13320ca9b2e62ece0dcdd409e91b"
UTF-8 Strings¶
- utils . toUtf8Bytes ( string ) => Uint8Array
Converts a UTF-8 string to a Uint8Array.
- utils . toUtf8String ( hexStringOrArrayish [ , ignoreErrors = false ] ) => string
Converts a hex-encoded string or array to its UTF-8 representation.
let text = "Hello Blockchain!";
let bytes = utils.toUtf8Bytes(text);
console.log(bytes);
// Uint8Array [ 72, 101, 108, 108, 111, 32, 66, 108, 111, 99, 107, 99, 104, 97, 105, 110, 33 ]
let array = [ 72, 101, 108, 108, 111, 32, 66, 108, 111, 99, 107, 99, 104, 97, 105, 110, 33 ];
let stringFromArray = utils.toUtf8String(array);
console.log(stringFromArray);
// "Hello Blockchain!"
let hexString = "0x48656c6c6f20426c6f636b636861696e21";
let stringFromHexString = utils.toUtf8String(hexString);
console.log(stringFromHexString);
// "Hello Blockchain!"