Utilities¶
The utility functions exposed in both the ethers umbrella package and the ethers-utils:
var utils = ethers.utils;
Big Numbers¶
A BigNumber is an immutable object which allow math operations to be carried out on numbers far larger than JavaScript can accurately handle. Many functions return these, so it is important to understand how to work with these.
- prototype . add ( otherValue )
- Return a new BigNumber of this plus otherValue
- prototype . sub ( otherValue )
- Return a new BigNumber of this minus otherValue
- prototype . mul ( otherValue )
- Return a new BigNumber of this times otherValue
- prototype . div ( otherValue )
- Return a new BigNumber of this divided by otherValue
- prototype . mod ( otherValue )
- Return a new BigNumber of this modulo otherValue
- prototype . eq ( otherValue )
- Return true if this is equal to otherValue
- prototype . lt ( otherValue )
- Return true if this is less than otherValue
- prototype . lte ( otherValue )
- Return true if this is less or equal to otherValue
- prototype . gt ( otherValue )
- Return true if this is greater than otherValue
- prototype . gte ( otherValue )
- Return true if this is greater than or equal to otherValue
- prototype . isZero ( )
- Return true if this is equal to zero
- prototype . toNumber ( )
- Return a JavaScript number representation; an error is thrown if the value is outside the safe range for JavaScript IEEE 754 64-bit floating point numbers
- prototype . toString ()
- Return a decimal string representation
- prototype . toHexString ( )
- Return a 0x prefixed hexidecimal representation
Creating Instances¶
- utils . bigNumberify ( value )
Returns a BigNumber instance of value. The value may be anything which can be reliably converted into a BigNumber:
- Decimal String
A string consisting of the decimal digits 0 through 9, optionally with a leading negative sign.
examples: utils.bigNumberify(“42”)
- Hex String
A hex string, witch has aa prefix of 0x and consisting of the hexidecimal digits 0 through 9 and a through f, case-insensitive. Must be non-negative.
examples: utils.bigNumberify(“0x2a”)
- JavaScript Numbers
Numbers must be within the safe range for JavaScript.
examples: utils.bigNumberify(42)
- Arrayish
Treats the arrayish as a big-endian encoded bytes representation.
examples: utils.bigNumberify([ 42 ])
- BigNumber
- Returns value, since a BigNumber is immutable.
Examples¶
var gasPriceWei = utils.bigNumberify("20902747399");
var gasLimit = utils.bigNumberify(3000000);
var maxCostWei = gasPriceWei.mul(gasLimit)
console.log("Max Cost: " + maxCostWei.toString());
// "Max Cost: 62708242197000000"
console.log("Number: " + maxCostWei.toNumber());
// throws an Error, the value is too large for JavaScript to handle safely
Ether Strings and Wei¶
- utils . etherSymbol
- The ethereum symbol (the Greek letter Xi )
- utils . parseEther ( etherString )
- Parse the etherString representation of ether into a BigNumber instance of the amount of wei.
- utils . formatEther ( wei [ , options ] )
- Format an amount of wei into a decimal string representing the amount of ether. The
options object supports the keys
commify
andpad
. The output will always include at least one whole number and at least one decimal place.
Examples¶
var wei = utils.parseEther('1000.0');
console.log(wei.toString(10));
// "1000000000000000000000"
console.log(utils.formatEther(0));
// "0.0"
var wei = utils.bigNumberify("1000000000000000000000");
console.log(utils.formatEther(wei));
// "1000.0"
console.log(utils.formatEther(wei, {commify: true}));
// "1,000.0"
console.log(utils.formatEther(wei, {pad: true}));
// "1000.000000000000000000" (18 decimal places)
console.log(utils.formatEther(wei, {commify: true, pad: true}));
// "1,000.000000000000000000" (18 decimal places)
Addresses¶
There are several formats available on the Ethereum network for addresses, and it is often useful to be able to convert between them.
- utils . getAddress ( address [ , generateIcap ] )
- Normalize an address to a checksum address, or as an ICAP address if generateIcap is true.
Examples¶
var address = "0xd115bffabbdd893a6f7cea402e7338643ced44a6";
var icapAddress = "XE93OF8SR0OWI6F4FO88KWO4UNNGG1FEBHI";
console.log('Checksum address: ' + utils.getAddress(address));
// "0xD115BFFAbbdd893A6f7ceA402e7338643Ced44a6"
console.log('Checksum address: ' + utils.getAddress(icapAddress));
// "0xD115BFFAbbdd893A6f7ceA402e7338643Ced44a6"
console.log('ICAP address:' + utils.getAddress(address, true));
// "XE93OF8SR0OWI6F4FO88KWO4UNNGG1FEBHI"
console.log('ICAP address:' + utils.getAddress(icapAddress, true));
// "XE93OF8SR0OWI6F4FO88KWO4UNNGG1FEBHI"
UTF-8 Strings¶
- utils . toUtf8Bytes ( string )
- Converts a UTF-8 string to a Uint8Array.
- utils . toUtf8String ( hexStringOrArrayish )
- Converts a hex-encoded string or array to its UTF-8 representation.
Examples¶
var text = "Hello World";
var bytes = utils.toUtf8Bytes(text);
console.log(bytes);
// Uint8Array [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
console.log(utils.toUtf8String(bytes));
// "Hello World"
var hexString = "0x48656c6c6f20576f726c64";
console.log(utils.toUtf8String(hexString));
// "Hello World"
Cryptographic Functions¶
- utils . keccak256 ( hexStringOrArrayish )
- Compute the keccak256 cryptographic hash of a value, returned as a hex string. (Note: often Ethereum refers to this, incorrectly, as SHA3)
- utils . sha256 ( hexStringOrArrayish )
- Compute the SHA2-256 cryptographic hash of a value, returned as a hex string.
- utils . randomBytes ( length )
- Return a Uint8Array of cryptographically secure random bytes
Examples¶
Hashing Binary Data
console.log(utils.keccak256([ 0x42 ]));
// '0x1f675bff07515f5df96737194ea945c36c41e7b4fcef307b7cd4d0e602a69111'
console.log(utils.keccak256("0x42"));
// '0x1f675bff07515f5df96737194ea945c36c41e7b4fcef307b7cd4d0e602a69111'
console.log(utils.sha256([ 0x42 ]));
// '0xdf7e70e5021544f4834bbee64a9e3789febc4be81470df629cad6ddb03320a5c'
console.log(utils.sha256("0x42"));
// '0xdf7e70e5021544f4834bbee64a9e3789febc4be81470df629cad6ddb03320a5c'
Hashing UTF-8 Strings
// Convert the string to binary data
var utf8Bytes = utils.toUtf8Bytes('Hello World');
console.log(utils.keccak256(utf8Bytes));
// '0x592fa743889fc7f92ac2a37bb1f5ba1daf2a5c84741ca0e0061d243a2e6707ba'
console.log(utils.sha256(utf8Bytes));
// '0xa591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e'
Random Bytes
console.log(utils.randomBytes(3));
// Uint8Array [ 194, 22, 140 ]
Arrayish¶
An arrayish object is any such that it:
- 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 [0, 255]
- utils . isArrayish ( object )
- Returns true if object can be treated as an arrayish object.
- utils . arrayify ( hexStringOrArrayish )
- Returns a Uint8Array of a hex string, BigNumber or of an Arrayish object.
- utils . concat ( arrayOfHexStringsAndArrayish )
- Return a Uint8Array of all arrayOfHexStringsAndArrayish concatenated.
- utils . padZeros ( typedUint8Array, length )
- Return a Uint8Array of typedUint8Array with zeros prepended to length bytes.
- utils . stripZeros ( hexStringOrArrayish )
- Returns a Uint8Array with all leading zero bytes striped.
Hex Strings¶
A hex string is always prefixed with “0x” and consists of the characters 0 – 9 and a – f. It is always returned lower case with even-length, but any hex string passed into a function may be any case and may be odd-length.
Contract Addresses¶
Every contract deployed on the Ethereum network requires an address (you can think of this as the memory address which the running application lives at). The address is generated from a cryptographic has of the address of the creator and the nonce of the transaction.
- utils . getContractAddress ( transaction )
- Computes the contract address a contract would have if this transaction
created a contract. (transaction requires only
from
andnonce
be defined)
Examples¶
// Ropsten: 0x5bdfd14fcc917abc2f02a30721d152a6f147f09e8cbaad4e0d5405d646c5c3e1
var transaction = {
from: '0xc6af6e1a78a6752c7f8cd63877eb789a2adb776c',
nonce: 0
};
console.log(utils.getContractAddress(transaction));
// "0x0CcCC7507aEDf9FEaF8C8D731421746e16b4d39D"